/*
* ESP8266 WiFi(UDP) <-> UART Bridge
* ESP8266 TX of Serial1 is GPIO2
*/
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
const char* ssid = "**********";
const char* password = "**********";
WiFiUDP Udp;
unsigned int localUdpPort = 4210; // local port to
listen on
char incomingPacket[255]; // buffer for incoming
packets
#define bufferSize 8192
uint8_t buf[bufferSize];
uint8_t iofs=0;
IPAddress remoteIp(255,255,255,255);
unsigned int remotePort = 4210;
#define BAUDRATE 9600
void setup()
{
delay(1000);
Serial1.begin(115200); // Debug Print
Serial.begin(BAUDRATE);
Serial1.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial1.print(".");
}
Serial1.println(" connected");
Udp.begin(localUdpPort);
Serial1.printf("Now listening at IP %s, UDP port %d
BaudRate=%d\n",
WiFi.localIP().toString().c_str(), localUdpPort,
BAUDRATE);
}
void loop()
{
int packetSize = Udp.parsePacket();
if (packetSize)
{
// receive incoming UDP packets
Serial1.printf("Received %d bytes from
%s, port %d\n", packetSize,
Udp.remoteIP().toString().c_str(), Udp.remotePort());
int len = Udp.read(incomingPacket,
255);
if (len > 0)
{
incomingPacket[len] = 0;
}
Serial1.printf("UDP packet contents:
%s\n", incomingPacket);
Serial.print(incomingPacket);
//送信先を固定する場合は以下の2行のコメントを外す
//応答してきた相手だけにUDP送信する
// remoteIp = Udp.remoteIP(); // store
the ip of the remote device
// remotePort = Udp.remotePort(); //
store the port of the remote device
}
if(Serial.available()) {
while(1) {
if(Serial.available()) {
buf[iofs] =
(char)Serial.read(); // read char from UART
if(iofs<bufferSize-1) {
iofs++;
} else {
Serial1.println("Buffer Over Run");
}
} else {
break;
}
}
// now send to WiFi
Udp.beginPacket(remoteIp, remotePort);
// remote IP and port
int byte = Udp.write(buf, iofs);
if (byte != iofs) Serial1.println("UDP
write fail");
Udp.endPacket();
iofs = 0;
}
}
|