前回前々回で準備した環境を使用してESP32からパブリッシュするプログラムを作成します。

パソコンと接続

続いて、PCのUSBポートにESP-WROOM-32を接続します。

Arduino互換機版はシリアルボードとして認識されます。(UARTですね)
USBで電力供給とシリアル通信の両方を行います。
正常に認識されれば、しばらくするとArduino-IDEに接続したシリアルポートが表示されるようになります。
(表示されない場合は管理ツールなどでハードウェアの認識状態を確認してください)

WIFI接続

まず、WIFI接続の確認をしましょう。
シリアルポートが使用できる状態になったら、「ツール」⇒「シリアルモニタ」を選択して、シリアルモニタ画面を表示します。

「ファイル」⇒「スケッチ例」⇒「WiFi」⇒「SimpleWiFiServer」を選択すると、WIFI接続のサンプルが表示されます。

30行目、31行目のSSID、パスワードを接続するWIFIアクセスポイントに合わせて書き換えて、書込みボタンでESP-WROOM-32に書き込みます。

iPhoneを使用して接続する場合は、SSIDにiPhone名、パスワードはインターネット共有画面の「”Wi-Fi”のパスワード」を設定します。

ENボタンを押しながらでないと書き込めないとか言われていましたが、通常のArduinoと同様、何もせず書き込みできました。

書き込みが完了するとプログラムが実行されます。
WIFI接続がうまくいくとシリアルモニターに以下のように表示されます。

サンプルソースはESP-WROOM-32がWebServerとなるプログラムになっています。

シリアルモニタに表示されたURLをブラウザで開くと画面が表示され、リンクをクリックするとGPIO5にLEDが接続されていれば光ったり消えたりするようです。

今回はWIFIの接続確認なので、IPアドレスが正常に割り振られ、HTMLが表示されればOKです。

デバイス組み立て

まずは、簡単にデバイスの準備をします。

fritzing

ブレッドボードにESP-WROOM-32を装着、3V電源とGRDを結線します。
GPIO34,32,25,12に緑LED、青LED、赤LED、ボタンをそれそれ結線、ボタンの反対側をGNDに結線します。

使用する開発ボードによってピン配置は異なります。

ピン番号は使いやすいものに変えても問題ありません。

通常のブレッドボードだと片方のGPIOが使えなくなってしまいます。
最近のESP32開発ボードは少し細く作れれていて両側使えるものも多くなってきました。

いよいよ、パブリッシュ

WIFI接続がうまくいったら、いよいよパブリッシュします。

プログラムは以下の通り。

/*
 WiFi Web Server LED Blink

 A simple web server that lets you blink an LED via the web.
 This sketch will print the IP address of your WiFi Shield (once connected)
 to the Serial monitor. From there, you can open that address in a web browser
 to turn on and off the LED on pin 5.

 If the IP address of your shield is yourAddress:
 http://yourAddress/H turns the LED on
 http://yourAddress/L turns it off

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 Circuit:
 * WiFi shield attached
 * LED attached to pin 5

 created for arduino 25 Nov 2012
 by Tom Igoe

ported for sparkfun esp32 
31.01.2017 by Jan Hendrik Berlin
 
 */

#include <WiFi.h>

const char* ssid     = "yourssid";
const char* password = "yourpasswd";

WiFiServer server(80);

void setup()
{
    Serial.begin(115200);
    pinMode(5, OUTPUT);      // set the LED pin mode

    delay(10);

    // We start by connecting to a WiFi network

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected.");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
    
    server.begin();

}

int value = 0;

void loop(){
 WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,
    Serial.println("New Client.");           // print a message out the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        if (c == '\n') {                    // if the byte is a newline character

          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println();

            // the content of the HTTP response follows the header:
            client.print("Click <a href=\"/H\">here</a> to turn the LED on pin 5 on.<br>");
            client.print("Click <a href=\"/L\">here</a> to turn the LED on pin 5 off.<br>");

            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            break;
          } else {    // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }

        // Check to see if the client request was "GET /H" or "GET /L":
        if (currentLine.endsWith("GET /H")) {
          digitalWrite(5, HIGH);               // GET /H turns the LED on
        }
        if (currentLine.endsWith("GET /L")) {
          digitalWrite(5, LOW);                // GET /L turns the LED off
        }
      }
    }
    // close the connection:
    client.stop();
    Serial.println("Client Disconnected.");
  }
}

SSID、パスワードは先ほどと同じように書き換えてください。
SSL通信を行うので、AWSからダウンロードした、ルートCA、”xxxxxxxxxx-certificate.pem.crt”、””を使用した認証処理を行う必要があります。
「ESP32でAWS-IoTしてみた(1)」でダウンロードした、ルートCA、”xxxxxxxxxx-certificate.pem.crt”、””、をテキストエディタで開き、内容を各所にコピーしてください。

-----BEGIN CERTIFICATE-----
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
.
.
.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-----END CERTIFICATE-----

↓コピー

const char* test_root_ca= \
     "-----BEGIN CERTIFICATE-----\n" \
     "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
     "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
     .
     .
     .
     "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
     "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
     "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
     "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
     "-----END CERTIFICATE-----\n";

コピーするときには2つ注意が必要です。

  • 各行に改行コード(\n)を付ける
  • 上記の改行コード(\n)を含む各行をダブルコーテーション(“)でくくり、そのあとに円マーク(\)を付ける

パブリッシュ先は”shadow/get”としていますので、shadowの内容が取得されます。
shadowの内容はAWS-IoTコンソールから、「管理」⇒「モノ」で対象のものを選択、「シャドー」を選択すると確認できます。

ちなみに、AWS-IoTコンソールから、「管理」⇒「モノ」で対象のものを選択、「操作」を選択すると”shadow/get”以外のパブリッシュのアドレスが確認できます。
“shadow/push”を行うとshadowの内容を書き換えることもできます。

では、プログラムをESP-WROOM-32に書き込んで実行してみましょう。

書き込みがうまくいくとWIFI接続を行い、結果がシリアルモニターに表示されます。
ではボタンを押してパブリッシュしましょう。
一瞬、緑LEDが点灯(ほとんど見えませんが)して、青LEDが点灯⇒消灯すれば処理は完了です。
shadowの内容がシリアルモニターに表示され、設定したメールアドレスにメールが飛べば成功です。

まとめ

今回はESP32からAWS-IoTにパブリッシュしました。
パブリッシュ先を”shadow/get”としましたが、本当は任意のトピックにパブリッシュしたいと考えていました。
いろいろとトライしたのですがうまくいかず、やむを得ずという感じです。
AWS-IoTの仕組みなどがまだ理解しきれていないので、もう少し掘り下げてみないといけないと思っています。
今後以下のような課題にも取り組みたいと思っています。

  • Lambdaを実装してサブクライブ
  • DynamoDBに登録
  • ESP32にサブクライブ

おつかれさまでした。