📄 -
字号:
#include "reg52.h"
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char
sbit DQ = P3^7; //从器件数据端
void delay(uchar x)
{
while(x--);
}
const uchar table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
const uchar table1[]={0xbf,0x86,0xdb,0xcf,0xe6,0xed,0xfd,
0x87,0xff,0xef};
/*
delay(1) 延时 7us
delay(7) 延时63us
delay(100) 延时 611us
*/
//单总线复位,启动,停止等
void IC_init()
{
DQ = 0;
delay(100); //主机拉低总线480us以上
DQ = 1; //释放总线
delay(100); //等待从器件拉低总线回复,延时大于480us
}
//读字节
uchar IC_read( )
{
bit flag = 0;
uchar i = 0, temp = 0;
for(i = 0; i < 8; i++)
{
temp = temp >> 1;//注意此处移位
DQ = 0;
_nop_(); //拉低总线至少1us启动读
DQ = 1; //释放总线
delay(1); //延时,使从器件写数据
flag = DQ; //主机须在15us内读走数据
if(flag == 1)
temp = temp | 0x80;
delay(7); //建立一个读周期至少需60us的条件
DQ = 1; //释放总线,进入下一个写周期
_nop_(); //两次读至少间隔1us
_nop_();
}
return temp;
}
//写字节
void IC_write(uchar date)
{
uchar temp = 0, i = 0;
temp = date;
for(i = 0; i < 8; i++)
{
DQ = 0;
_nop_(); //拉低总线,启动写
DQ = temp & 0x01; //在15us内需将数据写到总线
delay(7); //建立大于45us的延时,完成一个写周期
DQ = 1; //释放总线,进入下一个写周期
_nop_();
_nop_();
temp = temp >> 1;
}
}
void DS18B20_T(uchar *a1,uchar *a2,uchar *a3,uchar *a4,uchar *a5,uchar *a6,uint *t,uchar *fushu)
{
uchar tmp1 = 0, tmp0 = 0;
IC_init(); //启动
IC_write(0xcc); //跳过ROM
IC_write(0x44); //启动温度转换
IC_init(); //重新启动
IC_write(0xcc);
IC_write(0xbe); //读取温度
tmp0= IC_read(); //读低字节
tmp1 = IC_read(); //读高字节
if(tmp1>0xf8)
{
tmp1=~tmp1;
tmp0=~tmp0+1;
*fushu=1;
}
else
*fushu=0;
*t =(tmp1 * 256)|tmp0;
*t=(*t)*0.0625;
*t= (*t)*100;
*a1=*t/100000;
*a2=(*t%100000)/10000;
*a3=(*t%10000)/1000;
*a4=(*t%1000)/100;
*a5=(*t%100)/10;
*a6=*t%10;
}
void xianshi(uchar *a,uchar *b,uchar *c,uchar *d,uchar *e,uchar *f,uchar *fushu)
{
if(*fushu)
{
P2=0X7f;
P0=0x40;
delay(100);
}
else
{
P2=0X7f;
P0=table[*a];
delay(100);
}
P2=0Xbf;
P0=table[*b];
delay(100);
P2=0Xdf;
P0=table[*c];
delay(1000);
P2=0Xe7;
P0=table1[*d];
delay(1000);
P2=0Xf7;
P0=table[*e];
delay(100);
P2=0Xfb;
P0=table[*f];
delay(100);
}
void main()
{
uchar a1,a2,a3,a4,a5,a6;
uint t = 0; uchar fushu;
while(1)
{
DS18B20_T(&a1,&a2,&a3,&a4,&a5,&a6,&t,&fushu);
xianshi(&a1,&a2,&a3,&a4,&a5,&a6,&fushu);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -