stm32 检测温度,用的是DHT11,读取显示总是0000,是程序的问题么?
#include "stm32f10x.h" // Device header
#include "Delay.h"
uint16_t Time = 0;
void DHT11_Start(void) //引脚发送起始信号
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //开启GPIOB的时钟
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;//将PB0引脚初始化为推挽输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_ResetBits(GPIOB, GPIO_Pin_0);//PB0低电平18毫秒
Delay_ms(18);
GPIO_SetBits(GPIOB, GPIO_Pin_0);//PB0高电平40微秒
Delay_us(40);
}
void DHT11_Response(void)//手动应答成功
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;//将PB0引脚初始化为上拉输入
GPIO_InitStructure.GPIO_Pin = 0;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
while((GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_0) == 0) && (Time < 100))//B0口读取输入=0 100微秒
{
Time ++ ;
Delay_us(1);
}
Time = 0;
while((GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_0) == 1) && (Time < 100))//B0口读取输入=1 100微秒
{
Time ++ ;
Delay_us(1);
}
Time = 0;
}
uint8_t DHT11_Read_Byte(void)//读取一个字节
{
uint8_t i = 0;
uint8_t Data = 0;
for (i = 0; i < 8; i ++)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //开启GPIOA的时钟
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;//软件实现5K上拉电阻
GPIO_InitStructure.GPIO_Pin = 0;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure); //调用库函数初始化GPIOB
while((GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_0) == 0) && (Time < 50))//50微秒的低电平
{
Time ++ ;
Delay_us(1);
}
Time = 0;
Data <<= 1;//数据左移一位
Delay_us(40);//等40微秒26~28秒高电平是0,70微秒的高电平是1
if(GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_0) == 1)
{
Data |= 0x01;//数据低位补充
while((GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_0) == 1) && (Time < 30))
{
Time ++ ;
Delay_us(1);
}
Time = 0;
}
}
return Data;
}
void DHT11_Read_Data(uint8_t *humi, uint8_t *temp)
{
uint8_t i;
uint8_t DATA[5] = {0, 0, 0, 0, 0};
DHT11_Start();
DHT11_Response();
for (i = 0; i < 5; i ++)
{
DATA[i] = DHT11_Read_Byte();
}
Delay_ms(1);
if (DATA[0] + DATA[1] + DATA[2] + DATA[3] == DATA[4])
{
*humi = DATA[0];
*temp = DATA[2];
}
else
{
for (i = 0; i < 5; i ++)
{
DATA[i] = 0;
}
}
}
DHT11.h
#ifndef __DHT11_H
#define __DHT11_H
uint8_t DHT11_Read_Byte(void);
void DHT11_Read_Data(uint8_t *humi, uint8_t *temp);
#endif
main.c
#include "stm32f10x.h"
#include "OLED.h"
#include "Delay.h"
#include "DH11.h"
uint8_t humi, temp, KeyNum;
int main(void)
{
OLED_Init();
while (1)
{
DHT11_Read_Data(&humi, &temp);
OLED_ShowNum(0, 0, temp, 4, OLED_8X16);
OLED_ShowNum(60, 0, humi, 4, OLED_8X16);
OLED_Update();
}
}