找回密碼
 立即注冊

QQ登錄

只需一步,快速開始

搜索
查看: 1478|回復: 0
收起左側

DS18B20溫度模塊驅動代碼

[復制鏈接]
ID:687726 發(fā)表于 2021-12-1 08:15 | 顯示全部樓層 |閱讀模式
代碼如下:
#include"temp.h"

void Delay1ms(uint y)
{
        uint x;
        for( ; y>0; y--)
        {
                for(x=110; x>0; x--);
        }
}

uchar Ds18b20Init()
{
        uchar i;
        DSPORT = 0;                       
        i = 70;       
        while(i--);
        DSPORT = 1;               
        i = 0;
        while(DSPORT)       
        {
                Delay1ms(1);
                i++;
                if(i>5)
                {
                        return 0;
                }
       
        }
        return 1;
}

void Ds18b20WriteByte(uchar dat)
{
        uint i, j;

        for(j=0; j<8; j++)
        {
                DSPORT = 0;                      
                i++;
                DSPORT = dat & 0x01;
                i=6;
                while(i--);
                DSPORT = 1;       
                dat >>= 1;
        }
}

uchar Ds18b20ReadByte()
{
        uchar byte, bi;
        uint i, j;       
        for(j=8; j>0; j--)
        {
                DSPORT = 0;
                i++;
                DSPORT = 1;
                i++;
                i++;
                bi = DSPORT;         

                byte = (byte >> 1) | (bi << 7);                                                  
                i = 4;               
                while(i--);
        }                               
        return byte;
}

void  Ds18b20ChangTemp()
{
        Ds18b20Init();
        Delay1ms(1);
        Ds18b20WriteByte(0xcc);               
        Ds18b20WriteByte(0x44);          
}

void  Ds18b20ReadTempCom()
{       

        Ds18b20Init();
        Delay1ms(1);
        Ds18b20WriteByte(0xcc);         
        Ds18b20WriteByte(0xbe);       
}

int Ds18b20ReadTemp()
{
        int temp = 0;
        uchar tmh, tml;
        Ds18b20ChangTemp();                         
        Ds18b20ReadTempCom();               
        tml = Ds18b20ReadByte();       
        tmh = Ds18b20ReadByte();               
        temp = tmh;
        temp <<= 8;
        temp |= tml;
        return temp;
}

歡迎大家學習指正。

回復

使用道具 舉報

您需要登錄后才可以回帖 登錄 | 立即注冊

本版積分規(guī)則

手機版|小黑屋|51黑電子論壇 |51黑電子論壇6群 QQ 管理員QQ:125739409;技術交流QQ群281945664

Powered by 單片機教程網

快速回復 返回頂部 返回列表