走马观花

[Training Camp_Advanced Class] Smart socket based on Alibaba Cloud-827632A

 
Overview

[Summer Training Camp--Advanced Class]

describe

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.

Onboard resources

1. The project uses the ESP8266 integrated module ESP-12s, which is reasonably priced and integrates a 26MHz crystal oscillator and 32Mbit Flash.
2. USB to TTL circuit, the board has a USB interface, which can be used to power the board and download programs.
3.5v to 3.3v circuit, USB provides 5v power supply, the working voltage of the esp8266 analog part is 3.0V ~ 3.6V, the minimum is 2.7V, so it is necessary to convert 5v to 3.3v to make the module work stably.
4. Relay circuit to control the switch function and switch status on the cloud.
5. LED three-color lights, with different colors and frequencies used to indicate different states of the board.
6. The board has 3 buttons, namely reset, download, and wifi reconnect.
7. Temperature monitoring interface to monitor real-time temperature and upload it to the cloud.
8. Optional 220v to 5v circuit.

indicator light

After the board is powered on, the indicator light shows red (R) during the period when the wifi is not connected, the indicator light shows blue (B) during the wifi distribution process, and the indicator light shows green (G) after the wifi is connected.

ARDUINO code

#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();
}

Creation of Alibaba Cloud Life IoT Platform

1. Register your own account and perform real-name authentication.
2. Many people cannot find the Life IoT Platform. You can enter the Alibaba Cloud search box to search for the Life IoT Platform.

1.png

3. Create a new project

2.png

4.

3.png

5. Create new products

4.png

6.

5.png

7. You can delete and add functions by yourself, such as temperature

6.png

8. Fill it out by yourself, make sure there are no exclamation marks, and design the device panel yourself.

7.png

It is recommended to choose one-click network configuration. You can click the question mark to see the details.

8.png

9. Choose modules and chips according to your needs. If you don’t have a model, you can still choose uncertified. Then add test equipment. The name is arbitrary, just TEST.

9.png

Scan the QR code with your mobile phone to download, and you can see the interactive interface corresponding to the device. However, the device has not been developed yet, so it is not connected.

10.png

Equipment development and debugging

After writing the program framework, add your own triples and wifi to the code, compile and run it, and after mqtt is connected to Alibaba Cloud, the app can read device data based on publishing and subscription such as post and set in the code.
Due to the welding waste and the lack of a hot air gun at home, the soldering iron cannot adjust the temperature. The only ch340e welding is broken, so I can only use USB-TTL to push it. Also, I didn't pay attention to the original price when I placed the order. As a result, the pin header socket came back with a row of pins. Needle, hold it straight.

11.png12.png13.png

参考设计图片
×
 
 
Search Datasheet?

Supported by EEWorld Datasheet

Forum More
Update:2024-11-22 12:40:48

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号