1、#include sbit DQ = P33; /定义 DS18B20 端口 DQ sbit BEEP=P37 ;unsigned char presence ;unsigned char code LEDData = 0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90,0xff;unsigned char data temp_data2 = 0x00,0x00;unsigned char data display5 = 0x00,0x00,0x00,0x00,0x00;unsigned char code ditab16 = 0x00,0x01
2、,0x01,0x02,0x03,0x03,0x04,0x04,0x05,0x06,0x06,0x07,0x08,0x08,0x09,0x09;void beep(); sbit DIN = P07; /小数点bit flash=0; /显示开关标记/*/void Delay(unsigned int num)/延时函数while( -num );/*/Init_DS18B20(void)/初始化 ds1820DQ = 1; /DQ 复位Delay(8); /稍做延时DQ = 0; /单片机将 DQ 拉低Delay(90); /精确延时 大于 480usDQ = 1; /拉高总线Delay(8)
3、;presence = DQ; /如果=0 则初始化成功 =1 则初始化失败Delay(100);DQ = 1; return(presence); /返回信号, 0=presence,1= no presence/*/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 ch
4、ar dat)/写一个字节unsigned char i = 0;for (i = 8; i 0; i-)DQ = 0;DQ = datDelay(5);DQ = 1;dat=1;/*/Read_Temperature(void)/读取温度Init_DS18B20(); /初始化if(presence=1) beep();flash=1; /DS18B20 不正常,蜂鸣器报警else /初始化成功flash=0;/以下为 DS18B20 的基本操作时序WriteOneChar(0xCC); / 跳过读序号列号的操作WriteOneChar(0x44); / 启动温度转换Init_DS18B20
5、();WriteOneChar(0xCC); /跳过读序号列号的操作WriteOneChar(0xBE); /读取温度寄存器temp_data0 = ReadOneChar(); /温度低 8 位temp_data1 = ReadOneChar(); /温度高 8 位 /*/Disp_Temperature()/显示温度unsigned char n=0;display4=temp_data0display0=ditabdisplay4; /查表得小数位的值display4=(temp_data0 /整数位的值display3=display4/100; /百位值display1=displa
6、y4%100; /十位加个位值display2=display1/10; /十位值display1=display1%10; /个位值if(!display3) /高位为 0,不显示 display3=0x0a; if(!display2) /次高位为 0,不显示display2=0x0a;P0 = 0xc6; /显示 CP2 = 0x7f;Delay(300);P0 = 0x9c; /显示 P2 = 0xbf;Delay(300);P0 =LEDDatadisplay0 ; /显示小数位P2 = 0xdf;Delay(300);P0 =LEDDatadisplay1; /显示个位DIN =
7、0;P2 = 0xef;Delay(300);P0 =LEDDatadisplay2; /显示十位P2 = 0xf7;Delay(300);P0 =LEDDatadisplay3; /显示百位P2 = 0xfb;Delay(300);P2 = 0xff; /关闭显示/*/void beep()unsigned char i;for (i=0;i100;i+)Delay(60);BEEP=!BEEP; /BEEP 取反 BEEP=1; /关闭蜂鸣器/*/void main(void)while(1)Read_Temperature();if(flash=0) Disp_Temperature();else P2 = 0xff ; /DS18B20 不正常,关闭显示/*/