unsigned char code segtab[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,
0x6f,0x63,0x39};
unsigned char disp_buf[]={0,0,0,0};
unsigned char code ledbit[]={0xfe,0xfd,0xfb,0xf7};
unsigned char ledno=0,ms5;
unsigned char temperature=25;//温度值
sbit DQ =P3^3; //定义通信端口
void delay(unsigned int i)
{
while(i--);
}
//初始化函数
Init_DS18B20(void)
{
unsigned char x=0;
DQ = 1; //DQ复位
delay(8); //稍做延时
DQ = 0; //单片机将DQ拉低
delay(80); //精确延时 大于 480us
DQ = 1; //拉高总线
delay(14);
x=DQ; //稍做延时后 如果x=0则初始化成功 x=1则初始化失败
delay(20);
}
//读一个字节
ReadOneChar(void)
{
unsigned char i=0;
unsigned char dat = 0;
for (i=8;i> 0;i--)
{
DQ = 0; // 给脉冲信号
dat> > =1;
DQ = 1; // 给脉冲信号
if(DQ)
dat|=0x80;
delay(4);
}
return(dat);
}
//写一个字节
WriteOneChar(unsigned char dat)
{
unsigned char i=0;
for (i=8; i> 0; i--)
{
DQ = 0;
DQ = dat&0x01;
delay(5);
DQ = 1;
dat> > =1;
}
}
//读取温度
ReadTemperature(void)
{
unsigned char a=0;
unsigned char b=0;
unsigned int t=0;
float tt=0;
Init_DS18B20();
WriteOneChar(0xCC); // 跳过读序号列号的操作
WriteOneChar(0x44); // 启动温度转换
Init_DS18B20();
WriteOneChar(0xCC); //跳过读序号列号的操作
WriteOneChar(0xBE); //读取温度寄存器等(共可读9个寄存器) 前两个就是温度
a=ReadOneChar();
b=ReadOneChar();
t=b;
t < <=8;
t=t|a;
tt=t*0.0625;
t= tt*10+0.5; //放大10倍输出并四舍五入---此行没用
return(tt);
}
main()
{
TMOD=0x11;
EA=1;
ET0=1;
ET1=1;
TR0=1;
TR1=0;
TH0=0xee;
TL0=0x00;
//TH1=0xee;
// TL1=0x00;
while(1)
{
temperature=ReadTemperature();//读温度
delay(20000);
}
}
void timer0(void) interrupt 1
{
TR0=0;
TH0=0xee;
TL0=0x00;
P1=0xff;
disp_buf[0]=temperature/10;
disp_buf[1]=temperature%10;
disp_buf[2]=10;
disp_buf[3]=11;
P1=ledbit[ledno];
P0=segtab[disp_buf[ledno]];
ledno++;
if(ledno> 3) ledno=0;
TR0=1;
}
选配实验板 请详见重庆市优易特电子网站上 Easy51-B学习板
重庆市优易特电子
联系人:行卫军
电话:023-62111023
网址: