ESP32/ESP8266 使用WIFI模块进行UDP通信 - 米思齐/Arduino

使用UDP协议, 进行通信

  • ESP32以AP模式运行
  • ESP8266以STA模式运行
  • ESP8266每五秒发送"hello"
  • ESP32实时接受ESP8266发送的消息

注意 

  • 使用WiFi时, ADC2模拟通道无法使用
  • ADC2 10个通道:GPIO0、GPIO2、GPIO4、GPIO12-GPIO15、GOIO25-GPIO27
  • ADC1 8通道:GPIO32 - GPIO39

ESP - Ap 接收端

ESP32/ESP8266 使用WIFI模块进行UDP通信 - 米思齐/Arduino_第1张图片

#include 
#include 

const char AP_NameChar[] = "WIFI-SSID";
const char WiFiAPPSK[] = "WIFI-PSK";
IPAddress ESP8266ip1(192,168,4,2);
IPAddress ESP8266ip2(192,168,4,3);
IPAddress ESP8266ip(192,168,4,255);
unsigned int localPort =8080;
unsigned int remotePort=8080;
char incomingPacket[537];
char A;
WiFiUDP Udp;

void setup(){
    Serial.begin(9600);
    WiFi.mode(WIFI_AP);
    WiFi.softAP(AP_NameChar, WiFiAPPSK);
    Udp.begin(localPort);
    Serial.println();
    Serial.println("Started ap. Local ip: " + WiFi.softAPIP().toString());
    Serial.begin(9600);
}

void loop(){
    int packetSize = Udp.parsePacket();
    if (packetSize)
    {
        Serial.printf("Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
        int len = Udp.read(incomingPacket, 536);
        if (len > 0)
        {
            incomingPacket[len] = 0;
            Serial.printf("UDP packet contents: %s\n", incomingPacket);
            String COM=incomingPacket;
            Serial.println(COM);
        }
    }

}

ESP - STA 发送端

ESP32/ESP8266 使用WIFI模块进行UDP通信 - 米思齐/Arduino_第2张图片

#define STASSID "WIFI-SSID"
#define STAPSK "WIFI-PSK"
#include 
#include 
#include 

unsigned int localPort =8080;
unsigned int remotePort=8080;
char incomingPacket[537];
char A;
WiFiUDP Udp;

void setup(){
    Serial.begin(9600);
    WiFi.mode(WIFI_STA);
    WiFi.begin(STASSID, STAPSK);
    while (WiFi.status() != WL_CONNECTED)
        {
            Serial.print(".");
            delay(500);
        }
    delay(1000);
    Serial.println();
    Serial.print("Connected! IP address: ");
    Serial.println(WiFi.localIP());
    Serial.printf("UDP server on port  ", localPort);
    Udp.begin(localPort);
    Serial.begin(9600);
    Serial.print(WiFi.localIP());
}

void loop(){
    Udp.beginPacket("192.168.4.1",remotePort);
    Udp.print("hello");
    Udp.endPacket();
    delay(5000);

}

你可能感兴趣的:(ESP8266,ESP32,米思齐,udp,网络,网络协议,单片机)