One ESP client and other one server
Server send back what it receives from client
Server :
/* Udp Server
* Send back what it receive from client
*/
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
WiFiUDP Udp;
char packetBuffer[128];
unsigned int localPort = 9999;
const char *ssid = "ESP8266 Thing";
const char *password = "xxxxxxxxx";
bool tickerOccured;
void setup() {
Serial.begin(115200);
WiFi.softAP(ssid, password);
Udp.begin(localPort);
}
void loop() {
int packetSize = Udp.parsePacket();
if (packetSize) {
int len = Udp.read(packetBuffer, 255);
if (len > 0) packetBuffer[len-1] = 0;
Serial.print("Received : ");
Serial.println(packetBuffer);
Udp.beginPacket(Udp.remoteIP(),Udp.remotePort());
Udp.write(packetBuffer);
Udp.write("\r\n");
Udp.endPacket();
}
}
Client :
// udp client
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <SoftwareSerial.h>
#include <Ticker.h>
Ticker ticker;
WiFiUDP Udp;
const char *ssid = "ESP8266 Thing";
const char *password = "nardino26";
bool tickerOccured = false;
char packetBuffer[255];
unsigned int localPort = 9999;
IPAddress ipServer(192, 168, 4, 1);
IPAddress ipClient(192, 168, 4, 10);
IPAddress Subnet(255, 255, 255, 0);
void ticker_handler(){
tickerOccured = true;
}
void setup() {
Serial.begin(115200);
ticker.attach(1, ticker_handler);
WiFi.begin(ssid, password);
WiFi.mode(WIFI_STA); // STA important !!!
WiFi.config(ipClient, ipServer, Subnet);
Udp.begin(localPort);
delay(200);
}
void loop() {
//**************** Send to server**********************************************************
Udp.beginPacket(ipServer,9999);
char sbuf[128];
unsigned long testID = millis();
sprintf(sbuf, "%lu", testID);
Udp.write(sbuf);
Udp.write("\r\n");
Udp.endPacket();
Serial.print("S : ");Serial.println(sbuf);
delay(70);
//***************** Receive from server ****************************************************
int packetSize = Udp.parsePacket();
if (packetSize) {
int len = Udp.read(packetBuffer, 255);
if (len > 0) packetBuffer[len-1] = 0;
Serial.print("R : ");
Serial.println(packetBuffer);
}
Serial.println();
if (tickerOccured) {
Serial.println ("ticker occured"); // Testing ticker
tickerOccured = false;
}
delay(2);
}
Salutations