#include"reg51.h"
sbit DQ =P3^7; //定义本文引用的通信端口地址:http://www.eepw.com.cn/article/201611/315676.htm
///延迟函数
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=一是初始化失败
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; ///4舍5入结果
return(t);
}
//分别从0-9编码,注意这个编码只适合QQ请参考上述算法计算单片机实验板和其他电路板上的编码。
unsigned char code Num[10]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F};
//QQ在其他电路板上,单片机的私有函数可能
///在8个数字管上显示任何字符,由8个参数组成LED1--LED8决定 如果显示的字符是空的,则不扫描数字管以缩短扫描时间
ShowAny(unsigned char LED1,unsigned char LED2,unsigned char LED3,unsigned char LED4,unsigned char LED5,unsigned char LED6,unsigned char LED7,unsigned char LED8)
{
if(LED1) { P2=0xEF; P0=LED1; delay(100); }
if(LED2) { P2=0xDF; P0=LED2; delay(100); }
if(LED3) { P2=0xBF; P0=LED3; delay(100); }
if(LED4) { P2=0x7F; P0=LED4; delay(100); }
if(LED5) { P2=0xFE; P0=LED5; delay(100); }
if(LED6) { P2=0xFD; P0=LED6; delay(500); }
if(LED7) { P2=0xFB; P0=LED7; delay(500); }
if(LED8) { P2=0xF7; P0=LED8; delay(100); }
}
main()
{
unsigned int i=0;
while(1)
{
i=ReadTemperature(); //读取当前温度
ShowAny(0,0,0,0,0,0,0Num[i/100],Num[i/10] | 0x80,Num[i]); //显示当前温度
}
}