M2X でESP8266のWiFiモジュールをIoTデバイスに使用する方法を説明します。
※「ESP8266でIoT - 開発環境のセットアップ」の手順で開発環境をセットアップ済のこととします。
○準備
①「Arduino+M2XでIoT」の「②M2Xの準備」の手順でデバイスとストリームを作成します。
②「AT&T's M2X Android Client」ライブラリをダウンロードします。
③ダウンロードしたZIPファイルを解凍し、「M2XStreamClient」フォルダをArduino IDEのライブラリフォルダ(「Users\<ユーザー名>\Documents\Arduino\libraries」)にコピーします。
○プログラム(スケッチ)
M2Xにデータを送信するプログラムは、次のように書きます。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ESP8266WiFi.h> | |
#define ESP8266_PLATFORM | |
#include "M2XStreamClient.h" | |
char ssid[] = "<ssid>"; // your network SSID (name) | |
char pass[] = "<WPA password>"; // your network password (use for WPA, or use as key for WEP) | |
int keyIndex = 0; // your network key Index number (needed only for WEP) | |
int status = WL_IDLE_STATUS; | |
char deviceId[] = "<device id>"; // Device you want to push to | |
char streamName[] = "<stream name>"; // Stream you want to push to | |
char m2xKey[] = "<M2X access key>"; // Your M2X access key | |
WiFiClient client; | |
M2XStreamClient m2xClient(&client, m2xKey); | |
void setup() { | |
Serial.begin(115200); | |
while (status != WL_CONNECTED) { | |
Serial.print("Attempting to connect to SSID: "); | |
Serial.println(ssid); | |
// Connect to WPA/WPA2 network. Change this line if using open or WEP network: | |
status = WiFi.begin(ssid, pass); | |
// wait 10 seconds for connection: | |
delay(10000); | |
} | |
Serial.println("Connected to wifi"); | |
printWifiStatus(); | |
} | |
void loop() { | |
float val = analogRead(A0); | |
Serial.print("value: "); | |
Serial.print(val); | |
int response = m2xClient.updateStreamValue(deviceId, streamName, val); | |
Serial.print("M2x client response code: "); | |
Serial.println(response); | |
if (response == -1) while(1) ; | |
delay(5000); | |
} | |
void printWifiStatus() { | |
// print the SSID of the network you're attached to: | |
Serial.print("SSID: "); | |
Serial.println(WiFi.SSID()); | |
// print your WiFi shield's IP address: | |
IPAddress ip = WiFi.localIP(); | |
Serial.print("IP Address: "); | |
Serial.println(ip); | |
// print the received signal strength: | |
long rssi = WiFi.RSSI(); | |
Serial.print("signal strength (RSSI):"); | |
Serial.print(rssi); | |
Serial.println(" dBm"); | |
} |
0 件のコメント:
コメントを投稿