#include <reg51.h>//頭文件 #define uint unsigned int//宏定義 #define uchar unsigned char //宏定義 sbit DQ=P3^2;//18B20的2腳與單片機(jī)P3.2口相接 sbit P10=P1^0;//數(shù)碼管位選引腳P1.0 sbit P11=P1^1;//數(shù)碼管位選引腳P1.1 uchar temp; code unsigned char sz []={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};//0-9數(shù)組 void delay (uint t);//延時(shí)函數(shù)聲明 void delayms(uint a);//for語(yǔ)句延時(shí)函數(shù)聲明 void init();//18B20初始化程序聲明 void write (uchar dat);//寫1字節(jié)程序聲明 uchar read ();//讀1字節(jié)程序聲明 void display();//顯示程序聲明 uchar readtemp();//讀溫度程序聲明 void delay (uint t)//延時(shí)函數(shù) { while(t--); } void delayms(uint a) //for語(yǔ)句延時(shí)函數(shù) { uint x,y; for(x=a;x>0;x--) for(y=110;y>0;y--); } void init ()//18B20初始化程序 { uchar n; DQ=1; delay(8); DQ=0; delay(80); DQ=1; delay(8); n=DQ; delay(4); } void write (uchar dat)//寫1字節(jié)程序 { uchar i; for (i=0;i<8;i++) { DQ=0; DQ=dat&0x01; delay (4); DQ=1; dat>>=1;//dat=dat>>1 } delay(4); } uchar read ()//讀1字節(jié)程序 { uchar i,value; for (i=0;i<8;i++) { DQ=0; value>>=1; DQ=1; if(DQ) value|=0x80; delay(4); } return value; } uchar readtemp()//讀溫度程序 { uchar a,b; init(); write (0xcc); write (0x44); delay (300); init (); write (0xcc); write (0xbe); a=read(); b=read(); b<<=4; b+=(a&0xf0)>>4; return b; } void display ()//顯示程序 { P10=0; P0=sz[temp/10]; delayms(2); P10=1; P11=0; P0=sz[temp%10]; delayms(2); P11=1; } void main()//主程序 { while(1) { temp=readtemp(); display (); } } |
|