#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
uint temp; // variable of temperature
sbit DS=P1^0; //define interface
void delay1(uchar count)
{
while(count>0) count--;
}
void reset(void) //send reset and ini
tialization command
{
DS=0;
delay1(100);
DS=1;
delay1(4);
delay1(200);
}
bit read_bit(void) //read a bit
{
bit temp;
DS=0;
_nop_();
DS=1;
_nop_();
temp=DS;
delay1(200);
return temp;
}
uchar read_byte(void) //read a byte date
{
uchar i,byte=0;
bit j;
for(i=0;i<8;i++)
{
byte=_cror_(byte ,1);
j=read_bit();
if(j==0) byte=byte|0x00;
else byte=byte|0x80;
}
return byte;
}
void write_byte(uchar command) //write a byte to ds18b20
{
uchar i;
for(i=0;i<8;i++)
{
if((command & 0x01)==0)
{
DS=0;
delay1(8);
DS=1;
_nop_();
}
else
{
DS=0;
_nop_();
DS=1;
delay1(8);
}
command=_cror_(command,1);
}
}
void tmpchange(void) //DS18B20 begin change
{
reset();
write_byte(0xcc); //直接向18b20发送温度变换命令
write_byte(0x44); //启动18b20进行温度转换
}
uint tmp() //get the temperature
{
float tt;
uchar a,b;
reset();
write_byte(0xcc); //直接向18b20发送温度变换命令
write_byte(0xbe); //读取温度寄存器的温度值
a=read_byte();//读低八位
b=read_byte();//读高八位
temp=b;
temp<<=8; //two byte compose a int variable
temp=temp|a;
tt=temp*0.0625;
temp=tt*10+0.5;
return temp;
}
一周热门 更多>