📄 18b20liangshuqu.c
字号:
#include<reg51.h>
#include<absacc.h>
unsigned int code tab[]={0x88,0xEB,0x4C,0x49,0x2B,0x19,0x18,0x8B,0x08,0x09,0xFF,0x7F};
sbit DQ1=P1^0; // 数据传输线对应引脚
sbit DQ2=P1^1;
int n;
unsigned char dat[2]; //设全局变量
unsigned char tempL=0;
unsigned char tempH=0;
void delay(unsigned int time) //延时子程序
{
unsigned int r;
r=0;
while(r<time)
{ r++;}
return;
}
void display1(int k) //正温显示子程序
{
int x1,x2,x3,i;
x1=k%10; //个位数
x2=k%100/10; //十位数
x3=k/100; //百位数
SCON=0x00;
SBUF=tab[x1];
while(TI==0);
TI=0;
SBUF=tab[x2];
while(TI==0);
TI=0;
SBUF=tab[x3];
while(TI==0);
TI=0;
for(i=0;i<3;i++)
{
SBUF=tab[10];
while(TI==0);
TI=0;
}
}
void display2(int k ) //显示子程序
{
int x1,x2,i;
x1=k%10; //个位数
x2=k/10;
SCON=0x00;
SBUF=tab[x1];
while(TI==0);
TI=0;
SBUF=tab[x2];
while(TI==0);
TI=0;
SBUF=tab[11];
while(TI==0);
TI=0;
for(i=0;i<3;i++)
{
SBUF=tab[10];
while(TI==0);
TI=0;
}
}
Init_DS18B20(void) //初始化子程序
{
unsigned char x=0;
DQ1=1; //置高
DQ2=1;
delay(8); //延时
DQ1=0; //发复位脉冲
DQ2=0;
delay(85);
DQ1=1; //拉高数据线
DQ2=1;
delay(14);
delay(20);
}
ReadOneChar(n) //读一字节数据
{
unsigned char dat1=0;
unsigned char dat2=0;
unsigned char a;
unsigned char i=0;
for(i=8;i>0;i--)
{
DQ1=1;
DQ2=1;
delay(1);
if(n<1)
{
DQ1=0;
dat1>>=1;
DQ1=1;
if(DQ1)
{
dat1|=0x80;
}
dat[0]=dat1;
}
else
{
DQ2=0;
dat2>>=1;
DQ2=1;
if(DQ2)
{
dat2|=0x80;
}
dat[1]=dat2 ;
}
a=dat[n] ;
delay(4);
}
return(a);
}
WriteOneChar(unsigned char dat,n) //向DS18S20写一字节数据
{
unsigned char dat1;
unsigned char dat2;
unsigned char i=0;
dat1=dat;
dat2=dat;
for(i=8;i>0;i--)
{
if(n<1)
{
DQ1=0;
DQ1=dat1&0x01;
delay(5);
DQ1=1;
dat1>>=1;
}
else
{
DQ2=0;
DQ2=dat2&0x01;
delay(5);
DQ2=1;
dat2>>=1;
}
}
delay(4);
}
void main() //主程序
{
float i;
unsigned char j,tempH,tempL;
do
{
for(n=0;n<2;n++)
{
Init_DS18B20(); //初始化
WriteOneChar(0xcc,n); //跳过读序列号
WriteOneChar(0x44,n); //启动温度转换
delay(125);
Init_DS18B20();
WriteOneChar(0xcc,n);
WriteOneChar(0xbe,n); //读温度寄存器
tempL=ReadOneChar(n); //读出温度低位
tempH=ReadOneChar(n); //读出温度高位
j=tempH&0x80; //取符号位
delay(200);
if(j<1)
{ i=((tempH*256)+tempL)*0.0625; //温度转换
display1(i);
}
else
{
i=(~((tempH*256)+tempL )+1)*0.0625;
display2(i);
}
delay(180000) ;
}
}
while(1) ;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -