WeChat applet-MQTT-ESP8266 to operate SG90 switch light

This example is for reference only and will not be updated or improved.

Difficulty: domain name restrictions for WeChat applets;

ESP8266 connection MQTT can refer to: HTML Echarts graphic statistics display DHT11 temperature in real time (4)

ESP8266 control SG90 can refer to: NodeMcu (ESP8266) control SG90_I don't know blog-CSDN blog

ESP8266 DNS WEB dynamic network configuration can refer to: ESP8266 dynamic web page setting network connection_I don't know blog-CSDN blog_esp8266 how to connect to the public network and external network settings

Function can refer to: https://bemfa.blog.csdn.net/article/details/107367547

1. Realize the effect 

                                                      

  

 

 

2. ESP8266 program:

Use ESP8266 to connect to such as Baidu Cloud, Alibaba Cloud, Huawei Cloud, Tencent, Buffalo Cloud, etc. It is convenient to configure domain names for subsequent WeChat applets. WeChat applets cannot specify their own local IP or domain names that have not been verified by ICP on the government official website;

//DHT11数据上传+LED远程控制 //不限于DHT11,可以接其他传感器,也可以接多个传感器,这里只是例程
//DHT11数据上传主题temp   //根据自己在控制台命的名字可自己随意修改
//LED灯控制主题light002   //根据自己命的名字可自己随意修改
/*
程序讲解:ESP8266 有两个角色,一个是temp(传感器数据)主题消息的发布者,esp8266往这个主题推送消息,手机app订阅temp主题,就可以收到传感器数据了。
esp8266联网后,订阅light002,手机往这个主题推送消息,esp8266就能收到手机的控制的指令了。
D5  GND  VIN 
*/
#include <ESP8266WiFi.h>
//#include <SimpleDHT.h>
#include <Servo.h>


//服务器地址默认即可
#define TCP_SERVER_ADDR "bemfa.com"
//服务器端口//云端口8344//TCP设备云端口8340
#define TCP_SERVER_PORT "8344"

///****************需要修改的地方*****************///

//WIFI名称,区分大小写,不要写错
#define DEFAULT_STASSID  "ziroom1302"
//WIFI密码
#define DEFAULT_STAPSW "****"
//用户私钥,可在控制台获取,修改为自己的UID
String UID = "****";

//主题名字,可在控制台新建
String TOPIC2  = "light02";  //用于led控制的主题

///*********************************************///
//led 控制函数
void turnOnLed();
void turnOffLed();

//设置上传速率2s(1s<=upDataTime<=60s)
//下面的2代表上传间隔是2秒
// #define upDataTime 2*1000
#define upDataTime 800

//最大字节数
#define MAX_PACKETSIZE 512

//tcp客户端相关初始化,默认即可
WiFiClient TCPclient;
String TcpClient_Buff = "";
unsigned int TcpClient_BuffIndex = 0;
unsigned long TcpClient_preTick = 0;
unsigned long preHeartTick = 0;//心跳
unsigned long preTCPStartTick = 0;//连接
bool preTCPConnected = false;

//相关函数初始化
//连接WIFI
void doWiFiTick();
void startSTA();

//TCP初始化连接
void doTCPClientTick();
void startTCPClient();
void sendtoTCPServer(String p);

/*
  *发送数据到TCP服务器
 */
void sendtoTCPServer(String p){
  if (!TCPclient.connected()) 
  {
    Serial.println("Client is not readly");
    return;
  }
  TCPclient.print(p);
  Serial.println("[Send to TCPServer]:String");
  Serial.println(p);
}


/*
  *初始化和服务器建立连接
*/
void startTCPClient(){
  if(TCPclient.connect(TCP_SERVER_ADDR, atoi(TCP_SERVER_PORT))){
    Serial.print("\nConnected to server:");
    Serial.printf("%s:%d\r\n",TCP_SERVER_ADDR,atoi(TCP_SERVER_PORT));
    String tcpTemp="";
    tcpTemp = "cmd=1&uid="+UID+"&topic="+TOPIC2+"\r\n";

    sendtoTCPServer(tcpTemp);
    preTCPConnected = true;
    preHeartTick = millis();
    TCPclient.setNoDelay(true);
  }
  else{
    Serial.print("Failed connected to server:");
    Serial.println(TCP_SERVER_ADDR);
    TCPclient.stop();
    preTCPConnected = false;
  }
  preTCPStartTick = millis();
}

