帮我写一个基于stm32f103c8t6控制DHT11温湿度传感器控制灯,当温度过高,灯亮起的代码
时间: 2024-04-25 07:02:44 浏览: 77
STM32控制DHT11数字温湿度传感器_DHT11_STM32F103_
5星 · 资源好评率100%
好的,这里给您提供一个基于STM32F103C8T6和DHT11温湿度传感器的代码,当温度超过设定值时,点亮LED灯。
代码如下:
```c
#include "stm32f10x.h"
#define DHT11_DATA_PIN GPIO_Pin_0
#define DHT11_DATA_PORT GPIOA
#define LED_PIN GPIO_Pin_1
#define LED_PORT GPIOA
void delay_us(uint32_t us) {
SysTick->LOAD = 72 * us;
SysTick->VAL = 0;
SysTick->CTRL = SysTick_CTRL_ENABLE_Msk;
while ((SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) == 0);
SysTick->CTRL = 0;
}
void delay_ms(uint32_t ms) {
while (ms--) {
delay_us(1000);
}
}
void DHT11_Init(void) {
GPIO_InitTypeDef GPIO_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStruct.GPIO_Pin = DHT11_DATA_PIN;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_OD;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(DHT11_DATA_PORT, &GPIO_InitStruct);
GPIO_SetBits(DHT11_DATA_PORT, DHT11_DATA_PIN);
}
void DHT11_Start(void) {
GPIO_WriteBit(DHT11_DATA_PORT, DHT11_DATA_PIN, RESET);
delay_ms(18);
GPIO_WriteBit(DHT11_DATA_PORT, DHT11_DATA_PIN, SET);
delay_us(30);
}
uint8_t DHT11_Check_Response(void) {
uint8_t Response = 0;
delay_us(40);
if (!GPIO_ReadInputDataBit(DHT11_DATA_PORT, DHT11_DATA_PIN)) {
delay_us(80);
if (GPIO_ReadInputDataBit(DHT11_DATA_PORT, DHT11_DATA_PIN)) {
Response = 1;
} else {
Response = -1;
}
}
while (GPIO_ReadInputDataBit(DHT11_DATA_PORT, DHT11_DATA_PIN));
return Response;
}
uint8_t DHT11_Read(void) {
uint8_t i, j;
uint8_t data = 0;
for (j = 0; j < 8; j++) {
while (!GPIO_ReadInputDataBit(DHT11_DATA_PORT, DHT11_DATA_PIN));
delay_us(40);
if (GPIO_ReadInputDataBit(DHT11_DATA_PORT, DHT11_DATA_PIN) == 0) {
i = 0;
while (!GPIO_ReadInputDataBit(DHT11_DATA_PORT, DHT11_DATA_PIN));
for (i = 0; i < 8; i++) {
delay_us(30);
if (GPIO_ReadInputDataBit(DHT11_DATA_PORT, DHT11_DATA_PIN)) {
data |= 1 << (7 - i);
}
while (GPIO_ReadInputDataBit(DHT11_DATA_PORT, DHT11_DATA_PIN));
}
}
}
return data;
}
int main(void) {
GPIO_InitTypeDef GPIO_InitStruct;
uint8_t Temp = 0, RH = 0;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStruct.GPIO_Pin = LED_PIN;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_PORT, &GPIO_InitStruct);
DHT11_Init();
while (1) {
DHT11_Start();
if (DHT11_Check_Response() == 1) {
RH = DHT11_Read();
Temp = DHT11_Read();
if (Temp > 30) {
GPIO_SetBits(LED_PORT, LED_PIN);
} else {
GPIO_ResetBits(LED_PORT, LED_PIN);
}
}
delay_ms(2000);
}
}
```
在这个代码中,我们使用了STM32F103C8T6的SysTick定时器来实现延时功能。我们还使用了DHT11的三个函数来读取温湿度值,并利用读取到的温度值来控制LED灯的亮灭。
当温度大于30摄氏度时,LED灯会点亮;否则,LED灯会熄灭。您可以根据实际需求修改这个阈值。
阅读全文