stm32f103c8t6驱动dht11代码
时间: 2023-10-16 14:06:15 浏览: 49
好的,以下是基于STM32F103C8T6驱动DHT11的代码:
```c
#include "stm32f10x.h"
#include "dht11.h"
#define DHT11_GPIO GPIOA
#define DHT11_PIN GPIO_Pin_0
void DHT11_Init(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_GPIO, &GPIO_InitStructure);
}
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_GPIO, &GPIO_InitStructure);
GPIO_SetBits(DHT11_GPIO, DHT11_PIN);
delay_us(30);
GPIO_ResetBits(DHT11_GPIO, DHT11_PIN);
delay_ms(18);
GPIO_SetBits(DHT11_GPIO, DHT11_PIN);
delay_us(40);
}
uint8_t DHT11_Check_Response(void)
{
uint8_t Response = 0;
delay_us(40);
if (!(GPIO_ReadInputDataBit(DHT11_GPIO, DHT11_PIN)))
{
delay_us(80);
if ((GPIO_ReadInputDataBit(DHT11_GPIO, DHT11_PIN)))
Response = 1;
else
Response = -1;
}
while ((GPIO_ReadInputDataBit(DHT11_GPIO, DHT11_PIN)));
return Response;
}
uint8_t DHT11_Read(void)
{
uint8_t i, j;
for (j = 0; j < 8; j++)
{
while (!(GPIO_ReadInputDataBit(DHT11_GPIO, DHT11_PIN)));
delay_us(40);
if (!(GPIO_ReadInputDataBit(DHT11_GPIO, DHT11_PIN)))
i &= ~(1 << (7 - j));
else
i |= (1 << (7 - j));
while ((GPIO_ReadInputDataBit(DHT11_GPIO, DHT11_PIN)));
}
return i;
}
void DHT11_Get_Data(uint8_t *temp, uint8_t *humi)
{
uint8_t Response = 0;
uint8_t Rh_byte1, Rh_byte2, Temp_byte1, Temp_byte2;
uint16_t SUM;
DHT11_Start();
Response = DHT11_Check_Response();
if (Response == 1)
{
Rh_byte1 = DHT11_Read();
Rh_byte2 = DHT11_Read();
Temp_byte1 = DHT11_Read();
Temp_byte2 = DHT11_Read();
SUM = DHT11_Read();
if (SUM == (Rh_byte1 + Rh_byte2 + Temp_byte1 + Temp_byte2))
{
*humi = Rh_byte1;
*temp = Temp_byte1;
}
}
}
void delay_us(uint32_t us)
{
uint32_t i;
for (i = 0; i < us; i++)
__NOP();
}
void delay_ms(uint32_t ms)
{
uint32_t i;
for (i = 0; i < ms; i++)
delay_us(1000);
}
```