【arduino for esp8266】ESP8266连接服务器实现微信小程序控制led-Arduino中文社区 - Powered by Discuz!

Arduino中文社区

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 9790|回复: 3

【arduino for esp8266】ESP8266连接服务器实现微信小程序控制led

[复制链接]
发表于 2016-11-30 19:38 | 显示全部楼层 |阅读模式
本帖最后由 chenyuechi 于 2020-7-21 18:30 编辑

本教程是通过ESP8266连接云服务器实现远程控制LED灯的亮/灭,只要学会了控制了LED灯,就可以控制其他设备了,开发之前大家需搭好arduino for esp8266的开发环境,具体大家可以看下面两篇帖子:
           http://www.arduino.cn/thread-17895-1-1.html
           http://www.arduino.cn/thread-17896-1-1.html
        搭好arduino for esp8266开发环境后,大家还需要一个服务器,这样才能实现远程控制,这里我用的是酱菜物联小程序,不需要安装其他的app,方便!可以在微信搜索“酱菜物联”.
       esp8266出现以来针对不同的应用环境发布了多个版本,如esp8266-01~esp8266-12e等等不同的版本,但是他们只是应用范围的不同在开发上没有多大区别。几个常见的8266版本esp8266-01、esp8266-12     
1、硬件:可以选择以下的任一种
(1)ESP8266-01 ~13 + USB 转 TTL串口模块(如PL2303、CH340)
(2)ESP8266开发板或NodeMCU开发板 + USB数据线
硬件连接如下
192500ch77uhw8399jp00v.png
ESP8266-01 ~13 + USB 转 TTL串口模块(如PL2303、CH340)
(1)如果wifi模块是ESP8266-01的按以下接线:(按烧写模式接线)
烧写模式接线方法:(用USB转TTL串口连接模块与PC)
esp8266-01         u转串
VCC-----------3.3
GND----------GND
GPIO0--------GND
CH_PD--------3.3
RX-------------TX
TX-------------Rx
其余引脚为空。
烧写模式接线方法:烧写模式时需要将gpio0接地,工作模式时gpio0悬空
(注意有时8266需要独立供电,不直接在ttl取电,很多出现问题都在供电上,别对自己的电源太自信)
(2)如果wifi模块是ESP8266-07或12的按以下接线:
192520q2t2tuwfu8awtwp6.png

因为采用mqtt协议,所以程序还依赖pubsubclient和Arduino_JSON库,大家可以在库管理那搜索安装pubsubclient库
代码:


复制代码
  1. /*
  2. Basic ESP8266 MQTT example
  3. This sketch demonstrates the capabilities of the pubsub library in combination
  4. with the ESP8266 board/library.
  5. It connects to an MQTT server then:
  6.   - publishes "hello world" to the topic "outTopic" every two seconds
  7.   - subscribes to the topic "inTopic", printing out any messages
  8.     it receives. NB - it assumes the received payloads are strings not binary
  9.   - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
  10.     else switch it off
  11. It will reconnect to the server if the connection is lost using a blocking
  12. reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
  13. achieve the same result without blocking the main loop.
  14. To install the ESP8266 board, (using Arduino 1.6.4+):
  15.   - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
  16.        http://arduino.esp8266.com/stable/package_esp8266com_index.json
  17.   - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
  18.   - Select your ESP8266 in "Tools -> Board"
  19. */

  20. #include <ESP8266WiFi.h>
  21. #include <PubSubClient.h>
  22. #include <Arduino_JSON.h>
  23. // Update these with values suitable for your network.

  24. const char* ssid = "*******";
  25. const char* password = "*******";
  26. const char* mqtt_server = "jcckiot.com";
  27. const char* mqtt_username = "*******"; //为注册时填的邮箱
  28. const char* mqtt_password = "*******";           //为注册时填的密码

  29. WiFiClient espClient;
  30. PubSubClient client(espClient);
  31. unsigned long lastMsg = 0;
  32. #define MSG_BUFFER_SIZE        (50)
  33. char msg[MSG_BUFFER_SIZE];
  34. int value = 0;
  35. uint8_t mac[6];
  36. char mac_string[32];  //该mac地址将作为clientid

  37. char report_status_topic[64];
  38. char control_device_topic[64];
  39. char device_disconnect_topic[64];

  40. void setup_wifi() {

  41.   delay(10);
  42.   // We start by connecting to a WiFi network
  43.   Serial.println();
  44.   Serial.print("Connecting to ");
  45.   Serial.println(ssid);

  46.   WiFi.mode(WIFI_STA);
  47.   WiFi.begin(ssid, password);

  48.   while (WiFi.status() != WL_CONNECTED) {
  49.     delay(500);
  50.     Serial.print(".");
  51.   }

  52.   randomSeed(micros());

  53.   Serial.println("");
  54.   Serial.println("WiFi connected");
  55.   Serial.println("IP address: ");
  56.   Serial.println(WiFi.localIP());
  57.   
  58. }
  59. void set_topic()
  60. {
  61.   WiFi.macAddress(mac);
  62.   sprintf(mac_string, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  63.   Serial.println("MAC address: ");
  64.   Serial.println(mac_string);//将打印的mac地址在添加设备的时候填入
  65.   Serial.println("mac地址将在添加设备的时候填入,请保存");
  66.   Serial.println("");
  67.   sprintf(report_status_topic, "/device/%s/status/%s", mqtt_username,mac_string);
  68.   Serial.print("report_status_topic:");
  69.   Serial.println(report_status_topic);
  70.   sprintf(control_device_topic, "/device/%s/control/%s", mqtt_username,mac_string);
  71.   Serial.print("control_device_topic:");
  72.   Serial.println(control_device_topic);
  73.   sprintf(device_disconnect_topic, "/device/%s/disconnect/%s", mqtt_username,mac_string);
  74.   Serial.print("device_disconnect_topic:");
  75.   Serial.println(device_disconnect_topic);
  76. }
  77. void callback(char* topic, byte* payload, unsigned int length) {
  78.   Serial.print("Message arrived [");
  79.   Serial.print(topic);
  80.   Serial.print("] ");
  81.   char msg[64]={0};
  82.   for (int i = 0; i < length; i++) {
  83.     msg[i] = (char)payload[i];
  84.   }
  85.   
  86.   Serial.println(msg);
  87.   JSONVar myObject = JSON.parse(msg);
  88.   Serial.println((const char *)myObject["meteName"]);
  89.   Serial.println(myObject["meteValue"]);
  90.   // Switch on the LED if an 1 was received as first character
  91.   if (!strcmp((const char *)myObject["meteName"],"switch1") && (int)myObject["meteValue"] == 1) {
  92.     digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
  93.     Serial.println("set led: low");
  94.     client.publish(report_status_topic, "1");
  95.     // but actually the LED is on; this is because
  96.     // it is active low on the ESP-01)
  97.   }
  98.   if (!strcmp((const char *)myObject["meteName"],"switch1") && (int)myObject["meteValue"] == 0) {
  99.     digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  100.     Serial.println("set led: HIGH");
  101.     client.publish(report_status_topic, "0");
  102.   }

  103. }

  104. void reconnect() {
  105.   // Loop until we're reconnected
  106.   while (!client.connected()) {
  107.     Serial.println("Attempting MQTT connection...");
  108.     // Create a random client ID
  109.     String clientId = mac_string;
  110.     Serial.print("MQTT clientId:");
  111.     Serial.println(clientId);
  112.     // Attempt to connect
  113.     if (client.connect(clientId.c_str(),mqtt_username,mqtt_password,device_disconnect_topic,0,false,"0")) {
  114.       Serial.println("connected");
  115.       client.subscribe(control_device_topic);
  116.     } else {
  117.       Serial.print("failed, rc=");
  118.       Serial.print(client.state());
  119.       Serial.println(" try again in 5 seconds");
  120.       // Wait 5 seconds before retrying
  121.       delay(5000);
  122.     }
  123.   }
  124. }

  125. void setup() {
  126.   pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  127.   Serial.begin(115200);
  128.   setup_wifi();
  129.   set_topic();
  130.   client.setServer(mqtt_server, 1883);
  131.   client.setCallback(callback);
  132. }

  133. void loop() {

  134.   if (!client.connected()) {
  135.     reconnect();
  136.   }
  137.   client.loop();
  138.   
  139. }
复制代码

最后,进入酱菜物联小程序添加设备,就可以实现远程控制了有什么问题可以到酱菜物联交流群(81728935)来一起交流
微信图片_20200713143935.png 微信图片_20200713143925.png







发表于 2018-4-2 22:46 来自手机 | 显示全部楼层
我也说一句不错不错
发表于 2020-4-27 17:59 | 显示全部楼层
楼主,我用了你提供的网址下载了arduino IDE开发环境的安装包,然后用的你的程序,编译的时候出现error compiling for board NodeMCU 1.0(ESP-12E Module),怎么解决呢
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|Archiver|手机版|Arduino中文社区

GMT+8, 2024-12-1 03:36 , Processed in 0.078547 second(s), 19 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表