⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ds18b20.h

📁 这是一个电子钟和温度计的程序
💻 H
字号:
//DS1820 C51 子程序
//这里以11.0592M晶体为例,不同的晶体速度可能需要调整延时的时间
sbit DQ =P3^0;//根据实际情况定义端口

typedef unsigned char byte;
typedef unsigned int  word;
byte i;
/*void delays(unsigned char k)
{
 unsigned char i,j;
 for(i=0;i<k;i++)
  for(j=0;j<50;j++);
}*/ 
//*********** 18B20驱动 **************************
void delay1(unsigned char i)
{
  while(--i);
}
//复位
byte ow_reset(void)
{
  byte presence;
  DQ=0;        //拉低总线
  delay1(250);    // 保持 480us
  delay1(250);
  DQ = 1;       // 释放总线
  delay1(30);     // 等待回复
  presence = DQ; // 读取信号
  delay1(250);    // 等待结束信号
  return(presence); // 返回   0:正常 1:不存在
}     
//从 1-wire 总线上读取一个字节
byte read_byte(void)
{
  byte i;
  byte value = 0;
  for (i=8;i>0;i--)
  {
    value>>=1;
    DQ = 0; 
    DQ = 1;
    delay1(2);  
    if(DQ)value|=0x80;
    delay1(6); 
  }
  return(value);
}
//向 1-WIRE 总线上写一个字节
void write_byte(char val)
{
  byte i;
  for (i=8; i>0; i--)  // 一次写一位
  { DQ=1;
    DQ=0; 
    DQ = val&0x01;
    delay1(30);  
    DQ = 1;
    val=val/2;
  }
  delay1(70);
}
void adjust_res(char res) ///res 分别等于 0x1f, 0x3f, 0x5f 温度读数分辨率分别对应
                           //              0.5, 0.25, 0.125   
{
  ow_reset();        //复位
  write_byte(0xcc);  //跳过Rom
  write_byte(0x4e);  //写暂存器
  write_byte(0x02);  //写TH 
  write_byte(0x01);  //写TL
  write_byte(0x7f);  //写结构寄存器
  write_byte(res);
  ow_reset();       //复位
  write_byte(0xcc); //跳过Rom 
  write_byte(0x48); //把暂存器内容写到EPRam中
}
unsigned int Read_Temperature(void)
{   
 union
 {
  unsigned char c[2];
  unsigned int x;
 }temp;
 temp.x=0x0000;
 i=ow_reset();

 write_byte(0xCC);    //Skip ROM
 write_byte(0xBE);    //Read Scratch Pad
 temp.c[1]=read_byte();  //Start read data
 temp.c[0]=read_byte();  //read two byte data from device
 ow_reset();        //reset
 write_byte(0xCC);    //Skip ROM
 write_byte(0x44);    //Start Conversion
 
 return temp.x;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -