Please help with the following question:
The first ESP32 module is the AP server, and the other two are its clients (clients have the same source code).
One client receives the IP address 192.168.4.2, and the second - 192.168.4.3.
The client who first connected to the server and received the ip address 192.168.4.2 receives the message from the "OnLED" server, and the client who received the address 192.168.4.3 does not receive the message.
How can I write code on the server so that I can send messages to all clients at the same time and how can I write code so that I can send messages to specific IP addresses?
Thank you so much!
I enclose the code:
________________________________________
SERVER:
Code: Select all
// AP Server
#include <WiFi.h>
const int LED_PIN = 16;
// Replace with your network credentials
const char* ssid = "ESP32-Access-Point";
const char* password = "ESP32accesspoint";
WiFiServer server(80);
void setup() {
Serial.begin(115200);
delay(1000); // даем время на запуск последовательной коммуникации
Serial.println("Setting AP (Access Point)…");
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
delay(100);
digitalWrite(LED_PIN, HIGH);
WiFi.softAP(ssid, password);
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address ");
Serial.println(IP);
Serial.print("MAC address ");
Serial.println(WiFi.softAPmacAddress());
server.begin();
}
void loop() {
WiFiClient client = server.available(); //Listen for incoming clients
if (client)
{ //If a new client connects,
Serial.println("New Client."); //print a message out in the serial port
while (client.connected())
{
Serial.println("Client connected.");
Serial.println(client.available());
if (client.available() > 0)
{
// read the bytes incoming from the client:
char answer = client.read();
// echo the bytes back to the client:
server.write(answer);
client.println("OnLED\r");
}
}
client.stop();
Serial.println("Client disconnected.");
digitalWrite(LED_PIN, LOW);
delay(5000);
digitalWrite(LED_PIN, HIGH);
}
}
Client:
Code: Select all
//Client
#include <ESP8266WiFi.h>
const int ledPin = 16;
const char* ssid = "ESP32-Access-Point";
const char* password = "ESP32accesspoint";
String fromServer;
WiFiClient client;
IPAddress server(192, 168, 4, 1);
void setup()
{
Serial.begin(115200);
delay(1000);
Serial.println();
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
delay(100);
digitalWrite(ledPin, LOW);
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
}
void loop()
{
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("connecting...");
if (client.connect(server, 80))
{
Serial.println("connected to server");
Serial.println(WiFi.localIP());
client.write("data");
fromServer = client.readStringUntil('\r');
Serial.println(fromServer);
if (fromServer == "OnLED") {
digitalWrite(ledPin, HIGH);
delay(5000);
digitalWrite(ledPin, LOW);
}
else {
digitalWrite(ledPin, LOW);
}
}
else
{
Serial.println("failed to connect to server");
}
delay(1000);
}