DHT11的C语言STM代码
时间: 2023-11-12 19:10:44 浏览: 90
DHT11.zip_32dth11_STM32 sensor_STM32+DTH11_STM32的DTH11代码_stm32 d
以下是DHT11的C语言STM代码:
```
#include "stm32f10x.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_rcc.h"
GPIO_InitTypeDef GPIO_InitStructure;
void delay_us(uint32_t nTime)
{
uint32_t TimingDelay = nTime;
while(TimingDelay--);
}
void DHT11_start(void)
{
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_SetBits(GPIOB, GPIO_Pin_7);
delay_us(1000);
GPIO_ResetBits(GPIOB, GPIO_Pin_7);
delay_us(18000);
GPIO_SetBits(GPIOB, GPIO_Pin_7);
}
uint8_t DHT11_read(void)
{
uint8_t i,j;
uint8_t data = 0;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOB, &GPIO_InitStructure);
for(i=0;i<8;i++)
{
while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_7)==RESET);
delay_us(40);
if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_7)==SET)
{
j=1;
while(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_7)==SET)
{
delay_us(1);
j++;
if(j>100) break;
}
data |= (1<<(7-i));
}
}
return data;
}
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
while(1)
{
DHT11_start();
uint8_t RH_integral = DHT11_read();
uint8_t RH_decimal = DHT11_read();
uint8_t T_integral = DHT11_read();
uint8_t T_decimal = DHT11_read();
uint8_t checksum = DHT11_read();
if((RH_integral + RH_decimal + T_integral + T_decimal) == checksum)
{
//数据正常
}
else
{
//数据错误
}
}
}
```
阅读全文