著者:すずきひろのぶ
前回は、Arduino IDEを使って、中国Espressif Systems社のSoC「ESP32」を搭載する開発ボード「ESP32-DevKitC v2」で動作するサンプルプログラムを作成しました。今回は、前回作成したサンプルプログラムを省電力化してみます。
シェルスクリプトマガジン Vol.57は以下のリンク先でご購入できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
// Hironobu SUZUKI // <suzuki.hironobu@gmail.com> // SUZULABO #include <WiFi.h> #include <WiFiUdp.h> #define SENDBUFSIZE 32 #define SLEEPTIME 3 char ssid[] = "XXXXX"; char pass[] = "XXXXXX"; const char remoteIpAddr[] = "192.168.1.3"; const int port = 21231; uint8_t sendBuffer[SENDBUFSIZE]; int counter = 1; int WiFiStatus = WL_IDLE_STATUS; WiFiUDP udp; void setup() { Serial.begin(115200); WiFiConnectionManage(); udp.begin(port); } void loop() { for (int j = 0; j < SENDBUFSIZE; j++) { sendBuffer[j] = 0; } sendBuffer[0] = counter; sendBuffer[1] = '\0'; WiFiConnectionManage(); udp.beginPacket(remoteIpAddr, port); udp.write(sendBuffer, sizeof(sendBuffer)); udp.endPacket(); Serial.println(counter++); delay(500); if ( counter > 30 ) { system_deep_sleep(10 * 1000000); } } void WiFiConnectionManage() { int connection_error = 0; if ( (WiFiStatus = WiFi.status()) == WL_NO_SHIELD) { WiFiStatus = WL_IDLE_STATUS; } switch (WiFiStatus) { case WL_CONNECT_FAILED: // disconnect -> build connection WiFi.disconnect(); case WL_DISCONNECTED: // build connection case WL_IDLE_STATUS: // build connection Serial.print("WiFi Status: "); Serial.println(WiFiStatus); Serial.print("Attempting to WiFi connection SSID: "); Serial.println(ssid); while ( true ) { WiFiStatus = WiFi.begin(ssid, pass); if ( WiFiStatus == WL_CONNECTED ) { break; } delay(10000); if ( connection_error > 6 ) { // Too many connection error why? reboot. ESP.restart(); } connection_error++; } Serial.println("WiFi Connection Complete."); delay(10000); printWifiStatus(); break; case WL_CONNECTION_LOST: // lost -> try reconnection Serial.println("Try WiFi reconnect"); WiFi.reconnect(); break; default: break; } } void printWifiStatus() { String myssid; while (true) { myssid = WiFi.SSID(); if (myssid != "" ) { break; } delay(3000); } Serial.print("SSID: "); Serial.println(myssid); IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); } |
1 2 3 4 5 |
if ( counter > 30 ) { esp_sleep_enable_timer_wakeup(10*1000000); esp_light_sleep_start(); counter = 0; } |