Developed based on the Arduino framework and Alibaba Cloud IoT platform, it implements remote monitoring and control engineering of temperature and relays, and integrates the MQTT protocol.
Mobile APP and computer monitoring and control.
#include
#include
#include
#include
#include
//定义io
#define WiFi_KEY 2
#define RED 16
#define GREEN 14
#define BLUE 12
#define POWERKEY 5
#define ONE_WIRE_BUS 13 //1-wire数据总线连接在IO13
OneWire oneWire(ONE_WIRE_BUS); //声明
DallasTemperature sensors(&oneWire); //声明
//初始化次态
int keyState = 1;
int temperature;
int temperature_old = 0;
//你的wifi
#define WIFI_SSID "******-****"
#define WIFI_PASSWD "***********"
//阿里云三元组
#define PRODUCT_KEY "**********"
#define DEVICE_NAME "Test"
#define DEVICE_SECRET "***************************"
//Alink JSON所需
#define ALINK_BODY_FORMAT "{"id":"esp12s-iot","version":"1.0","method":"%s","params":%s}"
//属性上报Topic---发布
#define ALINK_TOPIC_PROP_POST "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"
//属性设置Topic---订阅
#define ALINK_TOPIC_PROP_SET "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/service/property/set"
#define ALINK_METHOD_PROP_POST "thing.event.property.post"
//创建WiFiClient实例
WiFiClient espClient;
//创建MqttClient实例
PubSubClient mqttClient(espClient);
//连接Wifi
void initWifi(const char *ssid, const char *password)
{
digitalWrite(RED, 1);
digitalWrite(GREEN, 1);
digitalWrite(BLUE, 0);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("WiFi is connecting ");
while (WiFi.status() != WL_CONNECTED)
{
Serial.println(".");
delay(1000);
}
Serial.println("Wifi is connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
WiFi.setAutoReconnect(true);
digitalWrite(RED, 1);
digitalWrite(BLUE, 1);
digitalWrite(GREEN, 0);
}
//连接Mqtt并订阅属性设置Topic
void mqttCheckConnect()
{
bool connected = connectAliyunMQTT(mqttClient, PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET);
if (connected)
{
Serial.println("MQTT connect succeed!");
//订阅属性设置Topic
mqttClient.subscribe(ALINK_TOPIC_PROP_SET);
Serial.println("subscribe done");
}
}
// 上报属性Topic数据
void mqttIntervalPost()
{
char param[256];
char jsonBuf[512];
sprintf(param, "{"powerstate":%d,"CuTemperature":%d}", keyState, temperature);
sprintf(jsonBuf, ALINK_BODY_FORMAT, ALINK_METHOD_PROP_POST, param);
//jsonBuf = "{"id":"123","version":"1.0","method":"thing.event.property.post","params":"{"S_D0":%d}"}"
Serial.println(jsonBuf);
mqttClient.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
}
//监听云端下发指令并处理
void callback(char *topic, byte *payload, unsigned int length)
{
Serial.println();
Serial.println();
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
Serial.println();
//云端下发属性设置topic = "[/sys/PRODUCT_KEY/DEVICE_SECRET/thing/service/property/set]"
payload[length] = '';
Serial.println((char *)payload);
//payload = "{"method":"thing.service.property.set","id":"282860794","params":{"S_D0":1},"version":"1.0.0"}"
if (strstr(topic, "/thing/service/property/set"))
{
//json解析payload
StaticJsonDocument doc;
DeserializationError error = deserializeJson(doc,payload);
//判断json解析是否成功
if (error)
{
Serial.println("deserializeJson() failed");
}
else
{
Serial.println("deserializeJson() success");
//redLedState0 = json解析后的"S_D0"的值
keyState = doc["params"]["powerstate"];
digitalWrite(POWERKEY, keyState);
Serial.print("powerstate:");
Serial.println(keyState);
Serial.println("Change !!!");
}
}
}
/*
* 读取温湿度数据
*/
int getTemperature()
{
sensors.requestTemperatures();
int temperature = sensors.getTempCByIndex(0); //获取索引号0的传感器摄氏温度数据
if (temperature != DEVICE_DISCONNECTED_C) //如果获取到的温度正常
{
Serial.print("当前温度是: ");
Serial.print(temperature);
Serial.println(" ℃
");
}
else
{
Serial.println("温度转化失败!");
}
return temperature;
}
void setup()
{
Serial.begin(115200);
pinMode(WiFi_KEY, INPUT);
pinMode(POWERKEY, OUTPUT);
pinMode(RED, OUTPUT);
pinMode(GREEN, OUTPUT);
pinMode(BLUE, OUTPUT);
digitalWrite(GREEN, 1);
digitalWrite(BLUE, 1);
digitalWrite(RED, 0);
digitalWrite(POWERKEY, keyState);
Serial.println();
initWifi(WIFI_SSID, WIFI_PASSWD);
Serial.println();
mqttCheckConnect(); //初始化首次链接
mqttIntervalPost(); //上报初始化数据
delay(1000);
Serial.println();
mqttClient.setCallback(callback); // 回调,监听云端下发指令,当ESP8266收到订阅Topic后调用callback函数
}
void loop()
{
digitalWrite(RED, 1);
digitalWrite(BLUE, 1);
digitalWrite(GREEN, 0);
if (WiFi.status() != WL_CONNECTED || digitalRead(WiFi_KEY) == 0)
{
digitalWrite(RED, 1);
digitalWrite(GREEN, 1);
digitalWrite(BLUE, 0);
Serial.print("[loop()]Attempting to connect to WPA SSID: ");
Serial.println(WIFI_SSID);
// 连接WiFi热点
WiFi.begin(WIFI_SSID, WIFI_PASSWD);
delay(2000);
Serial.println("[loop()]Connected to AP");
}
if ( !mqttClient.connected() ) {
mqttCheckConnect();
}
temperature = getTemperature();
if ( temperature != temperature_old ) { // 温度变化时,上传数据
temperature_old = temperature;
mqttIntervalPost(); //上报数据
}
delay(5000);
mqttClient.loop();
}
All reference designs on this site are sourced from major semiconductor manufacturers or collected online for learning and research. The copyright belongs to the semiconductor manufacturer or the original author. If you believe that the reference design of this site infringes upon your relevant rights and interests, please send us a rights notice. As a neutral platform service provider, we will take measures to delete the relevant content in accordance with relevant laws after receiving the relevant notice from the rights holder. Please send relevant notifications to email: bbs_service@eeworld.com.cn.
It is your responsibility to test the circuit yourself and determine its suitability for you. EEWorld will not be liable for direct, indirect, special, incidental, consequential or punitive damages arising from any cause or anything connected to any reference design used.
Supported by EEWorld Datasheet