DS18B20与数码管温度显示C程序(4页).doc
-DS18B20与数码管温度显示C程序-第 4 页#include<reg52.h>#define uchar unsigned char#define uint unsigned intsbit DQ=P14;/ds18b20与单片机连接口unsigned char code str=0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x39;/共阴数码管字码表unsigned char code str1=0x0bf,0x86,0x0db,0x0cf,0x0e6,0x0ed,0x0fd,0x87,0x0ff,0x0ef,0x39;/个位带小数点字码表unsigned char code wei=0x0fe,0x0fd,0x0fb,0x0f7;uchar data disdata5;uint tvalue;/温度值uchar tflag;/温度正负标志/*ds1820程序*/void delay_18B20(unsigned int i)/延时1微秒 while(i-);void ds1820rst()/*ds1820复位*/ unsigned char x=0;DQ = 1; /DQ复位delay_18B20(4); /延时DQ = 0; /DQ拉低delay_18B20(100); /精确延时大于480usDQ = 1; /拉高delay_18B20(40); uchar ds1820rd()/*读数据*/ 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_18B20(10); return(dat);void ds1820wr(uchar wdata)/*写数据*/unsigned char i=0; for (i=8; i>0; i-) DQ = 0; DQ = wdata&0x01; delay_18B20(10); DQ = 1; wdata>>=1;read_temp()/*读取温度值并转换*/uchar a,b;ds1820rst();ds1820wr(0xcc);/*跳过读序列号*/ds1820wr(0x44);/*启动温度转换*/ds1820rst();ds1820wr(0xcc);/*跳过读序列号*/ds1820wr(0xbe);/*读取温度*/a=ds1820rd();b=ds1820rd();tvalue=b;tvalue<<=8;tvalue=tvalue|a; if(tvalue<0x0fff) tflag=0; else tvalue=tvalue+1;tflag=1;tvalue=tvalue*(0.625);/温度值扩大10倍,精确到1位小数return(tvalue); void ds1820disp()/温度值显示 uchar flagdat; uchar i; disdata0=tvalue/1000;/百位数 disdata1=tvalue%1000/100;/十位数 disdata2=tvalue%100/10;/个位数 disdata3=tvalue%10;/小数位 if(tflag=0) flagdat=0x20;/正温度不显示符号 else flagdat=0x2d;/负温度显示负号:- if(disdata0=0x30) disdata0=0x20;/如果百位为0,不显示 if(disdata1=0x30) disdata1=0x20;/如果百位为0,十位为0也不显示for(i=0;i<150;i+) P2=wei0; P0=strdisdata3; delay_18B20(20); P2=wei1; P0=str1disdata2; delay_18B20(20); P2=wei2; P0=strdisdata1; delay_18B20(20); P2=wei3; P0=strdisdata0; delay_18B20(20);/*主程序*/void main() ds1820rst;/初始化显示 while(1)read_temp();/读取温度 ds1820disp();/显示