基于蓝桥杯官网给的代码做了一些修改,在proteus上成功仿真
#include "reg52.h"
sbit DQ = P2^3;
//************************下面的代码需要自己写***********************//
void Delay_OneWire(unsigned int t) //STC89C52RC
{
while(t--);
}
//************************上面的代码需要自己写***********************//
void Write_DS18B20(unsigned char dat)
{
unsigned char i;
for(i=0;i<8;i++)
{
DQ = 0;
DQ = dat&0x01;
Delay_OneWire(5);
DQ = 1;
dat >>= 1;
}
Delay_OneWire(5);
}
unsigned char Read_DS18B20(void)
{
unsigned char i;
unsigned char dat;
for(i=0;i<8;i++)
{
DQ = 0;
dat >>= 1;
DQ = 1;
if(DQ)
{
dat |= 0x80;
}
Delay_OneWire(5);
}
return dat;
}
bit init_ds18b20(void)
{
bit initflag = 0;
DQ = 1;
Delay_OneWire(12);
DQ = 0;
Delay_OneWire(80);
DQ = 1;
Delay_OneWire(10);
initflag = DQ;
Delay_OneWire(5);
return initflag;
}
//************************下面的代码需要自己写***********************//
int rd_temprature()
{
unsigned char low,high;
unsigned int temp;
int temprature;
init_ds18b20();
Write_DS18B20(0xcc);
Write_DS18B20(0x44);
Delay_OneWire(200);
init_ds18b20();
Write_DS18B20(0xcc);
Write_DS18B20(0xbe);
low=Read_DS18B20();
high=Read_DS18B20();
temp=(low|(high<<8));
temprature=temp*0.625;// 保留小数位1位
return temprature;
}
//************************上面的代码需要自己写***********************//