本文主要是介绍ESP8266(NODMCU模块)+Arduino IDE连接阿里云物联网实现开关控制与温度传输(小白教程),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
-
开发环境准备
首先在arduino ide中安装开发板适配环境。(用到网址http://arduino.esp8266.com/stable/package_esp8266com_index.json)
-
相应库的准备
再管理库中找到额外需要的库。(这里用到了PubSubClient;ArduinoJson;U8g2lib;其中U8g2lib是为了在我的lcd屏幕做显示用的)
-
阿里云物联网设备的添加及设备在线调试
关于添加设备bilibili上有详细的视频教程。
关联网址:https://www.bilibili.com/video/av71299561?from=search&seid=581284989892673131
关于在线调试如下:
在编辑框中输入相应命令即可下发数据。 -
程序相关内容的修改(重要)
比较重要的几点都在这里了,要注意:1.设备证书信息的修改;2.password的生成与修改。
这里用到了一个生成工具,大家可以在网上找,也可以下载我的分享,解压后用浏览器打开sign即可。(链接: https://pan.baidu.com/s/1sCT0tgkYmlmOw6RI2cQWJA 提取码: igb6) -
下发数据的截取与上传数据的格式
在设备定义好其功能后,相应功能都有对应的标识符,根据这些标识符就可以将数据一一对应的提取与上传。其中云端下发数据在callback函数中的payload数组中。上传数据通过mqttIntervalPost函数中的sprintf(param, “{“标识符”:%d}”,数据);
void callback(char *topic, byte *payload, unsigned int length)//网络反馈数据
{Serial.print("callback ");Serial.print("Message arrived [");Serial.print(topic);Serial.print("] ");payload[length] = '\0';Serial.println((char *)payload);//通过打印输出payload可以看到下发的数据
}
void mqttIntervalPost()
{Serial.print("mqttIntervalPost ");char param[32];char jsonBuf[128];sprintf(param, "{\"Temperature\":%d}",temp);//sprintf(param, "{\"标识符\":%d}",数据);sprintf(jsonBuf, ALINK_BODY_FORMAT, param);Serial.println(jsonBuf);boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);Serial.print("publish:");Serial.println(d);
}
7.一些注意事项及数据传输效果
- 步骤4中的设备信息与password一定要修改正确。
- 上传信息时,对应标识符的数据类型与其取值范围都要严格按照定义发送。
全部代码如下:
#include <ESP8266WiFi.h>
/* 依赖 C 2.4.0 */
#include <PubSubClient.h>
/* 依赖 ArduinoJson 5.13.4 */
#include <ArduinoJson.h>
#include <Arduino.h>
#include <U8g2lib.h>#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif#define SENSOR_PIN 12/* 修改1 ------------------------------------------ */
/* 连接您的WIFI SSID和密码 */
#define WIFI_SSID "Ren"
#define WIFI_PASSWD "h,19980128"
/* 修改1 end--------------------------------------- *//* 修改2 ------------------------------------------ */
/* 设备证书信息*/
#define PRODUCT_KEY "a1u6kVLHdBu"
#define DEVICE_NAME "light"
#define DEVICE_SECRET "8sswAiY71VYFpdeBuaYdntzVPt749Dyn"
#define REGION_ID "cn-shanghai"
/* 修改2 end--------------------------------------- *//* 线上环境域名和端口号,不需要改 */
#define MQTT_SERVER PRODUCT_KEY ".iot-as-mqtt." REGION_ID ".aliyuncs.com"
#define MQTT_PORT 1883
#define MQTT_USRNAME DEVICE_NAME "&" PRODUCT_KEY/* 修改3 ------------------------------------------ */
#define CLIENT_ID "esp8266|securemode=3,signmethod=hmacsha1,timestamp=1234567890|"
#define MQTT_PASSWD "8CB9F536ECD1D22A713DFA825CEFE5BC76795616"//8CB9F536ECD1D22A713DFA825CEFE5BC76795616
/* 修改3 end--------------------------------------- */#define ALINK_BODY_FORMAT "{\"id\":\"123\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
#define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE); // All Boards without Reset of the Displayunsigned long lastMs = 0;
WiFiClient espClient;
PubSubClient client(espClient);int flag=0;
int temp=0;
char Temperature[16]="Temperature: ";
void callback(char *topic, byte *payload, unsigned int length)//网络反馈数据
{int i=60;Serial.print("callback ");Serial.print("Message arrived [");Serial.print(topic);Serial.print("] ");payload[length] = '\0';Serial.println((char *)payload);Serial.println((char )payload[81]);if ((char )payload[78]=='e'){Temperature[13]=(char )payload[81];Temperature[14]=(char )payload[82];}else if((char )payload[78]=='h'){if((char )payload[81]=='0'){Serial.println("Light:close");flag=0;digitalWrite(SENSOR_PIN,LOW);}else if ((char )payload[81]=='1'){Serial.println("Light:on");flag=1;digitalWrite(SENSOR_PIN,HIGH);}}
}void wifiInit()
{Serial.print("wifiInit ");WiFi.mode(WIFI_STA);WiFi.begin(WIFI_SSID, WIFI_PASSWD);while (WiFi.status() != WL_CONNECTED){delay(1000);Serial.println("WiFi not Connect");}Serial.println("Connected to AP");Serial.println("IP address: ");Serial.println(WiFi.localIP());Serial.print("espClient [");client.setServer(MQTT_SERVER, MQTT_PORT); /* 连接WiFi之后,连接MQTT服务器 */client.setCallback(callback);
}void mqttCheckConnect()
{Serial.print("mqttCheckConnect ");while (!client.connected()){Serial.println("Connecting to MQTT Server ...");if (client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD)){Serial.println("MQTT Connected!");}else{Serial.print("MQTT Connect err:");Serial.println(client.state());delay(5000);}}
}void mqttIntervalPost1()
{Serial.print("mqttIntervalPost ");char param[32];char jsonBuf[128];if (flag==1)
{sprintf(param, "{\"LightSwitch\":%d}",1);
}
else
{sprintf(param, "{\"LightSwitch\":%d}",0);}sprintf(jsonBuf, ALINK_BODY_FORMAT, param);Serial.println(jsonBuf);boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);Serial.print("publish:");Serial.println(d);
}
void mqttIntervalPost2()
{Serial.print("mqttIntervalPost2 ");char param[32];char jsonBuf[128];temp=(Temperature[13]-0x30)*10+Temperature[14]-0x30;sprintf(param, "{\"Temperature\":%d}",temp);sprintf(jsonBuf, ALINK_BODY_FORMAT, param);Serial.println(jsonBuf);boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);Serial.print("publish:");Serial.println(d);
} void setup()
{pinMode(SENSOR_PIN, OUTPUT);/* initialize serial for debugging */u8g2.begin(); Serial.begin(115200);Serial.println("Demo Start");wifiInit();
}// the loop function runs over and over again forever
void loop()
{u8g2.clearBuffer(); // clear the internal memoryu8g2.setFont(u8g2_font_ncenB08_tr); // choose a suitable fontif (millis() - lastMs >= 5000){lastMs = millis();mqttCheckConnect(); /* 上报消息心跳周期 */mqttIntervalPost1();//开关状态mqttIntervalPost2();//温度数据}client.loop();if (flag){u8g2.drawStr(10,20,"Light: ON!");}else{u8g2.drawStr(10,20,"Light: OFF!");}u8g2.drawStr(10,40,Temperature); u8g2.sendBuffer(); // transfer internal memory to the displaydelay(200);}
我用到的开发板。
这篇关于ESP8266(NODMCU模块)+Arduino IDE连接阿里云物联网实现开关控制与温度传输(小白教程)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!