Intelligent access control system designed based on STM32+Huawei Cloud IOT

1. Project introduction

The smart access control system is an intelligent security system that applies Internet of Things technology to provide safe and efficient access control management and remote monitoring functions. Traditional access control systems usually use magnetic cards, passwords or keys to unlock, but there are problems such as easy loss, easy duplication, and cumbersome operation. In order to solve these problems and improve the security and convenience of access control, the design of an intelligent access control system based on STM32F103 and Huawei Cloud IOT is introduced here.

The core controller of the system uses the STM32F103 microcontroller, which has rich peripheral interfaces and powerful processing capabilities, and can achieve precise control and data processing of access control equipment. In order to provide a variety of unlocking methods, the RFID-RC522 read-write module and 4x4 capacitive matrix keyboard were selected as input devices. Users can open the access control by swiping their card or entering a password. A 28BYJ-48 stepper motor is used as the door lock control device, which can achieve precise control of the door lock.

In order to facilitate users to interact with the access control system, a 0.96-inch OLED display with SPI interface and a buzzer are used to display door lock status information and human-computer interaction prompts. In addition, in order to realize remote control and message push functions, the ESP8266 WiFi module was selected to connect to the Huawei Cloud IoT platform. Users can remotely unlock the door through the mobile APP and monitor the door lock status at any time. When the door lock is opened or closed successfully, the mobile APP will receive a notification reminder to increase the user's safety and convenience.

By combining STM32F103 with Huawei Cloud IOT, the smart access control system can achieve efficient, stable, and secure performance in data transmission, remote control, and message push. The system not only provides a variety of unlocking methods and human-computer interaction functions, but also has the intelligent features of remote monitoring and message reminders. It is suitable for the access control management needs of residential communities, schools, enterprises and institutions, etc.

image-20230801151934943

image-20230801151925200

2. Hardware selection

In the hardware selection of the intelligent access control system, the following modules were selected:

【1】Main controller: STM32F103 microcontroller. It is a high-performance, low-power ARM Cortex-M3 core microcontroller with rich peripheral interfaces and powerful computing and control capabilities. It is very suitable for control and data processing of access control systems.

【2】RFID reading and writing module: RFID-RC522. This module is based on 13.56MHz radio frequency identification technology, which can read and write RFID cards, and open and close access control by swiping the card.

【3】Door lock control: 28BYJ-48 stepper motor. The stepper motor has a simple structure and small size, and can accurately control the door lock and provide the function of opening and closing the door lock.

【4】Password input device: 4x4 capacitive matrix keyboard. This keyboard uses capacitive touch technology and is waterproof and highly sensitive. Users can enter the password to open the access control.

【5】Display: 0.96-inch OLED display with SPI interface. The display screen has the characteristics of high brightness, high contrast and low power consumption, and can display door lock status information and human-computer interaction prompts.

【6】Network connection module: ESP8266-WIFI. This module supports WiFi communication standards and can connect to the Huawei Cloud IoT platform to achieve remote control and message push functions.

【7】Door status detection: infrared magnetic induction module. Through infrared magnetic induction technology, it can detect whether the door is open or closed and provide accurate door status information.

The selected hardware can meet the functional requirements of the smart access control system. The main controller STM32F103 provides stable and reliable control and processing capabilities for the entire system. The RFID reading and writing module and password keyboard provide a variety of unlocking methods. The stepper motor realizes precise door lock control, and the display screen and buzzer provide For human-computer interaction function, the ESP8266-WIFI module connects to Huawei Cloud to realize remote control and message push, and the infrared magnetic induction module detects the door status, making the entire smart access control system more intelligent, safer and more convenient.

3. System design ideas

Design ideas of intelligent access control system:

【1】Hardware connection and integration: Each hardware component (such as main controller, RFID reading and writing module, stepper motor, etc.) requires correct connection and interface configuration. Connect each hardware module to the main controller through connecting lines, and set the correct pin connections and register configurations to ensure that they can work properly and implement the corresponding functions.

【2】Data collection and processing: The system reads the user's card swiping information through the RFID reading and writing module or obtains the password information entered by the user through the capacitive matrix keyboard. After receiving the data, the main controller performs corresponding data processing, such as verifying whether the card information or password is correct. If the verification is passed, proceed to the next step of the access control process.

【3】Door lock control and status detection: The main controller realizes precise control of the door lock by controlling the stepper motor. When the user authentication is successful, the main controller sends instructions to the stepper motor to rotate the corresponding number of steps to open or close the door lock. At the same time, the main controller also uses an infrared magnetic induction module to detect the status of the door to ensure accurate control of the door lock.

