我想从计算机发送广播消息,然后从ESP32答复它 我正在设法接收广播消息,但是我无法发送回复消息(我在计算机的线缆中看不到它)
我使用了Internet上的流行版本,因此代码应该没问题,但我不明白这是怎么回事。
我对Arduino相当陌生,所以我不太了解所有方面
这是我正在运行的代码。
值得一提的是,我正在iPhone热点上运行计算机和ESP32 wifi。
我试图将UDP消息从ESP32发送到自身,并且它起作用了,所以问题应该是ESP32无法将消息发送到网络。
#include "WiFi.h"
#define led 2
#include <Thread.h>
#include <WiFiUdp.h>
const char* ssid = "ssid";
const char* password = "password";
char packetBuffer[255];
WiFiUDP Udp;
WiFiServer wifiServer(10100);
Thread myThread = Thread();
void setup() {
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
Serial.begin(115200);
myThread.enabled = true;
myThread.setInterval(10);
myThread.ThreadName = "myThread tag";
myThread.onRun(listen_broad);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
Serial.println(WiFi.localIP());
wifiServer.begin();
Udp.begin(10100);
}
void listen_broad(){
int packetSize = Udp.parsePacket();
if (packetSize){
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(", port ");
Serial.println(Udp.remotePort());
int len = Udp.read(packetBuffer, 255);
if (len > 0) packetBuffer[len] = 0;
Serial.println("Contents:");
Serial.println(packetBuffer);
// send a reply, to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
int i = 0;
char ReplyBuffer[] = "ACK";
while (ReplyBuffer[i] != 0)
Udp.write((uint8_t)ReplyBuffer[i++]);
Udp.endPacket();
}
}
void loop() {
if(myThread.shouldRun()){
myThread.run();
}
WiFiClient client = wifiServer.available();
if (client) {
client.write("nonono");
while (client.connected()) {
while (client.available()>0){
char c = client.read();
Serial.write(c);
switch (c) {
case '1':
//TOGGLE LIGHT//
if(digitalRead(led)){
Serial.write("Turning OFF");
digitalWrite(led, LOW);
}
else{
Serial.write("Turning ON");
digitalWrite(led, HIGH);
}
break;
/////////////////
case '2':
//CLOSE////////
client.stop();
break;
////////////////
default:
Serial.write("DEF");
break;
}
}
delay(10);
}
Serial.println("Client disconnected");
}
}