Summary of the use of STM32+ESP8266 to connect to Alibaba Cloud through MQTT

This experiment takes the pyroelectric sensor sensing the human body as an example to introduce how to connect the STM32+ESP8266 to the Alibaba Cloud IoT platform through the MQTT protocol.

1. Preliminary preparation

Hardware: Wildfire Guide STM32F103VET6 development board, HC-SR501 pyroelectric sensor

Software: Keil5

Platform: Alibaba Cloud


2. Specific operation

Alibaba Cloud IoT platform configuration

Create product

Insert picture description here

The test signal is received by the pyroelectric sensor Ali cloud platform, so select the product model with Boolean infrared detection state will be able to meet the demand.

Create device

Insert picture description here

Product selection demo just created, click the new device.

Get triplet

Insert picture description here

The system will automatically generate a ProductKey, DeviceName and equipment setup complete DeviceSecret after, referred to as triplets.

Communication Topic

Insert picture description here

Experiments communicate, MQTT protocol is based on MQTT (V3.1.1) platform is based on an agreement with the agency "publish / subscribe" messaging protocol mode, in this protocol, there are publishers, subscribers and agent (broker) three kinds Role, the message is published by the publisher through the topic, and the subscriber subscribes to the topic of interest. One publisher can correspond to multiple subscribers.

Selected set of suffix Topic in the post object model of the communication device Topic, the publish and subscribe represent, of course, also possible to customize the communication Topic. After obtaining the triplet and the communication topic, you can save it in the text for later use. In this way, the configuration of the IoT platform is basically completed.


Hardware Configuration

Insert picture description here

HC-SR501 pyroelectric sensor connected STM32 relatively simple, just to ground GND, the VCC power supply connected to 3.3V-5V, OUT connected I / O port to. The left knob is used to adjust the sensitivity, the clockwise sensitivity is high, and the counterclockwise sensitivity is low; the right knob is used to adjust the delay induction, the clockwise delay increases, and the counterclockwise delay decreases.


Software configuration

Pyroelectric sensor configuration

#include "sensor.h"
void HCSR501_Config(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	RCC_APB2PeriphClockCmd(HCSR501_INT_GPIO_CLK ,ENABLE);
	
	GPIO_InitStructure.GPIO_Pin = HCSR501_INT_GPIO_PIN;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	GPIO_Init(HCSR501_INT_GPIO_PORT, &GPIO_InitStructure);
}

uint8_t HCSR501_Statue(void)
{
	if(GPIO_ReadInputDataBit(HCSR501_INT_GPIO_PORT, HCSR501_INT_GPIO_PIN)==Bit_SET)
		return 1;
	else return 0;
}		

ESP8266 connect to WiFi

  • AT+CWMODE=1: Set working mode (STA mode)

    bool ESP8266_Net_Mode_Choose ( ENUM_Net_ModeTypeDef enumMode )
    {
    	switch ( enumMode )
    	{
    		case STA:
    		  return ESP8266_Cmd ( "AT+CWMODE=1", "OK", "no change", 10); 
    		
    	  case AP:
    		  return ESP8266_Cmd ( "AT+CWMODE=2", "OK", "no change", 10); 
    		
    		case STA_AP:
    		  return ESP8266_Cmd ( "AT+CWMODE=3", "OK", "no change", 10); 
    		
    	  default:
    		  return false;
      }
    	
    }
    
  • AT+CWJAP="SSID","PASSWORD": Connect to the WIFI hotspot in the current environment (hotspot name, password)

    bool ESP8266_JoinAP ( char * pSSID, char * pPassWord )
    {
    	char cCmd [120];
    	sprintf ( cCmd, "AT+CWJAP=\"%s\",\"%s\"", pSSID, pPassWord );	
    	return ESP8266_Cmd ( cCmd, "OK", NULL, 150 );
    }
    
  • AT+CIPMODE=1: Turn on transparent transmission mode

    bool ESP8266_UnvarnishSend ( void )
    {
    	if ( ! ESP8266_Cmd ( "AT+CIPMODE=1", "OK", NULL, 100 ) )
    		return false;
    	
    	return 
    	  ESP8266_Cmd ( "AT+CIPSEND", "OK", ">", 100 );
    	
    }
    

MQTT porting