[4] User interface and human-computer interaction: The system is equipped with a 0.96-inch OLED display and a buzzer. The display can show the user the status information of the door lock and related prompts, such as successful unlocking, incorrect password, etc. The buzzer can emit different prompt sounds to provide interactive feedback to the user.

【5】Remote control and message push: Connecting to the Huawei Cloud IoT platform through the ESP8266-WIFI module, users can perform remote unlocking operations through the mobile APP. After the user inputs the unlocking command on the mobile APP, the APP will send the command to the Huawei Cloud Platform, and the cloud platform will then transmit the command to the Internet of Things device (smart access control system). After receiving the unlocking command, the main controller performs corresponding control actions and sends the results back to the mobile APP through the cloud platform to realize remote control and message push functions.

The design idea of ​​the entire system is to coordinate various hardware components, perform data processing and door lock control through the main controller, and provide human-computer interaction interface and remote control functions to achieve safe, efficient and convenient access management of the intelligent access control system. and remote monitoring.

4. Deployment of Huawei Cloud IoT Platform

Huawei Cloud official website: https://www.huaweicloud.com/

Open the official website and search for Internet of Things to find it quickly 设备接入IoTDA.

image-20230801151116995

4.1 Introduction to IoT platform

Huawei Cloud Internet of Things Platform (IoT device access cloud service) provides access and management capabilities for massive devices, connects physical devices to the cloud, supports device data collection on the cloud and the cloud issues commands to devices for remote control, and cooperates with Huawei Cloud Other products help us quickly build IoT solutions.

Using the IoT platform to build a complete IoT solution mainly includes 3 parts: IoT platform, business applications and equipment.

As the middle layer that connects business applications and devices, the IoT platform shields various complex device interfaces and enables quick access to devices. It also provides powerful open capabilities to support industry users in building various IoT solutions.

Devices can access the IoT platform through fixed network, 2G/3G/4G/5G, NB-IoT, Wifi and other networks, and use LWM2M/CoAP, MQTT, HTTPS protocols to report business data to the platform. The platform can also Send control commands to the device.

Business applications implement business scenarios such as device data collection, command issuance, and device management by calling the API provided by the IoT platform.

image-20230801151124332

image-20230801151130369

4.2 Activate IoT services

Address: https://www.huaweicloud.com/product/iothub.html

image-20230801151136153

Click 总览to view access information. Our current equipment is going to use the MQTT protocol to connect to the Huawei Cloud platform. Here you can see the address and port number of the MQTT protocol and other information.

image-20230801151202953

Summarize:

端口号:   MQTT (1883)| MQTTS (8883)   
接入地址: a161a58a78.iot-mqtts.cn-north-4.myhuaweicloud.com

Get IP address information based on domain name address:

Microsoft Windows [版本 10.0.19045.2965]
(c) Microsoft Corporation。保留所有权利。

C:\Users\11266>ping a161a58a78.iot-mqtts.cn-north-4.myhuaweicloud.com

正在 Ping a161a58a78.iot-mqtts.cn-north-4.myhuaweicloud.com [121.36.42.100] 具有 32 字节的数据:
来自 121.36.42.100 的回复: 字节=32 时间=38ms TTL=94
来自 121.36.42.100 的回复: 字节=32 时间=37ms TTL=94
来自 121.36.42.100 的回复: 字节=32 时间=38ms TTL=94
来自 121.36.42.100 的回复: 字节=32 时间=36ms TTL=94

121.36.42.100 的 Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 36ms,最长 = 38ms,平均 = 37ms

C:\Users\11266>

image-20230801151212765

There are two MQTT protocol access port numbers. 1883 is a non-encrypted port and 8883 is a certificate encryption port. The microcontroller cannot load the certificate, so it is more appropriate to use port 1883. The next ESP8266 uses port 1883 to connect to the Huawei Cloud IoT platform.

4.3 Create products

(1) Create products

Click on the product page, then click Create Product in the upper left corner.

image-20230801151220860

(2) Fill in product information

Fill in the form based on your product name.

image-20230801151228433

(3) Product creation is successful

image-20230801151234528

(4) Add custom model

After the product is created, click to enter the product details page and scroll to the bottom to see the model definition.

This model is to define the data types that your device needs to upload to the server next. Write according to your own data type.

Click on Custom Model first.

image-20230801151243343

Create another service ID.

image-20230801151250227

Then click Add attribute.

image-20230801151255512

image-20230801151300240

4.4 Add device

The product is an abstract model belonging to the upper layer, and then the actual equipment is added under the product model. The added device eventually needs to be associated with the real device to complete data interaction.

(1) Register device

image-20230801151308625

(2) Fill in according to your own equipment

image-20230801151315386

(3) Save device information

After creation, click Save and Close to get the created device key information. This information is needed when generating MQTT triples later.

image-20230801151322328

(4) Device creation completed

You can click on the device to enter the device details page.

