專注電子技術學習與研究
當前位置:單片機教程網 >> MCU設計實例 >> 瀏覽文章

DS18B20與數碼管程序

作者:我行天下   來源:本站原創(chuàng)   點擊數:  更新時間:2014年03月31日   【字體:

#include<reg51.h>
#define uint unsigned int
#define uchar unsigned char
sbit DQ=P2^0;//P2^0
uchar code tab[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};//不帶小數點
uchar code tab1[]={0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0x00,0x10};//帶小數點
sbit wei0=P0^0;//P3^2
sbit wei1=P0^1;//P3^3
//sbit wei2=P1^2;
//sbit wei3=P1^3;
uchar disdata[2];
uint tvalue;
uchar tflag;
void delay(uint i)
{
  while(i--);
}
void ds1820rst()//復位
{
  DQ=1;
  delay(4);
  DQ=0;
  delay(100);
  DQ=1;
  delay(40);
}
uchar ds1820rd()//讀數據
{
  uchar i;
  uchar dat=0;
   for(i=8;i>0;i--)
   {
      DQ=0;
   dat>>=1;
   DQ=1;
   if(DQ)
   dat|=0x80;//dat=DQ;dat&=0x80;
   delay(10);
   }
   return(dat);
}
void ds1820wr(uchar wdata)//寫數據
{
 uchar i=0;
  for(i=8;i>0;i--)
  {
    DQ=0;
    DQ=wdata&0x01;
    delay(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.0625);//0.625溫度值擴大10倍,精確到1位小數
return(tvalue);
}
 
 
void ds1820disp()//溫度值顯示
{
   disdata[0]=tvalue/10;//十位數
   disdata[1]=tvalue%10;//個位數
   wei0=0;
   P1=tab[disdata[0]];
   delay(250);
 wei0=1;
 wei1=0;
 P1=tab[disdata[1]];
 delay(250);
 wei1=1;
}
 
void main()
{
       while(1) 
   {
     
    read_temp();//讀取溫度
  
       ds1820disp();//顯示  
   }
}

關閉窗口

相關文章