#include<reg51.h>
#include<intrins.h>
#define UARTBUFMAXSIZE 30
#define JUDGE 30
unsigned char tempL=0;
unsigned char tempH=0;
sbit DQ=P3^7;
xdata unsigned char Uart1SendBufs[UARTBUFMAXSIZE]={0};//扩展缓冲区 RAM空间
unsigned char dat_r[5];
unsigned char outdata[5]={"RS232"};
//串行口初始化函数
void UartInit(void) //9600bps@11.0592MHz
{
PCON &= 0x7F; //波特率不倍速
SCON = 0x50; //8位数据,可变波特率
// AUXR &= 0xBF; //定时器时钟12T模式
// AUXR &= 0xFE; //串口1选择定时器1为波特率发生器
TMOD &= 0x0F; //设置定时器模式
TMOD |= 0x20; //设置定时器模式
TL1 = 0xFD; //设置定时初始值
TH1 = 0xFD; //设置定时重载值
ET1 = 0; //禁止定时器%d中断
TR1 = 1; //定时器1开始计时
}
//数据发送函数
unsigned char DataSendPreprocess()
{
unsigned char i=0,j,t=0;
Uart1SendBufs[i]=0x7f;i++; //起始字节
Uart1SendBufs[i]=UpID;i++; //接受者地址
Uart1SendBufs[i]=MyID;i++; //发送者地址
Uart1SendBufs[i]=5; i++; //数据长度
Uart1SendBufs[i]=0x83;i++; //传感器类型0x82--->DS18B20
Uart1SendBufs[i]=dat_r[0] ;i++;
Uart1SendBufs[i]=dat_r[1] ;i++;
Uart1SendBufs[i]=dat_r[2] ;i++;
Uart1SendBufs[i]=dat_r[3] ;i++;
for(j=1;j<i;j++) //异或校验码生成
t^=Uart1SendBufs[j];
Uart1SendBufs[i]=t; i++; //校验字节
Uart1SendBufs[i]=0xff;i++; //结束字节
return i;
}
void Uart1Send(unsigned char ss[],unsigned char len)
{
unsigned char i;
for(i=0;i<len;i++)
{
SBUF=ss[i];
while(TI==0);
TI=0;
}
}
void Delay10us(unsigned int x) //@11.0592MHz
{
unsigned char i;
while(x--)
{
_nop_();
_nop_();
_nop_();
i = 24;
while (--i);
}
}
void Delay1ms(unsigned int x) //@11.0592MHz
{
unsigned char i, j;
while(x--)
{
_nop_();
i = 11;
j = 190;
do
{
while (--j);
}
while (--i);
}
}
unsigned char GetDHT11Data(void)
{
unsigned char i,j;
unsigned char t;
unsigned char dat8=0;
unsigned char tmp=0;
DQ=0;
Delay1ms(20);
DQ=1;
Delay10us(3);
t=80;
while(DQ && t--);
if(t == 0)
{
DQ=1;
return 1;
}
t=250;
while(!DQ && t--);
if(t==0)
{
DQ=1;
return 2;
}
t=250;
while(DQ && t--);
if(t==0)
{
DQ = 1;
return 3;
}
for(j=0;j<5;j++)
{
for(i=0;i<8;i++)
{
t=150;
while(!DQ && t--);
if(t==0)
{
DQ=1;
return -4;
}
t=0;
while(DQ && ++t);
dat8 <<= 1;
if(t>JUDGE)
dat8 += 1;
}
dat_r[j] =dat8;
}
Delay10us(50);
DQ = 1;
for(i=0;i<4;i++)
tmp+=dat_r[i];
if(tmp!=dat_r[4])
return 5;
return 0;
}
//主函数
void main()
{
unsigned char t;
UartInit();
Uart1Send(outdata,5);
Delay1ms(2000);
while(1)
{
t=DataSendPreprocess();
if(GetDHT11Data()==0)
{
Uart1Send(Uart1SendBufs,t);
Delay1ms(2000);
}
}
}