#include #define uchar unsigned char #define uint unsigned int sbit DS=P2^2; // 18b20 IO连接引脚 sbit dula=P2^6; sbit wela=P2^7; unsigned char code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d, 0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71}; unsigned char code table1[]={0xbf,0x86,0xdb,0xcf,0xe6,0xed,0xfd, 0x87,0xff,0xef};//这里的是对应上面的数字,但是加了个点,即(x + 0x80) uint temp; // variable of temperature void DsReset(void); //send reset and initialization command bit TmpReadBit(void); //read a bit uchar TmpReadByte(void); //read a byte date void TmpWriteByte(uchar dat); //write a byte to ds18b20 void TmpTransfm(void); //DS18B20 begin transfomation uint ReadData(); //get the temperature void DisPlay(uint temp); //显示程序 void delay(uint count); //delay void main() { uchar i; while(1) { TmpTransfm(); DisPlay(ReadData()); } } void DsReset(void) // 器件初始化 { uint i; DS=0; // 拉低总线 i=103; while(i>0)i--; // 延时至少480us DS=1; // 释放总线,DS18B20检测到上升沿后会发送存在脉冲 i=4; while(i>0)i--; // 等待15-60us } bit TmpReadBit(void) // 读一位的数据 { uint i; bit dat; DS=0; // 拉低总线 i++; // 延时,保证总线拉低最少保持1us DS=1; // 释放总线 i++; // 延时 i++; dat=DS; // 读时序产生7us后读取总线数据 i=8;while(i>0)i--; // 延时,满足读时序的时间长度要求 return (dat); // 返回读取到的数据 } uchar TmpReadByte(void) // 读一个字节的数据 { uchar i, j, dat = 0; for(i=1;i<=8;i++) { j = TmpReadBit(); // 每次读取一位的数据 dat=(j<<7)|(dat>>1); // 读数据时最开始读的是最低位,所以每次读取的数据依次左移一位,这样刚好一个字节的数据放在dat里 } return(dat); // 返回一个字节的数据 } void TmpWriteByte(uchar dat) // 写一个字节的数据 { uint i; // 该数据不能够随便更改,不然会出错 uchar j; bit testb; for(j=1;j<=8;j++) { testb = dat & 0x01; // 取数据最低位 dat = dat >> 1; // 数据左移1位,即把已经取走的最低位移走 if(testb) // 写1 { DS=0; // 总线拉低 i++;i++; // 拉低时间要大于1us DS=1; // 总线拉高,15-60us期间总线为高,即为写入“1” i=8;while(i>0)i--; // } else // 写0 { DS=0; // 总线拉低 i=8;while(i>0)i--; // 写“0”时在15-60us期间总线保持为低,所以总线在拉低后延时较长时间 DS=1; // 释放总线 i++;i++; } } } void TmpTransfm(void) // 开始转换 { DsReset(); // 器件初始化 delay(1); TmpWriteByte(0xcc); // skip ROM TmpWriteByte(0x44); // 开始转换 } uint ReadData() { uchar a, b; float tt; // 用于计算的中间变量 DsReset(); // 这里必须也要初始化,不然读不出数据 delay(1); TmpWriteByte(0xcc); // Skip ROM TmpWriteByte(0xbe); // 发送读取数据命令 a = TmpReadByte(); // 读出低8位 b = TmpReadByte(); // 读出高8位 temp = b; temp <<= 8; temp = temp | a; // 高、低8位数据结合 tt = temp * 0.0625; // 转换为实际温度值,以浮点表示 temp = tt * 10 + 0.5; // 将浮点化为整数,+0.5为四舍五入处理 // 例:31.25,31.25*10 = 312.5 + 0.5 = 313,然后显示除以10即 为31.3,即保留1位小数 return temp; // 返回温度值 } void DisPlay(uint temp) //显示程序 { uchar A1,A2,A2t,A3; A1=temp/100; A2t=temp%100; A2=A2t/10; A3=A2t%10; dula=0; P0=table[A1]; //显示百位 dula=1; dula=0; wela=0; P0=0xfe; wela=1; wela=0; delay(1); dula=0; P0=table1[A2]; //显示十位 dula=1; dula=0; wela=0; P0=0xfd; wela=1; wela=0; delay(1); dula=0; P0=table[A3]; //显示个位 dula=1; dula=0; wela=0; P0=0xfb; wela=1; wela=0; delay(1); } void delay(uint count) { uint i; while(count) { i=200; while(i>0) i--; count--; } }