#include<reg51.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit DQ = P3^7; //温度传送数据IO口
sbit add_s=P3^2;
sbit sub_s=P3^3;
sbit add_g=P3^4;
sbit sub_g=P3^5;
sbit power=P3^6;
uchar code table[]={ //编码表
0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f,0x77,0x7c,
0x39,0x5e,0x79,0x71,};
uchar TempBuffer[5];
uchar temp_value,shi,ge,shi1,ge1; //温度值
char temp_value_set=99;
void delay(uint z) //10ms
{
uint x,y;
for(x=100;x>0;x--)
for(y=z;y>0;y--);
}
/***********ds18b20延迟子函数(晶振12MHz )*******/
void delay_18B20(unsigned int i)
{
while(i--);
}
/**********ds18b20初始化函数**********************/
void Init_DS18B20(void)
{
unsigned char x=0;
DQ = 1; //DQ复位
delay_18B20(8); //稍做延时
DQ = 0; //单片机将DQ拉低
delay_18B20(80); //精确延时 大于 480us
DQ = 1; //拉高总线
delay_18B20(14);
x=DQ; //稍做延时后 如果x=0则初始化成功 x=1则初始化失败
delay_18B20(20);
}
/***********ds18b20读一个字节**************/
unsigned char ReadOneChar(void)
{
uchar i=0;
uchar dat = 0;
for (i=8;i>0;i--)
{
DQ = 0; // 给脉冲信号
dat>>=1;
DQ = 1; // 给脉冲信号
if(DQ)
dat|=0x80;
delay_18B20(4);
}
return(dat);
}
/*************ds18b20写一个字节****************/
void WriteOneChar(uchar dat)
{
unsigned char i=0;
for (i=8; i>0; i--)
{
DQ = 0;
DQ = dat&0x01;
delay_18B20(5);
DQ = 1;
dat>>=1;
}
}
/**************读取ds18b20当前温度************/
void ReadTemp(void)
{
unsigned char a=0;
unsigned char b=0;
unsigned char t=0;
Init_DS18B20();
WriteOneChar(0xCC); // 跳过读序号列号的操作
WriteOneChar(0x44); // 启动温度转换
delay_18B20(100); // this message is wery important
Init_DS18B20();
WriteOneChar(0xCC); //跳过读序号列号的操作
WriteOneChar(0xBE); //读取温度寄存器等(共可读9个寄存器) 前两个就是温度
delay_18B20(100);
a=ReadOneChar(); //读取温度值低位
b=ReadOneChar(); //读取温度值高位
temp_value=b<<4;
temp_value+=(a&0xf0)>>4;
}
void Display(uchar temp,uchar temp1)
{
shi=temp/10;
shi1=temp1/10;
ge=temp%10;
ge1=temp1%10;
P2=0xfe;
P1=table[shi];
P0=table[shi1];
delay(10);
P2=0xfd;
P1=table[ge]+0x80;
P0=table[ge1]+0x80;
delay(10);
P2=0xfb;
P1=0x3f;
P0=0x3f;
delay(10);
}
void Button() //设置温度
{
if(add_s==0)
{
delay(5);
if(add_s==0)
{
while(add_s==0);
temp_value_set+=10;
if(temp_value_set>99)
{
temp_value_set=0;
}
}
}
if(sub_s==0)
{
delay(5);
if(sub_s==0)
{
while(sub_s==0);
temp_value_set-=10;
if(temp_value_set<0)
{
temp_value_set=0;
}
}
}
if(add_g==0)
{
delay(5);
if(add_g==0)
{
while(add_g==0);
temp_value_set++;
if(temp_value_set>99)
{
temp_value_set=0;
}
}
}
if(sub_g==0)
{
delay(5);
if(sub_g==0)
{
while(sub_g==0);
temp_value_set--;
if(temp_value_set<0)
{
temp_value_set=0;
}
}
}
}
void main()
{
Init_DS18B20( );
while(1)
{
ReadTemp();
Display(temp_value,temp_value_set);
Button();
if(temp_value_set>temp_value) //实际温度低于设置温度时,打开电源
{
power=0;
}
if(temp_value_set<=temp_value) //实际温度大于等于设置温度时,关掉电源
{
power=1;
}
}
}