DS18B20驱动根据数据手册编写
#include<reg51.h>
sbit ds18b20=P1^4;
void delay_ds18b20(unsigned int x)
{
while(x--);
}
void ds18b20_res(void)
{
unsigned char x=255;
ds18b20=1;
ds18b20=0;
delay_ds18b20(80);
ds18b20=1;
delay_ds18b20(5);
while(ds18b20 && x--);
delay_ds18b20(20);
}
void ds18b20_write_bit(unsigned char x)
{
unsigned char i;
for(i=0;i<=7;i++)
{
ds18b20=0;
ds18b20= x & 0x01;
x=x>>1;
delay_ds18b20(10);
ds18b20=1;
}
ds18b20=1;
}
unsigned char ds18b20_read_bit()
{
unsigned char i,x;
for(i=0;i<=7;i++)
{
ds18b20=0;
delay_ds18b20(1);
ds18b20=1;
x=x>>1;
if(ds18b20 == 1) x=x|0x80;
delay_ds18b20(5);
ds18b20=1;
}
ds18b20=1;
return(x);
}
unsigned char dot,tem,tem_zf;
void read_tem()
{
unsigned char a,b;
ds18b20_res();
ds18b20_write_bit(0xcc);
ds18b20_write_bit(0x44);
ds18b20_res();
ds18b20_write_bit(0xcc);
ds18b20_write_bit(0xbe);
a = ds18b20_read_bit();
b = ds18b20_read_bit();
dot = 0x0f & a;
a=a>>4;
b=b<<4;
tem = a | b;
if((tem & 0x80) == 0x80)
{
tem_zf = 1;
tem = 0xff - tem;
dot = (0x0f - dot)*0.625;
}
else
{
tem_zf = 0;
dot = dot * 0.625;
}
}
void tem_max_min_write(unsigned char tem_max,char tem_min)
{
ds18b20_res();
ds18b20_write_bit(0xcc);
ds18b20_write_bit(0x4E);
ds18b20_write_bit(tem_max);
ds18b20_write_bit(tem_min);
ds18b20_res();
ds18b20_write_bit(0xcc);
ds18b20_write_bit(0x48);
}
char tem_max,tem_min;
void tem_max_min_read()
{
unsigned char tool;
ds18b20_res();
ds18b20_write_bit(0xcc);
ds18b20_write_bit(0xBE);
tool = ds18b20_read_bit();
tool = ds18b20_read_bit();
tem_max = ds18b20_read_bit();
tem_min = ds18b20_read_bit();
}