基于stm32f103c8t6标准库的DHT11测温代码
时间: 2023-07-29 21:09:25 浏览: 124
基于stm32的DHT11传感器代码
5星 · 资源好评率100%
好的,以下是基于STM32F103C8T6标准库的DHT11测温代码,供参考:
```c
#include "stm32f10x.h"
#include "delay.h"
#define DHT11_PORT GPIOC
#define DHT11_PIN GPIO_Pin_3
void DHT11_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, 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_ms(1000);
}
uint8_t DHT11_Read_Byte(void)
{
uint8_t i, data = 0;
for(i=0; i<8; i++)
{
while(!GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN));
delay_us(30);
if(GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN))
data |= (1<<(7-i));
while(GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN));
}
return data;
}
uint8_t DHT11_Read_TempAndHumidity(float *Temp, float *Humidity)
{
uint8_t i, j, check_sum;
uint8_t DHT11Data[5];
GPIO_ResetBits(DHT11_PORT, DHT11_PIN);
delay_ms(18);
GPIO_SetBits(DHT11_PORT, DHT11_PIN);
delay_us(40);
if(GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN))
return 1;
delay_us(80);
if(!GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN))
return 2;
delay_us(80);
for(i=0; i<5; i++)
DHT11Data[i] = DHT11_Read_Byte();
GPIO_SetBits(DHT11_PORT, DHT11_PIN);
check_sum = DHT11Data[0] + DHT11Data[1] + DHT11Data[2] + DHT11Data[3];
if(check_sum != DHT11Data[4])
return 3;
*Humidity = (float)DHT11Data[0] + (float)DHT11Data[1]/10.0;
*Temp = (float)DHT11Data[2] + (float)DHT11Data[3]/10.0;
return 0;
}
int main(void)
{
float Temp, Humidity;
DHT11_Init();
while(1)
{
if(DHT11_Read_TempAndHumidity(&Temp, &Humidity) == 0)
{
printf("Temperature: %.1f C, Humidity: %.1f%%\n", Temp, Humidity);
}
delay_ms(2000);
}
}
```
这个程序使用了STM32F103C8T6的标准库和一个DHT11传感器来测量温度和湿度。程序首先初始化GPIO口,然后读取DHT11传感器来获取温度和湿度值。最后,程序会将读取到的温度和湿度值通过串口打印出来,然后等待2秒钟再次读取。
阅读全文