本帖最后由 jinglixixi 于 2020-8-30 00:58 编辑
DHT22是一款数字式温湿度传感器,它采用单总线方式工作。为此,在使用时需占用一个I/O口,来进行信息的收发处理,这里选用PF2来完成。 为进行温湿度的检测与显示,对引脚的配置如图1所示。 图1引脚配置
DHT22的初始化函数为:
unsigned char DHT22_Init(void)
{
DHT22_Rst();
return DHT22_Check();
}
读取DHT22温湿度的函数为: unsigned char DHT22_Read_Data(unsigned int *temp,unsigned int *humi)
{
unsigned char buf[5];
unsigned char i;
DHT22_Rst();
if(DHT22_Check()==0)
{
for(i=0;i<5;i++) {
buf[i]=DHT22_Read_Byte();
}
if((buf[0]+buf[1]+buf[2]+buf[3])==buf[4])
{
*humi=(buf[0]*256+buf[1]);
*temp=(buf[2]*256+buf[3]);
}
}else return 1;
return 0;
}
相应的数值显示函数为: void OLED_ShowNum(uint8_t x,uint8_t y,uint32_t num,uint8_t len)
{
uint8_t t,temp;
uint8_t enshow=0;
uint8_t size2=16;
for(t=0;t<len;t++)
{
temp=(num/oled_pow(10,len-t-1))%10;
if(enshow==0&&t<(len-1))
{
if(temp==0)
{
OLED_ShowChar(x+(size2/2)*t,y,' ');
continue;
}else enshow=1;
}
OLED_ShowChar(x+(size2/2)*t,y,temp+'0');
}
}
实现温湿度显示的主程序为: int main(void)
{
unsigned char senflag;
/* Initializes MCU, drivers and middleware */
SYSTEM_Initialize();
OLED_Init();
OLED_CLS();
OLED_P8x16Str(0,0,"ATmega4809");
OLED_P8x16Str(0,2,"OLED Display");
OLED_P8x16Str(0,4,"T= . C H= . %");
DELAY_milliseconds(100);
senflag=DH22_Init();
/* Replace with your application code */
while (1){
if(senflag)
{
OLED_P8x16Str(64,0," SEN OK!");
DHT22_Read_Data(&temperature,&humidity);
OLED_ShowNum(16,4,temperature/10,2);
OLED_ShowNum(40,4,temperature%10,1);
OLED_ShowNum(80,4,humidity/10,2);
OLED_ShowNum(104,4,humidity%10,1);
}
else
{
OLED_P8x16Str(64,0," NO SEN!");
}
//PORTF_toggle_pin_level(5);
LED_Toggle();
DELAY_milliseconds(1000);
}
}
经编译下载,其运行效果如图2所示。 图2 温湿度显示
运行文件:
|