概要
wemos d1で、alexaデバイスを作ってみる。
練習問題、やってみた。
練習問題
udpで、オウム返し、エコーバックを作れ。
方針
- ルーターに、入る。
- シリアルは、115200。
- ポートは、49152番。
サンプルコード
#include <ESP8266WiFi.h>
#include <WiFiUDP.h>
const char * ssid = "****";
const char * password = "****";
static WiFiUDP udp;
#define LOCAL_PORT 0xC000
#define REMOTE_PORT 0xC001
IPAddress localIP;
IPAddress remoteIP;
void setup() {
Serial.begin(115200);
delay(100);
boolean state = true;
int i = 0;
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
Serial.println("Connecting to WiFi");
Serial.print("Connecting ...");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
if (i > 10)
{
state = false;
break;
}
i++;
}
if (state)
{
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
else
{
Serial.println("");
Serial.println("Connection failed.");
}
udp.begin(LOCAL_PORT);
}
void loop() {
char packetBuffer[256];
int packetSize = udp.parsePacket();
if (packetSize)
{
int len = udp.read(packetBuffer, packetSize);
if (len > 0)
packetBuffer[len] = '\0';
remoteIP = udp.remoteIP();
Serial.print(remoteIP);
Serial.print(" / ");
Serial.println(packetBuffer);
udp.beginPacket(remoteIP, REMOTE_PORT);
udp.write(packetBuffer);
udp.endPacket();
}
}
実行結果
Connecting to WiFi
Connecting ..........
Connected to ****
IP address: 192.168.0.104
192.168.0.102 / hello
以上。