用stm32f103c8t6的标准库的A11引脚写一个读取dht11传感器的湿度的代码
时间: 2024-01-05 07:03:08 浏览: 51
由于DHT11传感器的数据是通过单总线协议传输的,因此需要先设置GPIO口为输入模式,然后发送起始信号,接收传感器返回的数据,最后计算湿度值。
以下是用stm32f103c8t6的标准库的A11引脚读取dht11传感器湿度的代码:
```c
#include "stm32f10x.h"
#include <stdio.h>
#define DHT11_PIN GPIO_Pin_11
#define DHT11_PORT GPIOA
void delay_us(uint32_t us) {
uint32_t count = us * (SystemCoreClock / 1000000) / 5;
while(count--);
}
void DHT11_Start(void) {
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
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(20);
GPIO_InitStructure.GPIO_Pin = DHT11_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(DHT11_PORT, &GPIO_InitStructure);
}
uint8_t DHT11_ReadBit(void) {
uint8_t retry = 0;
while (GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == RESET) {
if (retry++ > 100) return 0;
delay_us(1);
}
delay_us(40);
if (GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == SET) {
return 1;
} else {
return 0;
}
}
uint8_t DHT11_ReadByte(void) {
uint8_t i, data = 0;
for (i = 0; i < 8; i++) {
data <<= 1;
data |= DHT11_ReadBit();
}
return data;
}
uint8_t DHT11_ReadData(uint8_t *temperature, uint8_t *humidity) {
uint8_t data[5];
uint8_t i;
DHT11_Start();
if (GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == RESET) {
while (GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == RESET);
while (GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == SET);
for (i = 0; i < 5; i++) {
data[i] = DHT11_ReadByte();
}
if (data[4] == (data[0] + data[1] + data[2] + data[3])) {
*humidity = data[0];
*temperature = data[2];
return 1;
}
}
return 0;
}
int main(void) {
uint8_t temperature, humidity;
while(1) {
if (DHT11_ReadData(&temperature, &humidity) == 1) {
printf("Temperature: %d*C, Humidity: %d%%\n", temperature, humidity);
} else {
printf("Read failed\n");
}
delay_us(1000000);
}
}
```
注:由于DHT11的数据传输速率很慢,因此在读取数据时需要适当延长延时时间(例如上面的代码中的delay_us函数)。如果延时时间过短,可能会导致读取失败。
阅读全文