zoukankan      html  css  js  c++  java
  • ESP-手机--双向通信模式

    1 AP 接受手机

    2 STA(密码固定)连接路由器,AP接受手机

    3 STA(密码灵活)连接路由器,AP接受手机

    1 AP 接受手机

    #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,4,1);   
    IPAddress softGateway(192,168,4,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
    ", WiFi.localIP().toString().c_str());
     
    }
     
    void loop()
    {
     WiFiClient client = server.available();
     if (client)
      {
        Serial.println("
    [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('
    ');
            Serial.print(line);      
          }
        }
        delay(1); 
    
        client.stop();
        Serial.println("[Client disonnected]");
      }
     
     }
     
    

      

    2 STA(密码固定)连接路由器,AP接受手机

    /* 
      WiFiTelnetToSerial - Example Transparent UART to Telnet Server for esp8266
    
      Copyright (c) 2015 Hristo Gochkov. All rights reserved.
      This file is part of the ESP8266WiFi library for Arduino environment.
     
      This library is free software; you can redistribute it and/or
      modify it under the terms of the GNU Lesser General Public
      License as published by the Free Software Foundation; either
      version 2.1 of the License, or (at your option) any later version.
    
      This library is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      Lesser General Public License for more details.
    
      You should have received a copy of the GNU Lesser General Public
      License along with this library; if not, write to the Free Software
      Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    */
    #include <ESP8266WiFi.h>
    
    //how many clients should be able to telnet to this ESP8266
    #define MAX_SRV_CLIENTS 1
    const char* ssid = "**********";
    const char* password = "**********";
    
    WiFiServer server(23);
    WiFiClient serverClients[MAX_SRV_CLIENTS];
    
    void setup() {
      Serial1.begin(115200);
      WiFi.begin(ssid, password);
      Serial1.print("
    Connecting to "); Serial1.println(ssid);
      uint8_t i = 0;
      while (WiFi.status() != WL_CONNECTED && i++ < 20) delay(500);
      if(i == 21){
        Serial1.print("Could not connect to"); Serial1.println(ssid);
        while(1) delay(500);
      }
      //start UART and the server
      Serial.begin(115200);
      server.begin();
      server.setNoDelay(true);
      
      Serial1.print("Ready! Use 'telnet ");
      Serial1.print(WiFi.localIP());
      Serial1.println(" 23' to connect");
    }
    
    void loop() {
      uint8_t i;
      //check if there are any new clients
      if (server.hasClient()){
        for(i = 0; i < MAX_SRV_CLIENTS; i++){
          //find free/disconnected spot
          if (!serverClients[i] || !serverClients[i].connected()){
            if(serverClients[i]) serverClients[i].stop();
            serverClients[i] = server.available();
            Serial1.print("New client: "); Serial1.print(i);
            continue;
          }
        }
        //no free/disconnected spot so reject
        WiFiClient serverClient = server.available();
        serverClient.stop();
      }
      //check clients for data
      for(i = 0; i < MAX_SRV_CLIENTS; i++){
        if (serverClients[i] && serverClients[i].connected()){
          if(serverClients[i].available()){
            //get data from the telnet client and push it to the UART
            while(serverClients[i].available()) Serial.write(serverClients[i].read());
          }
        }
      }
      //check UART for data
      if(Serial.available()){
        size_t len = Serial.available();
        uint8_t sbuf[len];
        Serial.readBytes(sbuf, len);
        //push UART data to all connected telnet clients
        for(i = 0; i < MAX_SRV_CLIENTS; i++){
          if (serverClients[i] && serverClients[i].connected()){
            serverClients[i].write(sbuf, len);
            delay(1);
          }
        }
      }
    }
    

      

    3 STA(密码灵活)连接路由器,AP接受手机

    /**
    * 日期:2017/09/19
    * 功能:wifi lamp 8266端
    *       加入SmartConfig功能
    * 作者:单片机菜鸟
    **/
    #include <ESP8266WiFi.h>
    #include <EEPROM.h>
     
    #define MAX_SRV_CLIENTS 3   //最大同时联接数,即你想要接入的设备数量,8266tcpserver只能接入五个,哎
    #define led 2
    #define DEBUG //是否开启debug功能
     
    #ifdef DEBUG
    #define DebugPrintln(message)    Serial.println(message)
    #else
    #define DebugPrintln(message)
    #endif
     
    #ifdef DEBUG
    #define DebugPrint(message)    Serial.print(message)
    #else
    #define DebugPrint(message)
    #endif
       
    const char* ssid     = "360wifilulu";         // XXXXXX -- 使用时请修改为当前你的 wifi ssid
    const char* password = "6206908you11011010";         // XXXXXX -- 使用时请修改为当前你的 wifi 密码
       
    const unsigned long BAUD_RATE = 115200;                   // serial connection speed
    const unsigned long HTTP_TIMEOUT = 5000;               // max respone time from server
       
    WiFiServer server(8266);//你要的端口号,随意修改,范围0-65535
    WiFiClient serverClients[MAX_SRV_CLIENTS];
     
    //ssid和密码结构体
    struct config_type{
      char ssid[32];
      char psw[64];
    };
     
    config_type config;
    int flag = HIGH;//默认当前灭灯
       
    /**
    * @Desc 初始化操作
    */
    void setup() {
      Serial.begin(BAUD_RATE);
      pinMode(led,OUTPUT);
      digitalWrite(led, HIGH);
     
      if(!autoConfig()){
        smartConfig();
        DebugPrint("Connecting to ");//写几句提示,哈哈
        DebugPrintln(ssid);
        while (WiFi.status() != WL_CONNECTED) {
        //这个函数是wifi连接状态,返回wifi链接状态
           delay(500);
           DebugPrint(".");
        }
      }
       
      delay(1000);
      digitalWrite(led, LOW);
      DebugPrintln("IP address: ");
      DebugPrintln(WiFi.localIP());//WiFi.localIP()返回8266获得的ip地址
      server.begin();
      server.setNoDelay(true);  //加上后才正常些
    }
       
    /**
    * @Desc  主函数
    */
    void loop() {
      uint8_t i;
      if (server.hasClient()){
            for (i = 0; i < MAX_SRV_CLIENTS; i++){
                if (!serverClients[i] || !serverClients[i].connected()){
                    if (serverClients[i]) serverClients[i].stop();//未联接,就释放
                    serverClients[i] = server.available();//分配新的
                    continue;
                }
            }
            //8266tcpserver只能接入五个  超出的需要释放
            WiFiClient serverClient = server.available();
            if (serverClient){
              serverClient.stop();
            }
      }
       
      for (i = 0; i < MAX_SRV_CLIENTS; i++){
            if (serverClients[i] && serverClients[i].connected()){
                //处理客户端发过来的数据
                if (serverClients[i].available()){
                    while (serverClients[i].available()) 
                        Serial.write(serverClients[i].read());
                }
            }
       }
     
       if(Serial.available()>0){
          char ch = Serial.read();
          if(ch == '1'){
            smartConfig();
            delay(1000);
            digitalWrite(led, LOW);
            DebugPrintln("IP address: ");
            DebugPrintln(WiFi.localIP());//WiFi.localIP()返回8266获得的ip地址
          }
       }
    }
     
    /**
    * 自动连接20s 超过之后自动进入SmartConfig模式
    */
    bool autoConfig(){
      WiFi.mode(WIFI_AP_STA);     //设置esp8266 工作模式
      WiFi.begin();
      delay(2000);//刚启动模块的话 延时稳定一下
      DebugPrintln("AutoConfiging ......");
      for(int i=0;i<20;i++){
        int wstatus = WiFi.status();
        if (wstatus == WL_CONNECTED){
          DebugPrintln("AutoConfig Success");
          DebugPrint("SSID:");
          DebugPrintln(WiFi.SSID().c_str());
          DebugPrint("PSW:");
          DebugPrintln(WiFi.psk().c_str());
          return true;
        }else{
          DebugPrint(".");
          delay(1000);
          flag = !flag;
          digitalWrite(led, flag);
        } 
      }
      DebugPrintln("AutoConfig Faild!");
      return false;
    }
     
    /**
    * 开启SmartConfig功能
    */
    void smartConfig()
    {
      WiFi.mode(WIFI_STA);
      delay(2000);
      DebugPrintln("Wait for Smartconfig");
      // 等待配网
      WiFi.beginSmartConfig();
      while (1){
        DebugPrint(".");
        delay(500);
        flag = !flag;
        digitalWrite(led, flag);
         
        if (WiFi.smartConfigDone()){
          //smartconfig配置完毕
          DebugPrintln("SmartConfig Success");
          DebugPrint("SSID:");
          DebugPrintln(WiFi.SSID().c_str());
          DebugPrint("PSW:");
          DebugPrintln(WiFi.psk().c_str());
          strcpy(config.ssid, WiFi.SSID().c_str());
          strcpy(config.psw, WiFi.psk().c_str());
          saveConfig();
          WiFi.mode(WIFI_AP_STA);     //设置esp8266 工作模式
          WiFi.setAutoConnect(true);  // 设置自动连接
          break;
        }
      }
    }
      
    /*
    保存参数到eeprom
     */
    void saveConfig()
    {
      EEPROM.begin(1024);
      uint8_t *p = (uint8_t*)(&config);
      for (int i = 0; i < sizeof(config); i++)
      {
        EEPROM.write(i, *(p + i));
      }
      EEPROM.commit();
    }
      
    /*
       从EEPROM加载参数
    */
    void loadConfig()
    {
      EEPROM.begin(1024);
      uint8_t *p = (uint8_t*)(&config);
      for (int i = 0; i < sizeof(config); i++)
      {
        *(p + i) = EEPROM.read(i);
      }
      EEPROM.commit();
    }
    

      

  • 相关阅读:
    C 语言中 static 的作用
    STM32 标准库
    STM32 HAL库与标准库的区别_浅谈句柄、MSP函数、Callback函数
    asp.net core launchsettings.json
    asp.net core mvc/api部署到iis
    依赖倒置来反转依赖
    ASP.NET Core in2020
    DDD学习一
    asp.net core学习一
    从零开始实现ASP.NET Core MVC的插件式开发
  • 原文地址:https://www.cnblogs.com/kekeoutlook/p/9086028.html
Copyright © 2011-2022 走看看