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

📄 18b20.txt

📁 温度芯片DS18B20子程序.在MPLAB上使用,
💻 TXT
字号:
//*************************************************************************
//                  DS18B20子程序
//*************************************************************************

#include <pic.h>

#define uchar unsigned char
# define unint unsigned int

//************************端口定义***********************//
# define DQ        RA1//定义18B20数据端口     
# define DQ_DIR    TRISA1//定义18B20D口方向寄存器

# define W1_INPUT    1
# define W1_OUTPUT    0
# define FALSE        0
# define TRUE        !FALSE
# define DQ_HIGH()     DQ_DIR = W1_INPUT
# define DQ_LOW()      DQ = 0; DQ_DIR = W1_OUTPUT
uchar teml,temh;                             //温度的低高位--十六进制
unint dis_temp_int,dis_temp_float;         //温度显示的整数、小数
uchar dis_temp_int_h,dis_temp_int_l;         //温度显示的整数的高低位
//uchar dis_temp_float_h,dis_temp_float_l;   //温度显示的小数的高低位 


void delay(unint x)
{
    unint d;
    d=x;
    while(--d)
    {;}
}

bit reset(void)//初始化18B20 
{
     static bit presence;//定义一个应答信号     
     DQ_LOW();
     delay(70);//置总线为低电平并保持至少480us 
     DQ_HIGH();//等电阻拉高总线并保持15-60us 
     delay(5);
     presence=DQ;//接受应答信号 
     delay(20);//延时60-240us 
     return(presence);//返回应答信号 
}


//***************  读一位函数 ******************// 
bit read_bit(void)
{
    static bit i;
    DQ_LOW();
    DQ_LOW();
    DQ_HIGH();
    asm("nop");
    asm("nop");
    asm("nop");
    i=DQ;
    delay(3);
    return(i);
}

//*********************写一位函数****************// 
void write_bit(uchar bitval)
{
    DQ_LOW();
    delay(1);
    if (bitval==1)
    {
       DQ_HIGH();
     }
    delay(3);
    DQ_HIGH();
}

//**************  从18B20中读一个字节**************// 
uchar read_byte(void)
{
    uchar i;
    uchar j;
    uchar value=0;
    for (i=0;i<8;i++)
    {
        j=read_bit();//调读位函数 
        if (j)//如果是 1 置1 
        {
            value|=(0x01<<i);//先读低位,再读高位 
            asm("nop");
            asm("nop");
            asm("nop");
          }
     }//否则置 0 
    return(value);
}

//*********************向18B20中 写一个字节**************// 
void write_byte(uchar val)
{
     uchar i;
     uchar temp;
     for (i=0;i<8;i++)
     {
          temp=val>>i;
          temp&=0x01;
          write_bit(temp);//调写位函数 
       }
      asm("nop");
      asm("nop");
      asm("nop");
}

//*********************程序初始化**************//
void temp_initial()
{
       do{
         ;
        }while (reset()) ;//复位等待从机应答 
        write_byte(0XCC);//忽略ROM匹配 
        write_byte(0X44);//发送温度转化命令 
        delay(2500);//延时100-300us  2500
        do
        {
         ;
         }while( reset());//再次复位,等待从机应答 
        write_byte(0XCC);//忽略ROM匹配 
        write_byte(0XBE);//发送读温度命令
 }

⌨️ 快捷键说明

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