温度采集:
c:
DS18B20.zip
#include
#include
#define uchar unsigned char
#define uint unsigned
sbit rs=P2^4;
sbit rw=P2^5;
sbit e=P2^6;
sbit dq=P2^3;
uchar zm1[]=" temperature: ";
uchar zm2[]=" 00.0 c ";
uchar zm3[]=" NO DS18B20 ";
uchar i,lsb,msb,result,flag,sign,point,x; //p小数 s正负号,flag器件存在标志,i循环变量
void delay(int t)
{ while(t--);}
void DS18_delay(int useconds)//延时函数
{
int s;
for (s=0; s
}
void write_com(unsigned char com)
{ e=0;
rs=0;
rw=0;
P0=com;
delay(50);
e=1;
delay(50);
e=0;
delay(50); }
void write_data(unsigned char dat)
{ e=0;
rs=1;
rw=0;
P0=dat;
delay(50);
e=1;
delay(50);
e=0;
delay(50); }
void start()
{ delay(200);
write_com(0x38);
delay(200);
write_com(0x38);
delay(200);
write_com(0x38);
write_com(0x38);
write_com(0x08);
write_com(0x01);
write_com(0x06);
write_com(0x0c); }
void lcd(char *p)
{ int j;
write_com(0x80);
for(j=0;j<18;j++)
{ write_data(zm1[j]); }
write_com(0x80+0x40);
for(j=0;j<18;j++)
{ write_data(p[j]); } }
uint reset()
{ dq=0; //复位程序
DS18_delay(29);
dq=1;
DS18_delay(3);
flag=dq;
DS18_delay(25);
return(flag);
}
uchar read() //读操作低位在前
{ uchar dat=0;
for(i=0;i<8;i++)
{ dq=1;
DS18_delay(1);
dq=0;
dat>>=1;
dq=1;
if(dq)
dat|=0x80;
DS18_delay(4);
}
return(dat);
}
void write(uchar dat) //写低位在前
{ for(i=0;i<8;i++)
{ dq=0;
dq=dat&0x01; // 充当1us_nop_();
DS18_delay(5);
dq=1;
dat>>=1;
}
DS18_delay(4);
}
void disp(uchar lsb,uchar msb)
{ sign=(msb>>3)&0x01; //取符号
lsb>>=4;
msb<<=4;
result=lsb|msb;
point=(int)((float)(((~(lsb-=1))&0x0f)*0.625));
if(sign==1)
{ result-=1;
result=~result;
result=result&0x7f; }
if(result>=0x64)
{zm2[5]=result/100+0x30;} else zm2[5]=' ';
if(result>=0x0a)
{zm2[6]=(result/10)%10+0x30;} else zm2[6]=' ';
zm2[7]=result%10+0x30;
zm2[9]=point%10+0x30;
if(sign) zm2[4]='-'; else zm2[4]=' ';
lcd(zm2);
}
void main()
{ start();
lcd(zm2);
while(1)
{ flag=reset();
if(!flag)
{ write(0xcc);
write(0x44);
DS18_delay(125);
reset();
write(0xcc);
write(0xbe);
disp(lsb=read(),msb=read());
/* DS18_delay(29); //525.18
DS18_delay(3); //72.70
DS18_delay(25); //454.64
DS18_delay(1); //37.98
DS18_delay(4); //90.06
DS18_delay(5); //116.8 */
}
else lcd(zm3);
}
}
阅读(923) | 评论(0) | 转发(1) |