【酱菜物联】微信小程序实现远程控制LED灯
?
本教程是用ESP8266實現遠程控制LED燈的亮/滅,只要學會了控制LED燈,就可以控制繼電器、電機等很多東西噢
開發之前大家需要先搭好arduino for esp8266 的開發環境噢,具體可以看下面兩個大神寫的帖子
?
http://www.arduino.cn/thread-17895-1-1.html
http://www.arduino.cn/thread-17896-1-1.html
1、硬件:
可以選擇以下的任一種
?
(2)ESP8266開發板或NodeMCU開發板?+ USB數據線 硬件連接如下 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、物聯平臺?
? ??? ???這里我用的是醬菜物聯微信小程序,采用的mqtt協議,用了一段時間感覺還不錯,比較穩定,不用另外下載APP,直接微信控制。大家可以微信搜索“醬菜物聯”,就能找到,趕緊注冊吧。
協議說明:
? ? ? ? ? ? ? ?控制topic: /device/注冊時填入的郵箱地址/control/設備mac地址
? ? ? ? ? ? ? ?上報設備數據topic:?/device/注冊時填入的郵箱地址/status/設備mac地址
3、代碼:
因為微信小程序采用mqtt協議,所有這里還依賴pubsubclient和Arduino_JSON庫,大家可以在arduino庫管理搜索pubsubclient和Arduino_JSON,并安裝。
/*Basic ESP8266 MQTT exampleThis sketch demonstrates the capabilities of the pubsub library in combinationwith the ESP8266 board/library.It connects to an MQTT server then:- publishes "hello world" to the topic "outTopic" every two seconds- subscribes to the topic "inTopic", printing out any messagesit receives. NB - it assumes the received payloads are strings not binary- If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,else switch it offIt will reconnect to the server if the connection is lost using a blockingreconnect function. See the 'mqtt_reconnect_nonblocking' example for how toachieve the same result without blocking the main loop.To install the ESP8266 board, (using Arduino 1.6.4+):- Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":http://arduino.esp8266.com/stable/package_esp8266com_index.json- Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"- Select your ESP8266 in "Tools -> Board" */#include <ESP8266WiFi.h> #include <PubSubClient.h> #include <Arduino_JSON.h> // Update these with values suitable for your network.const char* ssid = "*******"; const char* password = "*******"; const char* mqtt_server = "jcckiot.com"; const char* mqtt_username = "*******"; //為注冊時填的郵箱 const char* mqtt_password = "*******"; //為注冊時填的密碼WiFiClient espClient; PubSubClient client(espClient); unsigned long lastMsg = 0; #define MSG_BUFFER_SIZE (50) char msg[MSG_BUFFER_SIZE]; int value = 0; uint8_t mac[6]; char mac_string[32]; //該mac地址將作為clientidchar report_status_topic[64]; char control_device_topic[64]; char device_disconnect_topic[64];void setup_wifi() {delay(10);// We start by connecting to a WiFi networkSerial.println();Serial.print("Connecting to ");Serial.println(ssid);WiFi.mode(WIFI_STA);WiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) {delay(500);Serial.print(".");}randomSeed(micros());Serial.println("");Serial.println("WiFi connected");Serial.println("IP address: ");Serial.println(WiFi.localIP());} void set_topic() {WiFi.macAddress(mac);sprintf(mac_string, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);Serial.println("MAC address: ");Serial.println(mac_string);//將打印的mac地址在添加設備的時候填入Serial.println("mac地址將在添加設備的時候填入,請保存");Serial.println("");sprintf(report_status_topic, "/device/%s/status/%s", mqtt_username,mac_string);Serial.print("report_status_topic:");Serial.println(report_status_topic);sprintf(control_device_topic, "/device/%s/control/%s", mqtt_username,mac_string);Serial.print("control_device_topic:");Serial.println(control_device_topic);sprintf(device_disconnect_topic, "/device/%s/disconnect/%s", mqtt_username,mac_string);Serial.print("device_disconnect_topic:");Serial.println(device_disconnect_topic); } void callback(char* topic, byte* payload, unsigned int length) {Serial.print("Message arrived [");Serial.print(topic);Serial.print("] ");char msg[64]={0};for (int i = 0; i < length; i++) {msg[i] = (char)payload[i];}Serial.println(msg);JSONVar myObject = JSON.parse(msg);Serial.println((const char *)myObject["meteName"]);Serial.println(myObject["meteValue"]);// Switch on the LED if an 1 was received as first characterif (!strcmp((const char *)myObject["meteName"],"switch1") && (int)myObject["meteValue"] == 1) {digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage levelSerial.println("set led: low");client.publish(report_status_topic, "1");// but actually the LED is on; this is because// it is active low on the ESP-01)} if (!strcmp((const char *)myObject["meteName"],"switch1") && (int)myObject["meteValue"] == 0) {digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGHSerial.println("set led: HIGH");client.publish(report_status_topic, "0");}}void reconnect() {// Loop until we're reconnectedwhile (!client.connected()) {Serial.println("Attempting MQTT connection...");// Create a random client IDString clientId = mac_string;Serial.print("MQTT clientId:");Serial.println(clientId);// Attempt to connectif (client.connect(clientId.c_str(),mqtt_username,mqtt_password,device_disconnect_topic,0,false,"0")) {Serial.println("connected");client.subscribe(control_device_topic);} else {Serial.print("failed, rc=");Serial.print(client.state());Serial.println(" try again in 5 seconds");// Wait 5 seconds before retryingdelay(5000);}} }void setup() {pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an outputSerial.begin(115200);setup_wifi();set_topic();client.setServer(mqtt_server, 1883);client.setCallback(callback); }void loop() {if (!client.connected()) {reconnect();}client.loop();}大家把代碼燒錄進8266,燒寫完成后把LED的正極接GPIO2,LED的負極接地
然后在微信小程序中添加設備,并把上面程序中打印的mac地址填入!
?
總結
以上是生活随笔為你收集整理的【酱菜物联】微信小程序实现远程控制LED灯的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Luogu 4244 [SHOI2008
- 下一篇: Java实现十进制数转十六进制数