用stm32驱动dht11
时间: 2023-09-08 12:10:17 浏览: 150
以下是使用STM32驱动DHT11的示例代码:
```
#include "stm32f10x.h"
#define DHT11_PIN GPIO_Pin_0
#define DHT11_PORT GPIOA
#define DHT11_TIMEOUT 10000
void delay_us(uint32_t us) {
uint32_t count = us * (SystemCoreClock / 1000000) / 5;
while (count--);
}
void DHT11_Start(void) {
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = DHT11_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(DHT11_PORT, &GPIO_InitStructure);
GPIO_SetBits(DHT11_PORT, DHT11_PIN);
delay_us(1000);
GPIO_ResetBits(DHT11_PORT, DHT11_PIN);
delay_us(18000);
GPIO_SetBits(DHT11_PORT, DHT11_PIN);
delay_us(30);
}
uint8_t DHT11_Check_Response(void) {
uint8_t count = 0;
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = DHT11_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(DHT11_PORT, &GPIO_InitStructure);
while (GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == SET) {
count++;
if (count > DHT11_TIMEOUT)
return 1;
delay_us(1);
}
count = 0;
while (GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == RESET) {
count++;
if (count > DHT11_TIMEOUT)
return 1;
delay_us(1);
}
count = 0;
while (GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == SET) {
count++;
if (count > DHT11_TIMEOUT)
return 1;
delay_us(1);
}
return 0;
}
uint8_t DHT11_Read_Bit(void) {
uint8_t count = 0;
while (GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == RESET) {
count++;
if (count > DHT11_TIMEOUT)
return 1;
delay_us(1);
}
delay_us(40);
if (GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == SET)
return 1;
else
return 0;
}
uint8_t DHT11_Read_Byte(void) {
uint8_t i, data = 0;
for (i = 0; i < 8; i++) {
data <<= 1;
if (DHT11_Read_Bit())
data |= 1;
}
return data;
}
uint8_t DHT11_Read_Data(uint8_t *humidity, uint8_t *temperature) {
uint8_t i, data[5];
DHT11_Start();
if (DHT11_Check_Response()) {
return 1;
}
for (i = 0; i < 5; i++) {
data[i] = DHT11_Read_Byte();
}
*humidity = data[0];
*temperature = data[2];
return 0;
}
int main(void) {
uint8_t humidity, temperature;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
while (1) {
if (DHT11_Read_Data(&humidity, &temperature) == 0) {
//读取到温湿度数据,进行处理
}
delay_us(2000000);
}
}
```
阅读全文