#include
#include
#define uchar unsigned char
#define uint unsigned int
float tt; //tt为采集的温度值
code uchar TAB[]={0xc0,0xf9,0xa4,0xb0,0x99,
0x92,0x82,0xf8,0x80,0x90}; //数码管段码
uchar str_TME[4]={0,0,0,0};
unsigned char MAX=29;
unsigned char MIN=10;
sbit DQ =P2^4; //定义通信端口
sbit fm =P2^7;
//短延时函数
void delay(unsigned int i)
{
while(i--);
}
//1ms延时函数
void delay1(uchar ms)
{
uchar i;
while(ms--)
for(i=0;i<125;i++);
}
//DS18B20初始化函数
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=1则初始化失败
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;
}
delay(4);
}
//读取温度
ReadTemperature(void)
{
unsigned char a=0;
unsigned char b=0;
unsigned int t=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;
return(tt);
}
uchar tmel=0;
//uchar ad_dat;
bit sim=1;
/********************定时器中断函数********************/
void tme_tr0(void) interrupt 1
{
TL0=0xb0;
TH0=0x3c;
if(++tmel==20)
{
tmel=0;
sim=1;
}
}
/*****************定义数码管显示***************************/
sbit k1=P1^0;
sbit k2=P1^1;
sbit k3=P1^2;
sbit k4=P1^3;
void VAL_xs()
{ k1=0;k2=0; k3=0;k4=0;
P0=TAB[str_TME[0]]; //?????
k1=1;
delay1(5);
k1=0;
P0=(TAB[str_TME[1]])&0x7f;
k2=1;
delay1(5);
k2=0;
P0=TAB[str_TME[2]];
k3=1;
delay1(5);
k3=0;
P0=0xc6;
k4=1;
delay1(5);
k4=0;
}
void changs() //数据转换
{
uchar tint,tfloat;
ReadTemperature();//读温度
tint=(int)(tt);
tfloat=(tt-tint)*100;
str_TME[0]=tint/10;
str_TME[1]=tint%10;
str_TME[2]=tfloat/10;
}
write_tempere_alarm()
{
if(((int)tt>MAX)||((int)tt {fm=0;} else {fm=1;} } main() { P1=0xc0; IE=0x82; TMOD=0x01; IP=0x01; TL0=0xb0; TH0=0x3c; TR0=1; while(1) { VAL_xs(); write_tempere_alarm(); if(sim==1) {changs(); sim=0; } } }