DS18B20程序
#include
#include
#include "Delay.h"
sbit DS18b20_DataPort=P1^7; //引腳選擇
bit DS18b20_reset(void) //返回0-有設(shè)備連接1-無(wú)設(shè)備連接
{
unsigned char i;
bit RstFlag;
RstFlag=1;
DS18b20_DataPort=0;
delay_us(600);//器件反應(yīng)時(shí)間最少480us
DS18b20_DataPort=1;
delay_us(60); //15us-60us
for (i=0;i<16;i++) //60us-240us
{
delay_us(15);
if (DS18b20_DataPort==0)
RstFlag=0;
}
delay_us(240);// 低電平持續(xù)時(shí)間最少240us
return RstFlag;
}
void DS1820_write(unsigned char command)
{
unsigned char i;
DS18b20_DataPort=1;
delay_us(1);
for (i=0;i<8;i++)
{
EA=0;
DS18b20_DataPort=0;
delay_us(15);
DS18b20_DataPort=ch&0x1;
EA=1;
delay_us(50);
DS18b20_DataPort=1;
command=command>>1;
delay_us(1);
}
}
unsigned char DS1820_read(void)
{
unsigned char i,date = 0;
DS18b20_DataPort = 1;
delay_us(1);
for (i = 0;i < 8;i++)
{
EA = 0;
DS18b20_DataPort = 0;
delay_us(10);
DS18b20_DataPort = 1;
delay_us(2);
date = date>>1;
if (DS18b20_DataPort == 1)
{
date += 0x80;
}
EA = 1;
delay_us(50);
}
return date;
}
void DS1820_skipROM(void) //主機(jī)發(fā)送跳過(guò)讀序列號(hào)的操作指令
{
DS18b20_reset();
DS18b20_write(0xcc);
}
void DS1820_startADC(void)
{
DS18b20_reset(); //復(fù)位
DS18b20_write(0xcc); //廣播
DS18b20_write(0x44); //啟動(dòng)AD轉(zhuǎn)換 12bit700ms
}
unsigned int DS1820_getTempValue(void)
{
unsigned char i,j;
unsigned int T;
DS18b20_skipROM();
DS18b20_write(0xBE); //讀取溫度的命令
i=DS18b20_read();
j=DS18b20_read();
DS18b20_startADC();
T = i+j*256;
if (T==0xffff)
return 0xffff;
if (T>0x8000) //溫度為負(fù)號(hào)
{
T = -T;
return (0x8000+T*5/80); // 計(jì)算溫度的值
}
else //溫度為正值
return (T*5/80);
}
//主函數(shù)
void main(void)
{
int w;
Init();//系統(tǒng)初始化
while(1)
{
w = DS1820_getTempValue(); //將溫度值送出
_nop_;
_nop_;
_nop_;
}
//while(1);
}
//-------------------------------------------------------------
//程序結(jié)束
//---------------------------------