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\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.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("\nConnecting 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();
}

  

 

转载于:https://www.cnblogs.com/kekeoutlook/p/9086028.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然可以!以下是一个示例的ESP-Now组网双向通信的代码: ``` #include <esp_now.h> #include <WiFi.h> #define CHANNEL 1 #define MAX_PEERS 20 typedef struct { uint8_t macAddr[6]; } __attribute__((packed)) peerInfo; // 函数声明 void onDataRecv(const uint8_t *macAddr, const uint8_t *data, int dataLen); void sendMsg(const uint8_t *peerMac, const uint8_t *data, int dataLen); void setup() { Serial.begin(115200); // 初始化ESP-NOW if (esp_now_init() != ESP_OK) { Serial.println("ESP-NOW 初始化失败"); return; } // 注册回调函数来接收数据 esp_now_register_recv_cb(onDataRecv); // 设置为组网模式 if (esp_now_set_self_role(ESP_NOW_ROLE_COMBO) != ESP_OK) { Serial.println("设置组网模式失败"); return; } // 添加对等节点 WiFi.mode(WIFI_STA); if (esp_now_add_peer(NULL, ESP_NOW_ROLE_COMBO, CHANNEL, NULL, 0) != ESP_OK) { Serial.println("添加对等节点失败"); return; } Serial.println("ESP-NOW 组网双向通信已准备就绪"); } void loop() { // 发送消息到对等节点 sendMsg(NULL, "Hello from Node 1", 17); delay(1000); } // 接收到数据的回调函数 void onDataRecv(const uint8_t *macAddr, const uint8_t *data, int dataLen) { Serial.println("收到消息:"); Serial.write(data, dataLen); Serial.println(); } // 发送消息到对等节点 void sendMsg(const uint8_t *peerMac, const uint8_t *data, int dataLen) { esp_now_send(peerMac, data, dataLen); } ``` 这是一个简单的示例,其中节点1发送消息到对等节点,并且对等节点收到消息后会打印出来。你可以根据自己的需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值