实验器材
- CW32饭盒派开发板
- DHT11温湿度传感器
接线
开发板 |
DHT11 |
---|
VCC |
+ |
GND |
GND |
PB1 |
OUT |
程序
- dht11.c
#include "dht11.h"
void DHT11_Rst(void)
{
PB01_DIR_OUTPUT();
PB01_SETLOW();
delay1ms(20);
PB01_SETHIGH();
delay10us(3);
}
uint8_t DHT11_Check(void)
{
uint8_t retry=0;
PB01_DIR_INPUT();
while (PB01_GETVALUE()&&retry<10)
{
retry++;
delay10us(1);
};
if(retry>=10)return 1;
else retry=0;
while (!PB01_GETVALUE()&&retry<10)
{
retry++;
delay10us(1);
};
if(retry>=10)return 1;
return 0;
}
uint8_t DHT11_Read_Bit(void)
{
uint8_t retry=0;
while(PB01_GETVALUE()&&retry<10)
{
retry++;
delay10us(1);
}
retry=0;
while(!PB01_GETVALUE()&&retry<10)
{
retry++;
delay10us(1);
}
delay10us(4);
if(PB01_GETVALUE())return 1;
else return 0;
}
uint8_t DHT11_Read_Byte(void)
{
uint8_t i,dat;
dat=0;
for (i=0;i<8;i++)
{
dat<<=1;
dat|=DHT11_Read_Bit();
}
return dat;
}
uint8_t DHT11_Read_Data(float *temp,uint8_t *humi)
{
char buf[5];
uint8_t i;
DHT11_Rst();
if(DHT11_Check()==0)
{
for(i=0;i<5;i++)
{
buf[i]=DHT11_Read_Byte();
}
if((buf[0]+buf[1]+buf[2]+buf[3])==buf[4])
{
*humi=buf[0];
*temp=buf[2];
}
}else return 1;
return 0;
}
uint8_t DHT11_GPIO_Config ( void )
{
GPIO_InitTypeDef GPIO_InitStruct;
__RCC_GPIOB_CLK_ENABLE();
GPIO_InitStruct.IT = GPIO_IT_NONE;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pins = GPIO_PIN_1;
GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
GPIO_Init(CW_GPIOB, &GPIO_InitStruct);
DHT11_Rst();
return DHT11_Check();
}
dht11.h
#ifndef __DHT11_H
#define __DHT11_H
#include "main.h"
uint8_t DHT11_Init(void);
uint8_t DHT11_Read_Data(float *temp,uint8_t *humi);
uint8_t DHT11_Read_Byte(void);
uint8_t DHT11_Read_Bit(void);
uint8_t DHT11_Check(void);
void DHT11_Rst(void);
uint8_t DHT11_GPIO_Config ( void );
#endif
接好线后,把程序下载到开发板,然后重启效果如下:
|