基于stm32的rc522温湿度模块代码
时间: 2023-11-03 22:08:31 浏览: 64
以下是基于STM32的RC522温湿度模块代码,需要配合RC522和DHT11使用:
```c
#include "main.h"
#include "rc522.h"
#include "dht11.h"
#include <stdio.h>
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
UART_HandleTypeDef huart2;
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART2_UART_Init();
rc522_init(); // 初始化RC522
dht11_init(); // 初始化DHT11
while (1)
{
uint8_t uid[5];
int8_t status = rc522_request(PICC_REQIDL, uid); // 寻卡
if (status == MI_OK) // 如果寻卡成功
{
status = rc522_anticol(uid); // 防冲撞
if (status == MI_OK)
{
float temp, humi;
dht11_read(&temp, &humi); // 读取温湿度
char message[100];
sprintf(message, "UID:%02X%02X%02X%02X%02X Temp:%.1f Humi:%.1f\r\n", uid[0], uid[1], uid[2], uid[3], uid[4], temp, humi);
HAL_UART_Transmit(&huart2, (uint8_t *)message, strlen(message), 100); // 发送数据
}
}
HAL_Delay(1000); // 延时1s
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
| RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
{
Error_Handler();
}
}
static void MX_USART2_UART_Init(void)
{
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
}
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOA_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOA, RC522_CS_Pin | RC522_RST_Pin, GPIO_PIN_RESET);
/*Configure GPIO pins : RC522_CS_Pin RC522_RST_Pin */
GPIO_InitStruct.Pin = RC522_CS_Pin | RC522_RST_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
```
需要注意的是,此代码中使用的是DHT11温湿度传感器,如果需要使用其他类型的传感器,需要修改dht11.c和dht11.h中的相关代码。
阅读全文