image-20230801151331651

4.5 MQTT protocol topic subscription and publishing

(1) Introduction to MQTT protocol

The current equipment uses the MQTT protocol to communicate with the Huawei Cloud Platform.

MQTT is an IoT transport protocol that is designed for lightweight publish/subscribe message transmission and aims to provide reliable network services for IoT devices in low-bandwidth and unstable network environments. MQTT is a lightweight transmission protocol developed specifically for the Internet of Things. The MQTT protocol has been specially optimized for low-bandwidth networks and devices with low computing power, making it adaptable to various IoT application scenarios. At present, MQTT has clients on various platforms and devices, and has formed a preliminary ecosystem.

MQTT is a message queue protocol that uses the publish/subscribe message model to provide one-to-many message publishing and decouple applications. Compared with other protocols, development is simpler; the MQTT protocol works on the TCP/IP protocol; by TCP The /IP protocol provides a stable network connection; therefore, any network device with a TCP protocol stack can use the MQTT protocol. The ESP8266 used in this device has a TCP protocol stack and can establish a TCP connection. Therefore, with the MQTT protocol encapsulated in the STM32 code, communication with the Huawei cloud platform can be completed.

Huawei Cloud's MQTT protocol access help document is here: https://support.huaweicloud.com/devg-iothub/iot_02_2200.html

image-20230801151337395

Business Process:

image-20230801151342879

(2) Huawei Cloud Platform MQTT protocol usage restrictions

describe limit
Supported MQTT protocol versions 3.1.1
Differences from the standard MQTT protocol Supports Qos 0 and Qos 1. Supports Topic customization. Does not support QoS2. Does not support will and retain msg.
Security levels supported by MQTTS Adopt TCP channel base + TLS protocol (up to TLSv1.3 version)
Maximum number of MQTT connection requests per second for a single account Unlimited
Maximum number of MQTT connections supported by a single device per minute 1
The throughput per second of a single MQTT connection, that is, the bandwidth, including directly connected devices and gateways 3KB/s
The maximum length of a single MQTT publishing message. Publishing requests exceeding this size will be directly rejected. 1MB
MQTT connection heartbeat time recommended value The heartbeat time is limited to 30 to 1200 seconds, and the recommended setting is 120 seconds
Does the product support custom topics? support
Message publishing and subscription The device can only publish and subscribe messages to its own Topic.
Maximum number of subscriptions per subscription request Unlimited

(3) Topic subscription format

Help document address: https://support.huaweicloud.com/devg-iothub/iot_02_2200.html

image-20230801151350067

image-20230801151355027

For devices, they generally subscribe to the topic of messages sent by the platform to the device.

If a device wants to receive messages sent by the platform, it needs to subscribe to the topic of messages sent by the platform to the device. After subscribing, the platform sends messages to the device, and the device will receive the message.

If the device wants to know the messages sent by the platform, it needs to subscribe to the topic marked in the picture above.

以当前设备为例,最终订阅主题的格式如下:
$oc/devices/{device_id}/sys/messages/down

最终的格式:
$oc/devices/6419627e40773741f9fbdac7_dev1/sys/messages/down

(4) Topic publishing format

For devices, topic publishing means uploading data to the cloud platform, and uploading the latest sensor data and device status to the cloud platform.

This operation is called: attribute reporting.

Help document address: https://support.huaweicloud.com/usermanual-iothub/iot_06_v5_3010.html

image-20230801151401246

According to the introduction of the help document, the current device publishing theme and the format of reported attributes are summarized as follows:

发布的主题格式:
$oc/devices/{device_id}/sys/properties/report
 
最终的格式:
$oc/devices/6419627e40773741f9fbdac7_dev1/sys/properties/report
发布主题时,需要上传数据,这个数据格式是JSON格式。

上传的JSON数据格式如下:

{
  "services": [
    {
      "service_id": <填服务ID>,
      "properties": {
        "<填属性名称1>": <填属性值>,
        "<填属性名称2>": <填属性值>,
        ..........
      }
    }
  ]
}
根据JSON格式,一次可以上传多个属性字段。 这个JSON格式里的,服务ID,属性字段名称,属性值类型,在前面创建产品的时候就已经介绍了,不记得可以翻到前面去查看。

根据这个格式,组合一次上传的属性数据:
{"services": [{"service_id": "stm32","properties":{"DS18B20":18,"motor_water":1,"motor_oxygen":1,"temp_max":10,"water_hp":130,"motor_food":0,"time_food":0,"oxygen_food":3}}]}

4.6 MQTT Triplets

MQTT protocol login requires filling in user ID, device ID, device password and other information. Just like when we usually log in to QQ and WeChat, we need to enter the account password to log in. These three parameters logged in the MQTT protocol are generally called MQTT triples.

Next, we will introduce how to obtain the MQTT triplet parameters of Huawei Cloud Platform.

(1) MQTT server address

To log in to the MQTT server, first remember to know the address and port of the server.

Help document address: https://console.huaweicloud.com/iotdm/?region=cn-north-4#/dm-portal/home

The port of the MQTT protocol supports 1883 and 8883. The difference between them is: 8883 is an encrypted port and is more secure. However, it is difficult to use on a microcontroller, so the current equipment uses the 1883 port for connection.

Based on the above domain name and port number, get the following IP address and port number information: If the device supports filling in the domain name, you can directly fill in the domain name, if not, directly fill in the IP address. (The IP address is obtained by domain name resolution)

华为云的MQTT服务器地址:114.116.232.138
域名:7445c6bcd3.st1.iotda-device.cn-north-4.myhuaweicloud.com
华为云的MQTT端口号:1883

Notice! ! ! ! See here for details:

image-20230801151408871

(2) Generate MQTT triples

Huawei Cloud provides an online tool to generate MQTT authentication triples: https://iot-tool.obs-website.cn-north-4.myhuaweicloud.com/

Open this tool, fill in the device information (that is, the information saved after creating the device just now), click Generate, and you can get the MQTT login information.

Here is the page that opens:

image-20230801151418248

Fill in the device information: (The above two lines are saved after the device is created)

After obtaining the triplet, when the device logs in for authentication through the MQTT protocol, just fill in the parameters.

ClientId 6419627e40773741f9fbdac7_dev1_0_0_2023032108
Username 6419627e40773741f9fbdac7_dev1
Password 861ac9e6a579d36888b2aaf97714be7af6c77017b017162884592bd68b086a6e

4.7 Simulate device login test

After the above steps, the product, device, and data model have been created, and the MQTT login information has been obtained. Next, use MQTT client software to simulate a real device to log in to the platform. Test whether communication with the server is normal.

(1) Fill in the login information

Open the MQTT client software and fill in the relevant information (the text introduction above). Then, click to log in, subscribe to the topic, and publish the topic.

image-20230801151429390

(2) Open the web page to view

After completing the above operations, open the Huawei Cloud web backend and you can see that the device is online.

Click on the details page to see the uploaded data.

At this point, the deployment of the cloud platform has been completed and the device can upload data normally.

4.8 Obtain device shadow data (API interface)

Help document: https://support.huaweicloud.com/api-iothub/iot_06_v5_0079.html

Device shadow introduction:

设备影子是一个用于存储和检索设备当前状态信息的JSON文档。
每个设备有且只有一个设备影子,由设备ID唯一标识
设备影子仅保存最近一次设备的上报数据和预期数据
无论该设备是否在线,都可以通过该影子获取和设置设备的属性

To put it simply: the device shadow is the latest data uploaded by the device.

In the software we designed, if we want to obtain the latest status information of the device, we use the device shadow interface.

If you are not familiar with the interface, you can perform online debugging first: https://apiexplorer.developer.huaweicloud.com/apiexplorer/doc?product=IoTDA&api=ShowDeviceShadow

Online debugging interface, you can request the shadow interface to understand the request and returned data format.

image-20230801151441245

The data returned by the device shadow interface is as follows:

{
    
    
 "device_id": "6419627e40773741f9fbdac7_dev1",
 "shadow": [
  {
    
    
   "service_id": "stm32",
   "desired": {
    
    
    "properties": null,
    "event_time": null
   },
   "reported": {
    
    
    "properties": {
    
    
     "DS18B20": 18,
     "motor_water": 1,
     "motor_oxygen": 1,
     "temp_max": 10,
     "water_hp": 130,
     "motor_food": 0,
     "time_food": 0,
     "oxygen_food": 3
    },
    "event_time": "20230321T081126Z"
   },
   "version": 0
  }
 ]
}

4.9 Modify device properties (API interface)

Address: https://support.huaweicloud.com/api-iothub/iot_06_v5_0034.html

Interface Description

设备的产品模型中定义了物联网平台可向设备下发的属性,应用服务器可调用此接口向指定设备下发属性。平台负责将属性以同步方式发送给设备,并将设备执行属性结果同步返回。

The interface for modifying device attributes allows the server to issue instructions to the device and control the device if needed.

Online debugging address:

https://apiexplorer.developer.huaweicloud.com/apiexplorer/doc?product=IoTDA&api=UpdateProperties

Modifying device properties is a synchronous command and requires the device to be online before debugging. First use the MQTT client to log in to the server and simulate the device going online.

Then debug and send the test data to the device remotely.

【1】Use MQTT client to log in to the device first (this is a synchronous command and must be online to debug)

image-20230801151450774

【2】Click to debug

image-20230801151457386

{
    
    "services":{
    
    "temp_max":100}}

【4】As you can see, the MQTT client software has received the message sent by the server.

image-20230801151505222

Since it is a synchronous command, the server must receive a response from the device to successfully complete a process. Only when the device responds can the server determine that the data is successfully delivered.

5. Code design

5.1 ESP8266 module introduction

ESP8266-WIFI is a low-cost Wi-Fi chip developed by Espressif Systems, which can be used in conjunction with other microcontrollers or microcontrollers to achieve wireless communication functions. The chip integrates a high-performance 32-bit Tensilica L106 RISC processor and a set of built-in WIFI modules and power management modules to provide stable wireless network connections at low power consumption.

The following is an introduction to commonly used AT commands related to ESP8266 and MQTT protocol:

【1】AT+CIPSTART: Establish TCP connection.

When using the MQTT protocol, a TCP connection needs to be established first. AT+CIPSTART can realize TCP connection with MQTT server, the format is as follows:

AT+CIPSTART="TCP","MQTT服务器地址",MQTT服务器端口号

【2】AT+CIPSEND: Send data.

After establishing a TCP connection, you can use AT+CIPSEND to send data, including various commands of the MQTT protocol. The format is as follows:

AT+CIPSEND=<length>
<MQTT命令>

Among them, represents the data length, and <MQTT command> represents the command of the MQTT protocol, such as CONNECT, PUBLISH, SUBSCRIBE, etc.

【3】AT+CIPCLOSE: Close the TCP connection. After using the MQTT protocol, you can use AT+CIPCLOSE to close the TCP connection. The format is as follows:

AT+CIPCLOSE

【4】AT+CIPSTATUS: Query the TCP connection status. Use AT+CIPSTATUS to query the status of the current TCP connection. The format is as follows:

AT+CIPSTATUS

The return value includes: STATUS, TCP connection status; LINK ID, TCP connection ID; IP, IP address of TCP connection; PORT, TCP connection port number.

【5】AT+MQTTCONN: Connect to MQTT server. Use AT+MQTTCONN to connect to the MQTT server. The format is as follows:

AT+MQTTCONN=<clientID>,<user>,<password>,<keepalive>,<clean>,<willTopic>,<willMessage>,<willQoS>,<willRetain>

Among them, represents the client ID; represents the user name; represents the password; represents the heartbeat packet interval; represents clearing the session flag; represents the subject of the last words; represents the message of the last words; represents the QoS level of the last words; represents whether the message of the last words is retained.

【6】AT+MQTTPUB: Publish messages. You can use AT+MQTTPUB to publish MQTT messages. The format is as follows:

AT+MQTTPUB=<topic>,<payload>,<QoS>,<retain>

Among them, represents the MQTT topic; represents the message load; represents the message QoS level; represents whether the message is retained.

【7】AT+MQTTSUB: Subscribe to the topic. Use AT+MQTTSUB to subscribe to MQTT topics, the format is as follows:

AT+MQTTSUB=<topic>,<QoS>

Among them, represents the MQTT topic; represents the message QoS level.

5.2 Connect to cloud code

The following is a sample code for STM32F103+ESP8266 to log in to the MQTT IoT server through the MQTT protocol to implement topic subscription and publishing. The AT command of the ESP8266-WIFI is used to achieve communication with the MQTT server.

The UART serial port needs to be configured on the STM32F103 to achieve communication with the ESP8266. Write the sending and receiving functions of AT instructions on STM32F103 and integrate them into the project.

code show as below:

#include "stm32f1xx_hal.h"
#include <string.h>
#include <stdio.h>

/* 定义ESP8266的UART串口 */
UART_HandleTypeDef huart1;

/* 定义MQTT服务器地址、端口号、用户名和密码等信息 */
const char* mqtt_server = "mqtt.example.com";
const int mqtt_port = 1883;
const char* mqtt_username = "username";
const char* mqtt_password = "password";

/* 定义MQTT主题 */
const char* mqtt_topic = "test/topic";

/* 定义回调函数,处理MQTT消息 */
void messageArrived(MessageData* data)
{
    
    
    printf("Message arrived: topic=%.*s, payload=%.*s\n", 
           data->topicName->lenstring.len, 
           data->topicName->lenstring.data, 
           data->message->payloadlen, 
           data->message->payload);
}

/* 发送AT指令并等待响应 */
int ESP8266_SendATCommand(char* cmd, char* response, int timeout)
{
    
    
    HAL_UART_Transmit(&huart1, (uint8_t*)cmd, strlen(cmd), timeout);

    int len = 0;
    int len_read = 0;
    HAL_Delay(100);
    while (1) {
    
    
        if (HAL_UART_Receive(&huart1, (uint8_t*)response + len, 1, timeout) == HAL_OK) {
    
    
            len++;
            if (strstr(response, "OK") != NULL) {
    
    
                return len;
            }
            if (strstr(response, "ERROR") != NULL) {
    
    
                return -1;
            }
            if (len >= 1024) {
    
    
                return -1;
            }
        }
    }
}

/* 连接MQTT服务器 */
int MQTT_Connect(void)
{
    
    
    char cmd[1024];
    char response[1024];

    /* 设置ESP8266为透传模式 */
    ESP8266_SendATCommand("AT+CIPMODE=1\r\n", response, 1000);
    ESP8266_SendATCommand("AT+CIPMUX=0\r\n", response, 1000);

    /* 建立TCP连接 */
    sprintf(cmd, "AT+CIPSTART=\"TCP\",\"%s\",%d\r\n", mqtt_server, mqtt_port);
    ESP8266_SendATCommand(cmd, response, 5000);

    /* 连接MQTT服务器 */
    sprintf(cmd, "AT+CIPSEND=%d\r\n", 33 + strlen(mqtt_username) + strlen(mqtt_password));
    ESP8266_SendATCommand(cmd, response, 1000);
    sprintf(cmd, "CONNECT\n\rclient_id:ESP8266\n\ruser:%s\n\rpassword:%s\n\r\n\r", mqtt_username, mqtt_password);
    ESP8266_SendATCommand(cmd, response, 5000);

    /* 订阅MQTT主题 */
    sprintf(cmd, "AT+CIPSEND=%d\r\n", 10 + strlen(mqtt_topic));
    ESP8266_SendATCommand(cmd, response, 1000);
    sprintf(cmd, "SUBSCRIBE\n\r%d\n\r0\n\r\n\r", strlen(mqtt_topic));
    ESP8266_SendATCommand(cmd, response, 5000);

    return 0;
}

/* 发布MQTT消息 */
void MQTT_Publish(const char* message)
{
    
    
    char cmd[1024];
    char response[1024];

    sprintf(cmd, "AT+CIPSEND=%d\r\n", 8 + strlen(mqtt_topic) + strlen(message));
    ESP8266_SendATCommand(cmd, response, 1000);
    sprintf(cmd, "PUBLISH\n\r%d\n\r%s\n\r\n\r%s\n\r", strlen(mqtt_topic), mqtt_topic, message);
    ESP8266_SendATCommand(cmd, response, 5000);
}

/* 主程序 */
int main(void)
{
    
    
    /* 连接MQTT服务器 */
    if (MQTT_Connect() != 0) {
    
    
        while (1) {
    
    
            /* 连接失败,进入死循环 */
        }
    }

    /* 发布MQTT消息 */
    MQTT_Publish("Hello, MQTT!");

    /* 等待接收MQTT消息 */
    while (1) {
    
    
        /* 读取ESP8266接收缓冲区中的数据 */
        char response[1024];
        int len = ESP8266_SendATCommand("AT+CIPRXGET=2,1024\r\n", response, 1000);
        if (len > 0) {
    
    
            printf("Received data: %.*s\n", len, response);
            /* TODO: 解析并处理MQTT消息 */
        }

        /* 延时一段时间 */
        HAL_Delay(100);
    }

    return 0;
}

The code implements functions such as connecting to the MQTT server, subscribing to topics, and publishing messages.

5.3 OLED display code

The following is the code for using STM32F103ZET6 to control the 0.96-inch OLED display with SPI interface:

cCopy Code#include "stm32f10x.h"
#include "spi.h" // SPI库头文件

// OLED相关定义
#define OLED_CMD  0 // 命令模式
#define OLED_DATA 1 // 数据模式

#define OLED_ADDR_START 0xB0 // OLED起始地址
#define OLED_PAGE_START 0x00 // 第一个页的地址
#define OLED_COLUMN_START 0x10 // 列起始地址

// 初始化OLED显示屏
void OLED_Init(void)
{
    
    
  // 初始化SPI接口
  SPI_Init();
  
  Delay(100);
  
  // 向OLED发送初始化命令和数据
  
  // 模式设置:设置4位数据线,扩展指令集
  OLED_WriteCmd(OLED_CMD, 0x21);
  // 对比度设置,默认为0x7F
  OLED_WriteCmd(OLED_CMD, 0x81);
  OLED_WriteCmd(OLED_CMD, 0x7F);
  // 设置显示模式:正常显示
  OLED_WriteCmd(OLED_CMD, 0xA4);
  // 设置偏置电压
  OLED_WriteCmd(OLED_CMD, 0xA8);
  OLED_WriteCmd(OLED_CMD, 0x3F);
  // 设置显示方向:从左到右,从上到下
  OLED_WriteCmd(OLED_CMD, 0xC8);
  // 设置扫描地段,从COM0到COM[N-1]
  OLED_WriteCmd(OLED_CMD, 0xDA);
  OLED_WriteCmd(OLED_CMD, 0x12);
  // 设置时钟分频因子
  OLED_WriteCmd(OLED_CMD, 0xD5);
  OLED_WriteCmd(OLED_CMD, 0x80);
  // 设置显示开启
  OLED_WriteCmd(OLED_CMD, 0xAF);
}

// 写入命令或数据到OLED显示屏
void OLED_WriteCmd(uint8_t mode, uint8_t cmd)
{
    
    
  if (mode == OLED_CMD) {
    
    
    GPIO_ResetBits(GPIOA, GPIO_Pin_4); // 将DC引脚置低,进入命令模式
  } else {
    
    
    GPIO_SetBits(GPIOA, GPIO_Pin_4); // 将DC引脚置高,进入数据模式
  }
  
  GPIO_ResetBits(GPIOA, GPIO_Pin_3); // 将CS引脚置低,选中OLED
  
  SPI_SendData(cmd); // 发送命令或数据
  
  while (SPI_GetFlagStatus(SPI1, SPI_FLAG_TXE) == RESET);
  
  GPIO_SetBits(GPIOA, GPIO_Pin_3); // 将CS引脚置高,释放OLED
}

// 在指定位置显示一个数字
void OLED_ShowNumber(uint8_t x, uint8_t y, uint32_t number)
{
    
    
  char str[11]; // 最大显示10位数字
  
  sprintf(str, "%lu", number); // 将数字转换为字符串
  
  OLED_ShowString(x, y, str); // 在指定位置显示字符串
}

// 在指定位置显示一个字符串
void OLED_ShowString(uint8_t x, uint8_t y, char *str)
{
    
    
  uint8_t i = 0;
  
  while (str[i] != '\0') {
    
    
    OLED_ShowChar(x, y, str[i]); // 在指定位置显示一个字符
    x += 6; // 移动到下一列
    i++;
  }
}

// 在指定位置显示一个字符
void OLED_ShowChar(uint8_t x, uint8_t y, char ch)
{
    
    
  uint8_t i, j;
  
  for (i = 0; i < 8; i++) {
    
     // 8行
    OLED_WriteCmd(OLED_CMD, OLED_ADDR_START + y); // 指定页
    OLED_WriteCmd(OLED_CMD, OLED_COLUMN_START + x); // 指定列
    
    for (j = 0; j < 6; j++) {
    
     // 6列
      OLED_WriteCmd(OLED_DATA, ASCII[ch - 32][j]);
    }
    
    y++;
  }
}

In this code, OLED-related constants and functions are defined, including OLED command mode and data mode, OLED start address, page start address, column start address, etc. The OLED initialization process is carried out in OLED_Init()the function, including sending corresponding initialization commands and data to the OLED display. In OLED_WriteCmd()the function, the DC pin is set to the corresponding state according to the incoming command mode (OLED_CMD) or data mode (OLED_DATA), and the command or data is sent to the OLED display through the SPI interface. In OLED_ShowNumber()the, OLED_ShowString()and functions, the corresponding instructions and data are sent OLED_ShowChar()by calling to display numbers, strings and characters at the specified position.OLED_WriteCmd()

5.4 Stepper motor control code

The following is the code for STM32F103+28BYJ40 stepper motor to implement angle control and forward and reverse control. The STM32F1xx_HAL library is used to control the GPIO port and timer to achieve precise angle control and forward and reverse control.

#include "stm32f1xx_hal.h"
#include <stdio.h>

/* 定义步进电机的4个控制引脚 */
#define IN1_Pin GPIO_PIN_0
#define IN1_GPIO_Port GPIOA
#define IN2_Pin GPIO_PIN_1
#define IN2_GPIO_Port GPIOA
#define IN3_Pin GPIO_PIN_2
#define IN3_GPIO_Port GPIOA
#define IN4_Pin GPIO_PIN_3
#define IN4_GPIO_Port GPIOA

/* 定义步进电机的步数数组 */
uint8_t step_sequence[8] = {
    
    0b0001, 0b0011, 0b0010, 0b0110, 0b0100, 0b1100, 0b1000, 0b1001};

/* 定义当前步进电机的位置和方向 */
int current_step = 0;  // 当前步数
int direction = 1;  // 1为顺时针,-1为逆时针

/* 定义角度控制参数 */
float angle_per_step = 1.8;  // 每步角度
int total_steps = 2048;  // 总步数

/* 定义定时器中断处理函数,控制步进电机的运动 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    
    
    /* 更新步进电机的位置 */
    current_step += direction;
    if (current_step >= total_steps) {
    
    
        current_step = 0;
    } else if (current_step < 0) {
    
    
        current_step = total_steps - 1;
    }

    /* 控制步进电机的旋转方向 */
    int sequence_index = current_step % 8;
    GPIO_PinState in1_state = (step_sequence[sequence_index] & 0b0001) ? GPIO_PIN_SET : GPIO_PIN_RESET;
    GPIO_PinState in2_state = (step_sequence[sequence_index] & 0b0010) ? GPIO_PIN_SET : GPIO_PIN_RESET;
    GPIO_PinState in3_state = (step_sequence[sequence_index] & 0b0100) ? GPIO_PIN_SET : GPIO_PIN_RESET;
    GPIO_PinState in4_state = (step_sequence[sequence_index] & 0b1000) ? GPIO_PIN_SET : GPIO_PIN_RESET;
    HAL_GPIO_WritePin(IN1_GPIO_Port, IN1_Pin, in1_state);
    HAL_GPIO_WritePin(IN2_GPIO_Port, IN2_Pin, in2_state);
    HAL_GPIO_WritePin(IN3_GPIO_Port, IN3_Pin, in3_state);
    HAL_GPIO_WritePin(IN4_GPIO_Port, IN4_Pin, in4_state);
}

/* 初始化定时器 */
void TIM_Init(void)
{
    
    
    TIM_HandleTypeDef htim;

    /* 使能定时器时钟 */
    __HAL_RCC_TIM2_CLK_ENABLE();

    /* 配置定时器 */
    htim.Instance = TIM2;
    htim.Init.Prescaler = 7199;  // 72MHz / 7200 = 10kHz
    htim.Init.CounterMode = TIM_COUNTERMODE_UP;
    htim.Init.Period = 99;  // 10kHz / 100 = 100Hz
    htim.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
    HAL_TIM_Base_Init(&htim);

    /* 启动定时器 */
    HAL_TIM_Base_Start_IT(&htim);
}

/* 控制步进电机旋转 */
void StepMotor_Rotate(int angle, int clockwise)
{
    
    
    /* 计算需要旋转的步数和方向 */
    int steps = angle / angle_per_step;
    direction = clockwise ? 1 : -1;

    /* 控制步进电机旋转 */
    for (int i = 0; i < steps; i++) {
    
    
        HAL_Delay(1);
    }
}

/* 主程序 */
int main(void)
{
    
    
    /* 初始化定时器 */
    TIM_Init();

    /* 控制步进电机旋转 */
    StepMotor_Rotate(90, 1);  // 顺时针旋转90度
    StepMotor_Rotate(180, 0);  // 逆时针旋转180度

    while (1) {
    
    
        /* 循环等待 */
    }

    return 0;
}

IN1_Pin to IN4_Pin are the control pins of the stepper motor, step_sequence is the step array of the stepper motor, current_step is the current number of steps, direction is the direction of rotation, angle_per_step is the angle of each step, and total_steps is the total number of steps. In the HAL_TIM_PeriodElapsedCallback function, the rotation direction of the stepper motor is controlled based on the current number of steps and rotation direction, and the HAL_GPIO_WritePin function is used to control the pin output state. In the StepMotor_Rotate function, the number and direction of rotation are calculated based on the incoming angle and direction of rotation, and then the stepper motor rotation is controlled by a loop delay. By calling the StepMotor_Rotate function, the angle control and forward and reverse control of the stepper motor can be realized.

6. Summary

The smart access control system is a safe and convenient access control solution based on the STM32F103 main controller and Huawei Cloud IoT platform. By integrating a variety of hardware modules and network communication technology, the system realizes a variety of unlocking methods (password input, RFID card swiping, mobile phone APP remote unlocking), and has remote monitoring and message push functions.

In terms of hardware selection, the card swiping module selected RFID-RC522, using a 28BYJ-48 stepper motor as the door lock controller, a 4x4 capacitive matrix keyboard for password input, and a 0.96-inch OLED display with SPI interface for door lock status information. display, and the ESP8266-WIFI module implements the networking function. In addition, an infrared magnetic induction module is used to detect the status of the door.

The design of the entire system makes access control more secure and reliable. Users can unlock the door in a variety of ways, including entering passwords, swiping cards, and remotely unlocking. At the same time, the system can monitor the status of the door lock in real time and send notification reminders to the user through the mobile APP when the door lock is opened or closed, improving user safety and convenience.

The smart access control system based on STM32F103 and Huawei Cloud IoT platform makes full use of the advantages of modern technology to provide safe and convenient access control solutions. In addition to basic access control functions, the system also has remote control and real-time monitoring capabilities, bringing users a more intelligent access control experience and meeting modern people's needs for safe and convenient life.

Guess you like

Origin blog.csdn.net/xiaolong1126626497/article/details/133203624