Arduino环境编译esp8266 mqtt连接阿里云,实现设备运云端双向通信,并同时获取sntp网络时间
Arduino源程序如下:
- //13=D7 16=D0 15=D8 14=D5 12=D6 4=D2 3=D9 2=D4=GPIO2 1=D10 0=D3=GPIO0
- #include <ESP8266WiFi.h>//安装esp8266arduino开发环境
- #include <AliyunIoTSDK.h>//引入阿里云 IoT SDK
- #include <NTPClient.h>
- #include <WiFiUdp.h>
- #define PRODUCT_KEY "***********"//替换自己的PRODUCT_KEY
- #define DEVICE_NAME "***********"//替换自己的DEVICE_NAME
- #define DEVICE_SECRET "***********"//替换自己的DEVICE_SECRET
- #define REGION_ID "cn-shanghai"//默认cn-shanghai
- #define WIFI_SSID "***********"//替换自己的WIFI
- #define WIFI_PASSWD "***********"//替换自己的WIFI
- #define ledPin 0
- static WiFiClient espClient;
- WiFiUDP ntpUDP;
- NTPClient timeClient(ntpUDP,"ntp1.aliyun.com",0,0);//30*60*1000
- unsigned long lastMsMain = 0;
- String rxbuff="";
- void setup()
- {
- Serial.begin(9600);
- pinMode(ledPin, OUTPUT);
- digitalWrite(ledPin, HIGH);
- //连接到wifi
- wifiInit(WIFI_SSID, WIFI_PASSWD);
- timeClient.begin();//SNTP begin
- //初始化 iot,需传入 wifi 的 client,和设备产品信息
- AliyunIoTSDK::begin(espClient, PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET, REGION_ID);
- //绑定一个设备属性回调,当远程修改此属性,会触发LED函数
- AliyunIoTSDK::bindData("PowerSwitch", Relay_Control);//电器开关
- AliyunIoTSDK::bindData("VehACSwitch", Air_Control);//空调开关
- AliyunIoTSDK::bindData("LightLuminance",PWM_Control);//主灯亮度PWM
- }
- void loop()
- {
- int t=36;
- AliyunIoTSDK::loop();//必要函数
-
- //时刻读取硬件串口数据
- while (Serial.available())
- {
- rxbuff += char(Serial.read());
- }
- while (Serial.read() >= 0) {} //清除串口缓存
- if (rxbuff.length() > 0)
- {
- Serial.println(rxbuff[2]);
- rxbuff="";
- }
-
- if (millis() - lastMsMain >= 2000)//每2秒发送一次
- {
- lastMsMain = millis();
- //发送温度到云平台
- AliyunIoTSDK::send("IndoorTemperature", t);//温度上传
- timeClient.update();
- //Serial.println(timeClient.getFormattedTime());
- //Serial.println(timeClient.getEpochTime());
- }
- }
- //wifi 连接
- void wifiInit(const char *ssid, const char *passphrase)
- {
- WiFi.mode(WIFI_STA);
- WiFi.begin(ssid, passphrase);
- while (WiFi.status() != WL_CONNECTED)
- {
- delay(1000);
- Serial.println("WiFi not Connect");
- }
- Serial.println("Connected to AP");
- }
- //继电器开关的属性修改的回调函数
- void Relay_Control(JsonVariant L)//固定格式,修改参数l
- {
- int Relay = L["PowerSwitch"];//参数l “”为aliyun 的标志符
- AliyunIoTSDK::send("PowerSwitch", Relay);
- if (Relay == 1)
- {
- Serial.println("Relay On_____________");
- digitalWrite(ledPin,HIGH);
- }
- else
- {
- Serial.println("Relay Off____________");
- digitalWrite(ledPin,LOW);
- }
-
- }
- //空调开关的属性修改的回调函数
- void Air_Control(JsonVariant L)
- {
- int Air = L["VehACSwitch"];//参数l “”为aliyun 的标志符
- AliyunIoTSDK::send("VehACSwitch", Air);
- if (Air == 1)
- Serial.println("Air PowerOn___________");
-
- else
- Serial.println("Air PowerOff__________");
- }
- //PWM变频的属性修改的回调函数
- void PWM_Control(JsonVariant L)
- {
- int PWM = L["LightLuminance"];//参数l “”为aliyun 的标志符
- AliyunIoTSDK::send("LightLuminance", PWM);
- Serial.println("PWM value:");
- Serial.println(PWM);
- }
复制代码
以上程序51hei提供下载:
esp.zip
(1.61 KB, 下载次数: 98)
|