#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
unsigned char leddata[]={
0xC0, //"0"
0xF9, //"1"
0xA4, //"2"
0xB0, //"3"
0x99, //"4"
0x92, //"5"
0x82, //"6"
0xF8, //"7"
0x80, //"8"
0x90, //"9"
};
sbit DQ = P2^4;
sbit wei0 = P2^0;
sbit wei1 = P2^1;
sbit wei2 = P2^2;
char m;
uchar n;
void delay(uint z) //延时1ms子程序
{
uint x, y;
for(x=z; x>0; x--)
for(y=114; y>0; y--);
}
void delay_us(uchar s) //延时1us子程序
{
--s;
}
void init_ds18b20() //初始化ds18b20温度传感器
{
uchar x = 0;
DQ = 1; //dq引脚复位
delay_us(8); //稍做延时
DQ = 0; //将引脚拉低
delay_us(80); //精确延时,大于480us
DQ = 1; //拉高引脚
delay_us(14); //精确延时,16~60us
x = DQ; //将引脚值保存在x中
delay_us(20); //精确延时,60~240us
}
uchar readonechar() //读取一个字节子程序
{
uchar i = 0;
uchar dat = 0;
for(i=8; i>0; i--)
{
DQ = 0; //拉低信号读字节
dat >>= 1; //dat右移一位再赋值直到赋值到第八位
DQ = 1; //读完拉高信号
if(DQ)
dat |= 0x80; //dat中数与0x80按位相或
delay_us(4); //稍做延时
}
return(dat); //将结果返回dat中
}
void writeonechar(uchar dat)
{
uchar i = 0;
for(i=0; i<8; i++)
{
DQ = 0; //拉低信号写字节
DQ = dat & 0x01; //dat中数与0x01按位相与
delay_us(5); //稍做延时
DQ = 1; //写完拉高信号
dat >>= 1; //dat右移一位再赋值直到赋值到第八位
}
}
uint readtemp() //读取温度子程序
{
uchar a=0, b=0;
uint t = 0;
float tt = 0;
init_ds18b20(); //初始化传感器
writeonechar(0xcc); //跳过读序列号的操作
writeonechar(0x44); //启动温度转换
init_ds18b20(); //初始化传感器
writeonechar(0xcc); //跳过读序列号的操作
writeonechar(0xbe); //读取温度寄存器
a = readonechar(); //读低八位
b = readonechar(); //读高八位
t = b; //将高八位的数据转移到t
t <<= 8; //t中数据左移8位
t = t|a; //将t中数据按位和a中数据相或
tt = t*0.0652-1; //将温度乘0.0652得到实际值
t = tt*10+0.5; //将实际温度乘10倍
return(t); //将数值返回到变量t中
}
void checktemp()
{
uint a,b,c;
c=readtemp(); //获取温度值
a=c/100; //计算得到十位数字
b=c/10-a*10; //计算得到个位数字
m=c/10; //计算得到整数位
n=c-a*100-b*10;
}
void displaytemp()
{
wei0 = 1;
P0 = leddata[n];
delay(100);
wei0 = 0;
wei1 = 1;
P0 = leddata[m%10];
delay(100);
wei1 = 0;
wei2 = 1;
P0 = leddata[m/10];
delay(100);
wei2 = 0;
}
void main()
{
checktemp();
displaytemp();
}
|