1、#include #define DO P3_7 #define SEG P0 /数码管自左至右依次为 1234 位#define MS2L 0x18 /1ms 的延时参数#define MS2H 0xfc#define uchar unsigned char#define uint unsigned intuchar code comm4 = 0x01,0x02,0x04,0x08;uchar code seg10 = 0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90;uchar code seg_add_dicimal10 = 0x40,0
2、x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10; uchar code seg_dicimal2 =0xc0, 0x92;uchar k = 0;uchar temp_l = 0;uchar temp_h = 0;uchar tempsign = 0;uchar hundreds = 0;uchar tens = 0;uchar ones = 0;uchar low_four = 0;/*延时以 ms 为单位的 t 时间*/void Delay(uint t)uint i;while(t-)for(i=0; i 1;/*配置 ds18b20,9 位分辨率
3、 */void Configurate()EA = 0;Resetpaulse(); /发出复位脉冲,每次操作都从复位开始Delay(1);Writebyte(0xcc); /skip room 命令Writebyte(0x4e);Writebyte(0x7f);Writebyte(0x80);Writebyte(0x1f);EA = 1;/*启动温度转换*/void StartConvert()Resetpaulse(); / 发出复位脉冲,每次操作都从复位开始Delay(1);EA = 0;Writebyte(0xcc); /skip room 命令Writebyte(0x44); /启动
4、温度转换命令EA = 1;/*读取温度值*/void ReadTempreture()EA = 0;Resetpaulse(); / 发出复位脉冲,每次操作都从复位开始Delay(1);Writebyte(0xcc); /skip room 命令Writebyte(0xbe); /读取暂存器命令temp_l = Readbyte(); /存储温度低字节值 (整数部分低四位和小数部分)temp_h = Readbyte(); /存储温度高字节值 (其中高五位为符号位)EA = 1;/*数据转换*/void DigitalConvert()uchar total = 0;tempsign = (t
5、emp_h 7) /得出符号位if(tempsign = 0) /正数的处理方法 total = (temp_h 4) /取整数位low_four = (temp_l3) /取小数位,9 位分辨率,低字节第 3 位为小数位,只有 0、1 两种取值hundreds = total / 100; /计算百、十、个位 tens = (total%100)/10;ones = (total%100)%10;else /负数处理 求负数补码规则是,按位取反,得到反码,加 1 即得补码(符号位不变)tempsign = 1;total = (temp_l 4) /取整数部分低 4 位total |= (t
6、emp_h 3) /取小数位if(low_four = 0) /这里 total 位 uchar 型变量,所以根据最低位来确定整数取补规则total = total + 1; /最低位为 0 的时候,取反加 1 后有进位,所以这里 total 要取反加1elsetotal = total; /最低位为 1 的时候,取反加 1 没有进位,所以 total 直接取反即可tens = (total%100)/10;ones = (total%100)%10;/*中断处理*/void Display() interrupt 1EA = 0;TL0 = MS2L;TH0 = MS2H; DigitalC
7、onvert(); /数据转换if(tempsign = 0) /正数if(k = 0)if(hundreds = 0) /高位 0 消隐P1 = 0;elseP1 = commk;SEG = seghundreds; else if(k = 1)if(tens = 0 elseP1 = commk;SEG = segtens; else if(k = 2) /显示个位,因为个位有小数点,所以又定义了一个数组分开来显示P1 = commk;SEG = seg_add_dicimalones; /要加上小数点else /显示小数,0 或 5P1 = commk;SEG = seg_dicimal
8、low_four; else if(tempsign = 1) /负数if(k = 0) /显示符号位P1 = commk;SEG = 0xbf;else if(k = 1)if(tens = 0)P1 = 0;elseP1 = commk;SEG = segtens; else if(k = 2) /显示个位,因为各位有小数点,所以分开来显示P1 = commk;SEG = seg_add_dicimalones; /要加上小数点else /显示小数, 0 或 5P1 = commk;SEG = seg_dicimallow_four; k+;if(k = 4) k = 0;EA = 1;/*主函数部分*/void main()TMOD = 0x01;TL0 = MS2L;TH0 = MS2H; TF0 = 0; EA = 1;ET0 = 1;TR0 = 1;Configurate();doDelay(1);StartConvert();Delay(100);ReadTempreture();while(1);