基于stm32的温湿度检测代码
时间: 2023-08-24 10:09:56 浏览: 39
以下是基于STM32的温湿度检测代码的示例:
```c
#include "stm32f10x.h"
#include "dht11.h"
GPIO_InitTypeDef GPIO_InitStructure;
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
DHT11_Init();
while(1)
{
uint8_t temp, humi;
if(DHT11_Read_TempAndHumidity(&temp, &humi) == SUCCESS)
{
printf("Temperature: %d°C, Humidity: %d%%\n", temp, humi);
}
else
{
printf("Failed to read temperature and humidity\n");
}
Delay_ms(2000);
}
}
void Delay_us(uint32_t us)
{
uint32_t i;
for(i = 0; i < us; i++)
{
asm("NOP");
}
}
void Delay_ms(uint32_t ms)
{
uint32_t i;
for(i = 0; i < ms; i++)
{
Delay_us(1000);
}
}
void DHT11_Init(void)
{
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void DHT11_Set_Mode(uint8_t mode)
{
if(mode == DHT11_MODE_OUTPUT)
{
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
}
else
{
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPD;
}
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
uint8_t DHT11_Read_Bit(void)
{
while(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == Bit_RESET);
Delay_us(40);
if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == Bit_SET)
{
while(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == Bit_SET);
return 1;
}
else
{
while(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == Bit_RESET);
return 0;
}
}
uint8_t DHT11_Read_Byte(void)
{
uint8_t i;
uint8_t data = 0;
for(i = 0; i < 8; i++)
{
data <<= 1;
data |= DHT11_Read_Bit();
}
return data;
}
uint8_t DHT11_Read_TempAndHumidity(uint8_t* temp, uint8_t* humi)
{
uint8_t data[5];
uint8_t i;
DHT11_Set_Mode(DHT11_MODE_OUTPUT);
GPIO_ResetBits(GPIOA, GPIO_Pin_0);
Delay_ms(18);
GPIO_SetBits(GPIOA, GPIO_Pin_0);
Delay_us(40);
DHT11_Set_Mode(DHT11_MODE_INPUT);
if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == Bit_RESET)
{
while(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == Bit_RESET);
while(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0) == Bit_SET);
for(i = 0; i < 5; i++)
{
data[i] = DHT11_Read_Byte();
}
if(data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF))
{
*humi = data[0];
*temp = data[2];
return SUCCESS;
}
else
{
return FAILURE;
}
}
else
{
return FAILURE;
}
}
```
这个示例使用了DHT11温湿度传感器。在主函数中,不断读取温度和湿度并打印出来。```DHT11_Init```函数用于初始化GPIO,```DHT11_Set_Mode```函数用于设置GPIO的输入/输出模式,```DHT11_Read_Bit```函数用于读取一个位,```DHT11_Read_Byte```函数用于读取一个字节,```DHT11_Read_TempAndHumidity```函数用于读取温湿度数据。```Delay_us```和```Delay_ms```函数用于延时。
阅读全文