ESP8266 UDP串口透传


前言

在使用ESP8266进行开发时,往往只是想使用其无线传输功能,就想着能不能写一个基于UDP的串口透传,可以作为STM32等主控进行开发时,实现无线传输给上位机

直接上代码,比较简单

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();
        }
}


使用步骤

1、电脑、手机连接其ESP8266开放的AP端
2、通过手机、电脑上的网络调试助手,设置本机ip及端口,远程主机的ip及端口
即可进行串口透传

总结

代码很简单,只是实现了串口的透传(可能存在问题,但也不深究了,写着玩玩),之后再加入TCP及其模式的切换,变得全面一些。

猜你喜欢

转载自blog.csdn.net/qq_42866708/article/details/121823732