专注电子技术学习与研究
当前位置:单片机教程网 >> MCU设计实例 >> 浏览文章

DS18B20与数码管程序

作者:我行天下   来源:本站原创   点击数:  更新时间: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();//显示  
   }
}

关闭窗口

相关文章