|
void Delay1ms(uchar ms)
{
uint x,y;
for(x=ms; x>0; x--)
{
for(y=124; y>0; y--);
}
}
void delay_us(uchar us)
{
while(--us);
}
uchar Ds18b20Init()
{
uchar i;
bit x;
DSPORT = 1; //将总线拉低480us~960us
delay_us(5);
while(i--); //延时642us
DSPORT = 0; //然后拉高总线,如果DS18B20做出反应会将在15us~60us后总线拉低
delay_us(300);
delay_us(300);
DSPORT = 1;
delay_us(50);
x= DSPORT;
delay_us(25);
return x; //初始化成功
}
void Ds18b20WriteByte(uchar dat)
{
uint j;
for(j=0; j<8; j++)
{
DSPORT = 0; //每写入一位数据之前先把总线拉低1us
DSPORT = dat & 0x01; //然后写入一个数据,从最低位开始
delay_us(25);
DSPORT = 1; //然后释放总线,至少1us给总线恢复时间才能接着写入第二个数值
dat >>= 1;
}
delay_us(25);
}
uchar Ds18b20ReadByte()
{
uchar byte = 0;
uint j;
for(j=8; j>0; j--)
{
DSPORT = 0;
byte >>= 1; //先将总线拉低1us
DSPORT = 1; //然后释放总线 //延时6us等待数据稳定
if(DSPORT)
byte |= 0x80;
delay_us(25);
}
return byte;
}
void Ds18b20ChangTemp()
{
Ds18b20Init();
Delay1ms(1);
Ds18b20WriteByte(0xcc); //跳过ROM操作命令
Ds18b20WriteByte(0x44);
}
void Ds18b20ReadTempCom()
{
Ds18b20Init();
Delay1ms(1);
Ds18b20WriteByte(0xcc); //跳过ROM操作命令
Ds18b20WriteByte(0xbe); //发送读取温度命令
}
int Ds18b20ReadTemp()
{
char temp ;
uchar tmh, tml;
Ds18b20ChangTemp();
Delay1ms(30); //先写入转换命令
Ds18b20ReadTempCom(); //然后等待转换完后发送读取温度命令
tml = Ds18b20ReadByte(); //读取温度值共16位,先读低字节
tmh = Ds18b20ReadByte(); //再读高字节
temp = tmh<<8|tml;
return temp;
}
|
|