ESP8266 tcp透传AP+STA

匿名 (未验证) 提交于 2019-12-02 23:34:01

AP

建立WIFI,接受STA连接,串口数据和TCP互传

#include <ESP8266WiFi.h>    const char *ssid = "esp8266_666"; const char *password = "12345678"; WiFiServer server(8266); void setup() {   Serial.begin(115200);   Serial.println();   Serial.print("Setting soft-AP ... ");      IPAddress softLocal(192,168,1,1);   IPAddress softGateway(192,168,1,1); IPAddress softSubnet(255,255,255,0);    WiFi.softAPConfig(softLocal, softGateway, softSubnet);   WiFi.softAP(ssid, password);      IPAddress myIP = WiFi.softAPIP();   Serial.print("AP IP address: ");   Serial.println(myIP);  server.begin();  Serial.printf("Web server started, open %s in a web browser\n", WiFi.localIP().toString().c_str());    }    void loop() {  WiFiClient client = server.available();  if (client)   {     Serial.println("\n[Client connected]");     while (client.connected())     {    //  将串口数据打印给TCP   if(Serial.available()){     size_t len = Serial.available();     uint8_t sbuf[len];     Serial.readBytes(sbuf, len);         client.write(sbuf, len);     delay(1);           }                 // 将TCP数据打印给串口       if (client.available())       {         String line = client.readStringUntil('\r');         Serial.println(line);                      }     }     delay(1);     //  client.stop();     Serial.println("[Client disonnected]");   }     }    

  

STA

连接WIFI,连接AP,串口数据互传

#include <ESP8266WiFi.h>  const char* ssid = "esp8266_666"; const char* password = "12345678";  const char* host = "192.168.1.1";   const int httpPort = 8266;    IPAddress staticIP(192,168,1,22); IPAddress gateway(192,168,1,1); IPAddress subnet(255,255,255,0);  WiFiClient client;   void setup(void) {   Serial.begin(115200);   Serial.println();    Serial.printf("Connecting to %s\n", ssid);   WiFi.config(staticIP, gateway, subnet);   WiFi.begin(ssid, password);   while (WiFi.status() != WL_CONNECTED)   {     delay(500);     Serial.print(".");   }   Serial.println();   Serial.print("Connected, IP address: ");   Serial.println(WiFi.localIP());        if (!client.connect(host, httpPort)) {     Serial.println("connection failed");     return;   }     }  void loop() {               client.print("abc\r");     delay(1000);    while(client.available()){     String line = client.readStringUntil('\r');     Serial.print(line);   }      } 

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!