基于STM32f103zet6的dht11温湿度传感器数据采集代码
时间: 2023-09-12 15:10:20 浏览: 126
以下是基于STM32f103zet6的dht11温湿度传感器数据采集代码,你可以根据自己的实际情况进行修改和调试:
```c
#include "stm32f10x.h"
#include "dht11.h"
#include "delay.h"
int main(void)
{
uint8_t res;
uint8_t humi, temp;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //使能GPIOB时钟
DHT11_Init(); //初始化DHT11
while(1) {
res = DHT11_Read_Data(&humi, &temp); //读取温湿度数据
if(res == 0) { //读取成功
printf("Temperature: %d.%d *C, Humidity: %d.%d %%\r\n", temp/10, temp%10, humi/10, humi%10);
}
else { //读取失败
printf("Read error!\r\n");
}
Delay_Ms(2000); //延时2s
}
}
```
其中,`dht11.h`和`delay.h`是需要自己编写的头文件,可以参考下面的示例代码:
```c
#ifndef __DHT11_H
#define __DHT11_H
#include "stm32f10x.h"
#define DHT11_PIN GPIO_Pin_0
#define DHT11_GPIO GPIOB
#define DHT11_RCC RCC_APB2Periph_GPIOB
void DHT11_Init(void);
uint8_t DHT11_Read_Byte(void);
uint8_t DHT11_Read_Data(uint8_t *humi, uint8_t *temp);
#endif
```
```c
#ifndef __DELAY_H
#define __DELAY_H
#include "stm32f10x.h"
void Delay_Init(void);
void Delay_Ms(uint16_t nms);
void Delay_Us(uint32_t nus);
#endif
```
以下是`dht11.c`和`delay.c`的代码示例,你可以根据自己的需求进行修改和完善:
```c
#include "dht11.h"
#include "delay.h"
//DHT11初始化
void DHT11_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(DHT11_RCC, ENABLE); //使能GPIOB时钟
GPIO_InitStructure.GPIO_Pin = DHT11_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //输出模式
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //50MHz
GPIO_Init(DHT11_GPIO, &GPIO_InitStructure); //初始化GPIO
}
//DHT11读取一个字节
uint8_t DHT11_Read_Byte(void)
{
uint8_t i, byte = 0;
for(i=0; i<8; i++) {
while(!GPIO_ReadInputDataBit(DHT11_GPIO, DHT11_PIN)); //等待高电平
Delay_Us(30); //延时30us
if(GPIO_ReadInputDataBit(DHT11_GPIO, DHT11_PIN)) { //如果仍是高电平
byte |= (1<<(7-i)); //写入数据,MSB先传输
while(GPIO_ReadInputDataBit(DHT11_GPIO, DHT11_PIN)); //等待低电平
}
}
return byte;
}
//DHT11读取温湿度数据
uint8_t DHT11_Read_Data(uint8_t *humi, uint8_t *temp)
{
uint8_t buf[5], i;
GPIO_ResetBits(DHT11_GPIO, DHT11_PIN); //发送起始信号
Delay_Ms(18);
GPIO_SetBits(DHT11_GPIO, DHT11_PIN);
Delay_Us(30);
if(!GPIO_ReadInputDataBit(DHT11_GPIO, DHT11_PIN)) { //等待DHT11响应
while(!GPIO_ReadInputDataBit(DHT11_GPIO, DHT11_PIN)); //等待DHT11响应完成
for(i=0; i<5; i++) {
buf[i] = DHT11_Read_Byte(); //读取5个字节的数据
}
if((buf[0]+buf[1]+buf[2]+buf[3]) == buf[4]) { //校验和正确
*humi = buf[0];
*temp = buf[2];
return 0; //返回读取成功
}
}
return 1; //返回读取失败
}
```
```c
#include "delay.h"
static uint32_t TimingDelay;
//延时初始化
void Delay_Init(void)
{
SysTick->CTRL = 0x00;
SysTick->LOAD = SystemCoreClock / 1000000 - 1;
SysTick->VAL = 0x00;
SysTick->CTRL = 0x05;
}
//延时nms
void Delay_Ms(uint16_t nms)
{
TimingDelay = nms;
while(TimingDelay != 0);
}
//延时nus
void Delay_Us(uint32_t nus)
{
uint32_t ticks;
ticks = nus * (SystemCoreClock / 1000000);
while(ticks--);
}
//SysTick中断处理函数
void SysTick_Handler(void)
{
if(TimingDelay != 0x00) {
TimingDelay--;
}
}
```
阅读全文