标题:
DS18B20读写程序
[打印本页]
作者:
Kent_Cheung
时间:
2018-4-11 16:39
标题:
DS18B20读写程序
//----------------------------------------------------------
// 模块名称:DS18B20.h
// 模块功能:DS18B20 读写操作
//----------------------------------------------------------
sbit DS = P1^0;
//----------------------------------------------------------
// 函数名称:void DelayTmp(unsigned int count)
// 函数功能:延时
//----------------------------------------------------------
void DelayTmp(unsigned int count)
{
unsigned int i;
while(count)
{
i=200;while(i》0)i--;
count--;
}
}
//----------------------------------------------------------
// 函数名称:void DsReset(void)
// 函数功能:复位
//----------------------------------------------------------
void DsReset(void)
{
unsigned int i;
DS=0;
i=103; while(i》0)i--;
DS=1;
i=4;while(i》0)i--;
}
//----------------------------------------------------------
// 函数名称:bit TmpReadBit(void)
// 函数功能:读取一位
//----------------------------------------------------------
bit TmpReadBit(void)
{
unsigned int i;
bit dat;
DS=0;i++;
DS=1;i++;i++;
dat=DS;
i=8;while(i》0)i--;
return (dat);
}
//----------------------------------------------------------
// 函数名称:unsigned char TmpRead(void)
// 函数功能:读取一字
//----------------------------------------------------------
unsigned char TmpRead(void)
{
unsigned char i,j,dat;
dat=0;
for(i=1;i《=8;i++)
{j=TmpReadBit();
dat=(j《《7)|(dat》》1); }
return(dat);
}
//----------------------------------------------------------
// 函数名称:void TmpWriteByte(unsigned char dat)
// 函数功能:写入一字节
//----------------------------------------------------------
void TmpWriteByte(unsigned char dat)
{
unsigned int i;
unsigned char j;
bit testb;
for(j=1;j《=8;j++)
{
testb=dat&0x01
dat=dat》》1;
if(testb) //write 1
{
DS=0;
i++;i++;
DS=1;
i=8;while(i》0)i--;
}
else
{
DS=0; //write 0
i=8;while(i》0)i--;
DS=1;
i++;i++;
}
}
}
//----------------------------------------------------------
// 函数名称:void TmpChange(void)
// 函数功能:温度转换
//----------------------------------------------------------
void TmpChange(void)
{
DsReset();
DelayTmp(1);
TmpWriteByte(0xcc);
TmpWriteByte(0x44);
}
//----------------------------------------------------------
// 函数名称:unsigned int Tmp()
// 函数功能:获取温度
//----------------------------------------------------------
unsigned int Tmp()
{
float tt;
unsigned char a,b;
unsigned int temp;
DsReset();
DelayTmp(1);
TmpWriteByte(0xcc);
TmpWriteByte(0xbe);
a=TmpRead();
b=TmpRead();
temp=b;
temp《《=8;
temp=temp|a;
tt=temp*0.0625;
temp=tt*10+0.5;
return temp;
}
//----------------------------------------------------------
// 函数名称:void RefreshTmp()
// 函数功能:刷新温度
//----------------------------------------------------------
void RefreshTmp()
{
TmpChange();
DisplayTmp(Tmp());
}
欢迎光临 (http://www.51hei.com/bbs/)
Powered by Discuz! X3.1