ESP8266 UDP serial port transparent transmission


foreword

When using ESP8266 for development, I often just want to use its wireless transmission function, and I wonder if I can write a UDP-based serial port transparent transmission, which can be used as a master control such as STM32 for development, and realize wireless transmission to the host computer.

Directly on the code, it is relatively simple

IDE : Arduino

#include <ESP8266WiFi.h>
#include <WiFiUDP.h>
unsigned int UDPPort = 4120;      // local port to listen on
char packetBuffer[255]; //buffer to hold incoming packet
char  ReplyBuffer[] = "acknowledged";       // a string to send back
WiFiUDP Udp;
// 复位或上电后运行一次:
void setup() {
    
    
        //在这里加入初始化相关代码,只运行一次:
        Serial.begin(115200);  
        WiFi.softAP("Wi-Fi");
        //可以在这里设计AP端的其他东西
        Udp.begin(UDPPort);
}
//发送函数
void send(){
    
    
  if (Serial.available())//串口读取到的转发到服务器,因为串口是一位一位的发送所以在这里缓存完再发送
  {
    
    
    size_t counti = Serial.available();
    uint8_t sbuf[counti];
    Serial.readBytes(sbuf, counti);
    Udp.beginPacket("192.168.4.2", 8080);//只需对此处进行修改,需要发送的ip及端口
    Udp.write(sbuf,counti);
    Udp.endPacket();
  }
}
 
//一直循环执行:
void loop() {
    
    
  		send();
        // 在这里加入主要程序代码,重复执行:
        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());
                 
                // read the packet into packetBufffer
                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());
                Udp.write(ReplyBuffer);
                Udp.endPacket();
        }
}


Steps for usage

1. Connect the computer and mobile phone to the open AP of ESP8266
2. Set the local ip and port through the network debugging assistant on the mobile phone and computer, and the ip and port of the remote host
can perform serial port transparent transmission

Summarize

The code is very simple, it just realizes the transparent transmission of the serial port (there may be problems, but I won't delve into it, just write and play), and then add TCP and its mode switching to become more comprehensive.

Guess you like

Origin blog.csdn.net/qq_42866708/article/details/121823732