專注電子技術(shù)學(xué)習(xí)與研究
當(dāng)前位置:單片機(jī)教程網(wǎng) >> MCU設(shè)計實(shí)例 >> 瀏覽文章

基于C8051F的18B20程序

作者:文于鷹   來源:本站原創(chuàng)   點(diǎn)擊數(shù):  更新時間:2013年12月06日   【字體:

 

#include "C8051F410.h"
#include <INTRINS.H>
#define uint  unsigned int
#define uchar unsigned char

sbit DQ   = P2^4 ;

void delay(unsigned int i)
{
 while(i--);
}
Init_DS18B20(void)
{
  unsigned char x=0;
  DQ = 1;         //DQ復(fù)位
  delay(176);      //稍做延時
  DQ = 0;         //單片機(jī)將DQ拉低
  delay(1760);     //精確延時 大于 480us
  DQ = 1;         //拉高總線
  delay(308);
 x=DQ;           //稍做延時后 如果x=0則初始化成功 x=1則初始化失敗
 delay(440);
}

uchar ReadOneChar(void)
{
  unsigned char i=0;
 unsigned char dat = 0;
 for (i=8;i>0;i--)
  {
    DQ = 0;     // 給脈沖信號
    dat>>=1;
    DQ = 1;     // 給脈沖信號
    if(DQ)
     dat|=0x80;
    delay(88);
  }
  return(dat);
}

WriteOneChar(unsigned char dat)
{
  unsigned char i=0;
  for (i=8; i>0; i--)
  {
    DQ = 0;
    DQ = dat&0x01;
    delay(110);
    DQ = 1;
    dat>>=1;
  }
}

uint ReadTemperature(void)   //溫度*10
{
  uchar a=0;
  uchar b=0;
  uint temp=0;
  uint t=0;
  int temple;              /*存放讀取的溫度值 將其除以16即為得到的值*/
  Init_DS18B20();
  WriteOneChar(0xCC);   // 跳過讀序號列號的操作
  WriteOneChar(0x44);   // 啟動溫度轉(zhuǎn)換
  Init_DS18B20();
  WriteOneChar(0xCC);   //跳過讀序號列號的操作
  WriteOneChar(0xBE);   //讀取溫度寄存器等(共可讀9個寄存器) 前兩個就是溫度
  a=ReadOneChar();   //低8位
  b=ReadOneChar();   //高8位
  temp=b;
  temp<<=8;
  temp=temp|a;
  temp&=0x07ff;
    if( (b&0x08))
    {
        temple=~temp+1;     //如果為負(fù)溫則去除其補(bǔ)碼
        FWD=0;           /*表示溫度為負(fù)數(shù)*/
    }
    else
    {
        temple=temp;
        FWD=1;         /*表示溫度為正數(shù)*/
    }
    t=temple*10/16;
 //t = temp;
 //t= t*625;
 //t = t/1000;
 return(t);
}
 

關(guān)閉窗口

相關(guān)文章