pic16f877a驱动温湿度传感器DHT11
时间:10-02
整理:3721RD
点击:
#include<pic.h> //用12M晶振
#include"12864.h"
#define uint unsigned int
#define uchar unsigned char
__CONFIG(FOSC_HS&WDTE_OFF&LVP_OFF);
uchar temp_valueH,hum_valueH,hum_valueL,temp_valueL,check;
uint delay_time;
void timer0_init()
{
TMR0=0; //初值
T0CS=0; //选择时钟源,为晶振的1/4;
T0SE=1; //时钟源边沿选择位
PSA=0; //预分频器分配位
PS0=0;PS1=0;PS2=0; //预分频选择位
TMR0IF=0; //定时器标志位清0
GIE=1; //开全局中断
TMR0IE=0; //定时器0使能
TMR0=236; //赋初值
}
void interrupt timer0()
{
if(TMR0IF)
{
TMR0IF=0;TMR0=235;
delay_time--;
}
}
void timer0_delay(uint delay_value)
{
delay_time=delay_value;
TMR0IE=1;
while(delay_time);
TMR0IE=0;
}
uchar Read_byte()
{
uchar i,temp,hum;
for(i=0;i<8;i++)
{
while(!RC1);
timer0_delay(2); //延时20us
temp=0;
if(RC1){temp=1;while(RC1);}
else{temp=0;}
hum<<=1;
hum|=temp;
}
return(hum);
}
void Read_data()
{
uchar ckeck_value;
RC1=0;
timer0_delay(2500);//总线拉低至少18MS
RC1=1;
timer0_delay(2); //总线由上拉电阻拉高 主机延时20us
TRISC1=1; //主机设为输入 判断从机响应信号
RC1=1;
if(!RC1)
{
while((!RC1)) //判断从机是否发出 80us 的低电平响应信号是否结束
{
NOP();
}
while(RC1) //判断从机是否发出 80us 的高电平,如发出则进入数据接收状态
{
NOP();
}
temp_valueH=Read_byte();
temp_valueL=Read_byte();
hum_valueH=Read_byte();
hum_valueL=Read_byte();
check=Read_byte();
ckeck_value=hum_valueL+hum_valueH+temp_valueL+temp_valueH;
if(check==ckeck_value)
{
Proce_num(0x84,temp_valueH);
Proce_num(0x94,hum_valueH);
}
}
TRISC1=0;
RC1=1;
}
void main()
{
TRISB=0X00;
lcdinit();
timer0_init();
while(1)
{
Read_data();
}
}
好东东,谢谢小编!