51單片機定時溫度控制,數碼管顯示。時間和溫度。
單片機源程序如下:
- #include<reg52.h>
- #include<intrins.h>
- sbit DQ=P2^2;//溫度采集
- sbit latch1=P2^6;//段鎖存
- sbit latch2=P2^7;//位鎖存
- unsigned char code dofly_DuanMa[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};//顯示0~9
- unsigned char code dofly_WeiMa[]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};//點亮數碼管
- unsigned char TempData[8];//存儲顯示的度數
- bit Readtime;//讀取時間的標志
- //定義延時函數delayus,delayms
- void delayus(unsigned char t)
- {
- while(--t);
- }
- void delayms(unsigned char t)
- {
- while(t--)
- {
- delayus(245);
- delayus(245);
- }
- }
- //18b20初始化
- bit ds18b20()
- {
- bit test=0;
- DQ=1;//復位DQ
- delayus(5);//稍作延時
- DQ=0;//將DQ拉低
- delayus(200);//精確 >480us <960us
- delayus(200);
- DQ=1;//將DQ拉高
- delayus(50);//延時15~60us后,接收脈沖
- test=DQ;//判斷是否初始化成功
- delayus(25);//延時后返回值
- return test;
- }
- //顯示程序函數
- void Display(unsigned char FirstBit,unsigned char Num)
- {
- static unsigned char i=0;
- P0=0;//防止有重影
- latch1=1;//段鎖存
- latch1=0;
- P0=dofly_WeiMa[i+FirstBit];//取位碼
- latch2=1;//位鎖存
- latch2=0;
- P0=TempData[i];//取顯示數據,取斷碼
- latch1=1;//段鎖存
- latch2=0;
- i++;
- if(i==Num)
- i=0;
- }
- //讀數據函數
- unsigned char Readchar()
- {
- unsigned char i=0;
- unsigned char test=0;
- for(i=8;i>0;i--)
- {
- DQ=0;
- test>>=1;//右移一位
- DQ=1;
- if(DQ)
- test|=0x80;
- delayus(25);
- }
- return(test);
- }
- //寫入數據函數
- void Writechar(unsigned char test)
- {
- unsigned char i=0;
- for(i=8;i>0;i--)
- {
- DQ=0;
- DQ=test&0x01;
- delayus(25);
- DQ=1;
- test>>=1;
- }
- delayus(25);
- }
- //讀取溫度函數
- unsigned int ReadTempture()
- {
- unsigned char a=0;
- unsigned int b=0;
- unsigned int t=0;
- ds18b20();
- Writechar(0xCC);//跳過讀序列號
- Writechar(0x44);//啟動溫度轉換
- delayms(10);
- ds18b20();
- Writechar(0xCC);//跳過讀序列號
- Writechar(0xBE);//讀取溫度
- a=Readchar();//高8位
- b=Readchar();//低8位
- b<<=8;
- t=a+b;
- return(t);
- }
- //主函數main
- void main()
- {
- unsigned int TempH,TempL,Temp;
- TMOD |= 0x01;//確定使用哪個定時器,確定工作模式
- EA=1; //打開中斷允許
- ET0=1; //定時器T0允許
- TR0=1; //啟動T0
- while(1)
- {
- if(Readtime==1)
- {
- Readtime=0;
- Temp=ReadTempture();
- if(Temp&0x8000)
- {
- TempData[0]=0x40;//表示為負數
- Temp=~Temp;//取反碼
- Temp+=1;//取補碼
- }
- }
- else
- TempData[0]=0;//表示為正數
- TempH=Temp>>4;
- TempL=Temp&0x0F;
- TempL=TempL*6/10;//小數近似處理
- if(TempH/100==0)
- TempData[1]=0;//百位
- else
- TempData[1]=dofly_DuanMa[TempH/100];//十位
- if((TempH/100==0)&&((TempH%100)/10==0))//消影
- TempData[2]=0;
- else
- TempData[2]=dofly_DuanMa[(TempH%100)/10];//十位
- TempData[3]=dofly_DuanMa[(TempH%100)%10]|0x80;//個位溫度,帶小數點
- TempData[4]=dofly_DuanMa[TempL];//小數位溫度
- TempData[6]=0x39;//顯示溫度C
- }
- }
- //定時中斷函數
- void Timer0_isr() interrupt 1
- {
- static unsigned int num;
- TH0=(65536-2000)/256;
- TL0=(65536-2000)%256;
-
- Display(0,8);//調用函數
- num++;
- if(num==300)
- {
- num=0;
- Readtime=1; //讀標志位1
- }
- }
復制代碼
所有資料51hei提供下載:
5.rar
(30.19 KB, 下載次數: 16)
2019-2-18 14:32 上傳
點擊文件名下載附件
下載積分: 黑幣 -5
|