/*
  *检查数据,发送数据
*/
void doTCPClientTick(){
 //检查是否断开,断开后重连
   if(WiFi.status() != WL_CONNECTED) return;
  if (!TCPclient.connected()) {//断开重连
  if(preTCPConnected == true){
    preTCPConnected = false;
    preTCPStartTick = millis();
    Serial.println();
    Serial.println("TCP Client disconnected.");
    TCPclient.stop();
  }else if(millis() - preTCPStartTick > 1*1000)//重新连接
    startTCPClient();
  }else{
    if (TCPclient.available()) {//收数据
      char c =TCPclient.read();
      TcpClient_Buff +=c;
      TcpClient_BuffIndex++;
      TcpClient_preTick = millis();
      
      if(TcpClient_BuffIndex>=MAX_PACKETSIZE - 1){
        TcpClient_BuffIndex = MAX_PACKETSIZE-2;
        TcpClient_preTick = TcpClient_preTick - 200;
      }
      preHeartTick = millis();
    }
  }
  if((TcpClient_Buff.length() >= 1) && (millis() - TcpClient_preTick>=200))
  {//data ready
    TCPclient.flush();
    Serial.println("Buff");
    Serial.println(TcpClient_Buff);
    //字符串匹配,检测发了的字符串TcpClient_Buff里面是否包含&msg=on,如果有,则打开开关
    if((TcpClient_Buff.indexOf("&msg=on") > 0)) {
      turnOnLed();
    //字符串匹配,检测发了的字符串TcpClient_Buff里面是否包含&msg=off,如果有,则关闭开关
    }else if((TcpClient_Buff.indexOf("&msg=off") > 0)) {
      turnOffLed();
    }
   TcpClient_Buff="";//清空字符串,以便下次接收
   TcpClient_BuffIndex = 0;
  }
}
// SG90舵机控制
Servo myServo;  // 定义Servo对象来控制
int pos = 0;    // 角度存储变量
//打开灯泡
void turnOnLed(){
  Serial.println("Turn ON");
  for (pos = 33; pos <= 85; pos ++) { // 33°到85°
    // in steps of 1 degree
    myServo.write(pos);              // 舵机角度写入
    delay(5);                       // 等待转动到指定角度
  } 
}
//关闭灯泡
void turnOffLed(){
  Serial.println("Turn OFF");
  for (pos = 85; pos >= 33; pos --) { // 从85°到33°
    myServo.write(pos);              // 舵机角度写入
    delay(15);                       // 等待转动到指定角度
  }
}
void startSTA(){
  WiFi.disconnect();
  WiFi.mode(WIFI_STA);
  WiFi.begin(DEFAULT_STASSID, DEFAULT_STAPSW);
}
/**************************************************************************
                                 WIFI
***************************************************************************/
/*
  WiFiTick
  检查是否需要初始化WiFi
  检查WiFi是否连接上,若连接成功启动TCP Client
  控制指示灯
*/
void doWiFiTick(){
  static bool startSTAFlag = false;
  static bool taskStarted = false;
  static uint32_t lastWiFiCheckTick = 0;
  if (!startSTAFlag) {
    startSTAFlag = true;
    startSTA();
    Serial.printf("Heap size:%d\r\n", ESP.getFreeHeap());
  }
  //未连接1s重连
  if ( WiFi.status() != WL_CONNECTED ) {
    if (millis() - lastWiFiCheckTick > 1000) {
      lastWiFiCheckTick = millis();
    }
  }
  //连接成功建立
  else {
    if (taskStarted == false) {
      taskStarted = true;
      Serial.print("\r\nGet IP Address: ");
      Serial.println(WiFi.localIP());
      startTCPClient();
    }
  }
}
// 初始化,相当于main 函数
void setup() {
  Serial.begin(115200);
  // SG90使用D5接口  
  myServo.attach(14); 
}
//循环
void loop() {
  doWiFiTick();
  doTCPClientTick();
}

Guess you like

Origin blog.csdn.net/chenyang_wei/article/details/128498501