Download paho mqtt open source code on Github Github Code link and unzip paho.mqtt.embedded-c-master \ MQTTPacket \ src in MQTT source and paho.mqtt.embedded-c-master \ MQTTPacket \ transport samples in Copy the file to your own project. Modify the transport_sendPacketBuffer() and transport_getdata() functions in the transport.c file to send and receive TCP data.

Insert picture description here

Modify MQTT protocol related parameters

#define   HOST_NAME       "a12Dg3Gsw50.iot-as-mqtt.cn-shanghai.aliyuncs.com"     //服务器域名
#else
#define   HOST_NAME       "139.196.135.135"     //服务器IP地址
#endif


#define   HOST_PORT     1883    //由于是TCP连接,端口必须是1883

#define   CLIENT_ID     "test01|securemode=3,signmethod=hmacsha1|"       //ID
#define   USER_NAME     "test01&a12Dg3Gsw50"     //用户名
#define   PASSWORD      "ce046a566db6047561024d89b99b898f98c39648"  //秘钥

#define   TOPIC         "/sys/a12Dg3Gsw50/test01/thing/service/property/set"      //订阅的主题
#define   PUBTOPIC      "/sys/a12Dg3Gsw50/test01/thing/event/property/post"      //发布的主题
HOST_NAME Fixed format: {YourProductKey}.iot-as-mqtt.{YourRegionId}.aliyuncs.com. {YourProductKey} is the ProductKey of the device. {YourRegionId} is the region ID.
HOST_PORT 1883
Client ID Fixed format: {YourDeviceName}|securemode=3,signmethod=hmacsha1|. {YourDeviceName} is the DeviceName in the triplet.
User Name Fixed format: {YourDeviceName}&{YourProductKey}. {YourDeviceName} and {YourProductKey} are DeviceName and ProductKey in the triplet respectively.
Password Format: clientId{YourDeviceName}deviceName{YourDeviceName}productKey{YourProductKey} {YourDeviceName} and {YourProductKey} are DeviceName and ProductKey in the triplet respectively. Encryption method is HmacSHA1; encryption key: DeviceSecret ; hmacsha1 encryption website: http://encode.chahuo.com/

Insert picture description here

upload data

if(HCSR501_Statue()==1)
				{
					sprintf(mqtt_message,"{\"method\":\"thing.event.property.post\",\"id\":\"0000000001\",\"params\":{\"MotionAlarmState\":1},\"version\":\"1.0.0\"}");
					MQTTMsgPublish(PUBTOPIC,QOS0,mqtt_message);
					printf( "\r\nsomeone inside\r\n");
				}
				else	
				{
					sprintf(mqtt_message,"{\"method\":\"thing.event.property.post\",\"id\":\"0000000001\",\"params\":{\"MotionAlarmState\":0},\"version\":\"1.0.0\"}");
					MQTTMsgPublish(PUBTOPIC,QOS0,mqtt_message);
					printf( "\r\nnoone inside\r\n");
				}								 
parameter Types of Description
method String Request method, the value is thing.event.property.post.
id String Message ID number. String type number, the value range is 0~4294967295, and each message ID is unique in the current device.
params bool MotionAlarmState state identifier, the value is 0 or 1.
version String Protocol version number. The current protocol version number is 1.0.0.

to sum up

ESP8266 sequentially connected aliyun can be divided into the following steps: a configuration module connected to STA mode ➡ ➡ hotspot connection TCP➡ configured transmission mode to transparent mode ➡ ➡ key authentication user name and subscription topic heartbeat packets are sent ➡ ➡ Receive/send data

Program sign-in format MQTT, ID and password, send a message format must be strictly in accordance with the agreement to perform MQTT, may lead to more than one space can not connect Ali cloud; send a message id parameter value is not fixed, just It is easy to take a value within the range, but the length of the id needs to be guaranteed; QOS means the quality of communication, because there may be data loss in the process of sending the message, the most direct solution is to resend it, such as Alibaba Cloud Most networking platforms do not support QOS2, and most of the needs can be met by using QOS0 in the actual development process.

3. Results display

Insert picture description here
Insert picture description here

After data visualization, you can see, when someone inside the display serial port, the platform interface displays red for someone; on the contrary, serial display noone inside, platform interface displays green for no one.

Guess you like

Origin blog.csdn.net/weixin_44355637/article/details/109261348
Recommended