_________________________________________________________ 功能:數碼管顯示XX.XC標示攝氏度,例如25.3C標示當前溫度 時間:2010—7—20 _________________________________________________________ #include<reg52.h> #include<math.h> #include<INTRINS.H> #define uchar unsigned char #define uint unsigned int; sbit seg1=P2^0; sbit seg2=P2^1; sbit seg3=P2^2; sbit DQ=P1^3; sfr dataled=0x80; uint temp; uchar flag_get,count,num,minute,second; uchar code tab[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f}; uchar str[6]; void delay1(uchar MS); unsigned int ReadTemperature(void); void Init_DS18B20(void); unsigned char ReadOneChar(void); void WriteOneChar(unsigned char dat); void delay(unsigned int i); main() { unsigned char TempH,TempL; TMOD|=0x01; TH0=0xef; TL0=0xf0; IE=0x82; TR0=1; P2=0x00; count=0; while(1) { str[5]=0x39; str[1]=tab[TempH/100]; str[2]=tab[(TempH%100)/10]; str[3]=tab[(TempH%100)%10]|0x80; str[4]=tab[TempL]; if(flag_get==1) { temp=ReadTemperature(); if(temp&0x8000) { str[0]=0x40; temp=~temp; temp +=1; } else str[0]=0; TempH=temp>>4; TempL=temp&0x0F; TempL=TempL*6/10; flag_get=0; } } } void tim(void) interrupt 1 using 1 { TH0=0xef; TL0=0xf0; num++; if (num==50) { num=0; flag_get=1; second++; if(second>=60) { second=0; minute++; } } count++; if(count==1) { P2=0; dataled=str[0]; } if(count==2) { P2=1; dataled=str[1]; } if(count==3) { P2=2; dataled=str[2]; } if(count==4) { P2=3; dataled=str[3]; } if(count==5) { P2=4; dataled=str[4]; } if(count==6) { P2=5; dataled=str[5]; count=0; } } void delay(unsigned int i) { while(i--); } void Init_DS18B20(void) { unsigned char x=0; DQ = 1; delay(8); DQ = 0; delay(80); DQ = 1; delay(10); x=DQ; delay(5); } unsigned char 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(5); } return(dat); } void WriteOneChar(unsigned char dat) { unsigned char i=0; for (i=8; i>0; i--) { DQ = 0; DQ = dat&0x01; delay(5); DQ = 1; dat>>=1; } delay(5); } unsigned int ReadTemperature(void) { unsigned char a=0; unsigned int b=0; unsigned int t=0; Init_DS18B20(); WriteOneChar(0xCC); WriteOneChar(0x44); delay(200); Init_DS18B20(); WriteOneChar(0xCC); WriteOneChar(0xBE); a=ReadOneChar(); b=ReadOneChar(); b<<=8; t=a+b; return(t); }