#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit DQ=P2^0;
uint h,temp;
bit flag;
uchar code dian_table[16]={0x00,0x01,0x01,0x02,0x03,0x03,0x04,0x04,
0x05,0x06,0x06,0x07,0x08,0x08,0x09,0x09}; //温度小数部分用查表法
uchar data temp_data[2]={0x00,0x00}; //读出温度暂放
uchar data display[5]={0x00,0x00,0x00,0x00,0x00};
//显示单元数据,共4个数据和一个运算暂用
uchar idata temp_display[]={0x30,0x31,0x32,0x33,0x34,
0x35,0x36,0x37,0x38,0x39};
void init() //串口初始化
{
SCON= 0x50; //串口方式1 允许接收
PCON=0; //SMOD=0
TMOD= 0x20; //定时器1定时方式2
TH1= 0xf3; //12MHz 2400波特率
TL1= 0xf3;
TR1= 1;
EA = 1;
ES = 1;
}
//---------------------------------------------------------------
//串口发送函数
//---------------------------------------------------------------
/*void serial_send(unsigned char ch) //串口发送函数
{
TI=0;
SBUF=ch;
while(TI== 0); //等待发送完成
}*/
void delay(uint t) //11us延时函数
{
for (;t>0;t--);
}
void ow_reset(void) //DS18B20复位函数
{
char presence=1;
while(presence)
{
while(presence)
{
DQ=1;_nop_();_nop_();//从高拉倒低
DQ=0;
delay(50); //550 us
DQ=1;
delay(6); //66 us
presence=DQ; //presence=0 复位成功,继续下一步
}
delay(45); //延时500 us
presence=~DQ;
}
DQ=1; //拉高电平
}
void write_byte(uchar val) //DS18B20写命令函数
{
uchar i;
for(i=8;i>0;i--)
{
DQ=1;_nop_();_nop_(); //从高拉倒低
DQ=0;_nop_();_nop_();_nop_();_nop_(); //5 us
DQ=val&0x01; //最低位移出
delay(6); //66 us
val=val/2; //右移1位
}
DQ=1;
delay(1);
}
uchar read_byte(void) //DS18B20读1字节函数
{
uchar i;
uchar value=0;
for(i=8;i>0;i--)
{
DQ=1;_nop_();_nop_();
value>>=1;
DQ=0;_nop_();_nop_();_nop_();_nop_(); //4 us
DQ=1;_nop_();_nop_();_nop_();_nop_(); //4 us
if(DQ)value|=0x80;
delay(6); //66 us
}
DQ=1;
return(value);
}
read_temp() //读出温度函数
{
ow_reset(); //总线复位
delay(200);
write_byte(0xcc); //发命令
write_byte(0x44); //发转换命令
ow_reset();
delay(1);
write_byte(0xcc); //发命令
write_byte(0xbe);
temp_data[0]=read_byte(); //读温度值的低字节
temp_data[1]=read_byte(); //读温度值的高字节
temp=temp_data[1];
temp<<=8;
temp=temp|temp_data[0]; // 两字节合成一个整型变量。
return temp; //返回温度值
}
void work_temp(uint tem) //温度数据处理函数
{
uchar n=0;
if(tem>6348) // 温度值正负判断
{
tem=65536-tem;
n=1;
} // 负温度求补码,标志位置1
display[4]=tem&0x0f; // 取小数部分的值
display[0]=dian_table[display[4]]; // 存入小数部分显示值
temp_display[0]=display[0]+0x30;
display[4]=tem>>4; // 取中间八位,即整数部分的值
display[3]=display[4]/100; // 取百位数据暂存
temp_display[4]=display[3]+0x30;
display[1]=display[4]%100; // 取后两位数据暂存
display[2]=display[1]/10; // 取十位数据暂存
temp_display[3]=display[2]+0x30;
display[1]=display[1]%10;
temp_display[2]=display[1]+0x30;
temp_display[1]='.';
if(!display[3])
{
temp_display[4]=' '; //最高位为0时不显示
if(!display[2])
{
temp_display[3]=' '; //次高位为0时不显示 4-百位 3-十位 2-个位 1-小数点 0-小数部分
}
}
if(n)
{
temp_display[4]='-';
} //负温度时最高位显示"-"
}
void main() //主函数
{
uint i;
init();
ow_reset(); //开机先转换一次
write_byte(0xcc); //Skip ROM
write_byte(0x44); //发转换命令
while(1)
{
work_temp(read_temp()); //处理温度数据
if(flag==1)
{
for(i=0;i<5;i++)
{
SBUF=temp_display[4-i];
while(!TI);
TI=0;
}
flag=0;
}
}
}
void serial() interrupt 4 //串口中断
{
if(RI)
{
RI = 0;
flag=1;
}
}