用245驱动DS18B20的程序
发布网友
发布时间:2022-07-20 03:16
我来回答
共1个回答
热心网友
时间:2023-10-18 20:18
//本人亲自调试过,包你没问题
//外部晶振11.0592M
#include<stc12c5a60s2.h>
bit B20DIRCTR=P3^7; //245方向控制端 H=A->B,L=B->A
sbit DQ=P2^7; //DS18B20数据口
void DS18B20_delayms(unsigned int z)
{
unsigned int x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void DS18B20_delayus(unsigned int us)
{
while(--us);
}
/*-------------------------
*****DS18B20 operation*****
-------------------------*/
/*initialization*/
bit DS18B20_reset()
{
bit presence=0;
B20DIRCTR=1;
DQ=1;
DS18B20_delayus(10);
DQ=0;
DS18B20_delayus(500);
DQ=1;
DS18B20_delayus(60);
B20DIRCTR=0;
DS18B20_delayus(2);
if(DQ)
presence=0;
else
presence=1;
B20DIRCTR=1;
return presence;
}
#if 0
/*read a bit*/
bit DS18B20_readbit()
{
bit dat;
B20DIRCTR=1;
DQ=0;
DS18B20_delayus(1);
DQ=1;
DS18B20_delayus(5);
B20DIRCTR=0;
dat=DQ;
DS18B20_delayus(100);
B20DIRCTR=1;
return dat;
}
/*read byte*/
unsigned char DS18B20_readbyte()
{
unsigned char i,j,dat;
dat=0;
for(i=0;i<8;i++)
{
j=DS18B20_readbit(); //The lowest bit at front
dat=(j<<7)|(dat>>1); //The positive preface arranges a word knot potential
}
return dat;
}
#endif
unsigned char DS18B20_readbyte()
{
unsigned char i,temp;
for(i=1;i<=8;i++)
{
temp>>=1;
B20DIRCTR=1;
DQ=0;
DS18B20_delayus(1);
DQ=1;
B20DIRCTR=0;
if(DQ)
temp|=0x80;
DS18B20_delayus(45);
}
B20DIRCTR=1;
return temp;
}
/*write byte*/
void DS18B20_writebyte(unsigned char dat)
{
unsigned char j;
// B20DIRCTR=1;
DQ=1;
for(j=1;j<=8;j++)
{
DQ=0;
DS18B20_delayus(10);
if(dat&0x01)
DQ=1;
else
DQ=0;
DS18B20_delayus(40);
DQ=1;
DS18B20_delayus(1);
dat>>=1; //right move a bit
}
}
/*read scratchpad,return actual temperature*/
int DS18B20_gettemp()
{
float f_temp;
int temp;
unsigned char hdata=0,ldata=0;
/*change temperature*/
if(!DS18B20_reset()) //DS18B20 reset function
return;
DS18B20_delayms(1); //need delay 1ms
DS18B20_writebyte(0xcc); //skip ROM command
DS18B20_writebyte(0x44); //start convertion temperature command
DS18B20_delayms(5000); //上电转换需要延时足够长时间,否则会读出默认值85
if(!DS18B20_reset()) //DS18B20 reset function
return;
DS18B20_delayms(1);
DS18B20_writebyte(0xcc); //skip ROM command
DS18B20_writebyte(0xbe); //read Scratchpad command
ldata=DS18B20_readbyte(); //read high byte
hdata=DS18B20_readbyte(); //read low byte
temp=hdata;
temp<<=8; //high byte left move eight bit
temp=temp|ldata; //high byte and low byte OR
f_temp=temp*0.0625; //multiplicative precision
temp=f_temp*10+(temp>0 ? 0.5 : -0.5);
// f_temp+=0.05;
if(temp==0xffff)
return 0;
return temp;
}void main()
{
unsigned int i;
int Temp_T1=0;
LCD1602_Init(); //液晶初始化
while(1)
{
Temp_T1=DS18B20_gettemp(); //读温度值
Ttable[0]=Temp_T1/100%10+0x30;
Ttable[1]=Temp_T1%100/10+0x30;
Ttable[2]='.';
Ttable[3]=Temp_T1%10+0x30;
Ttable[4]='C'; //温度单位
Ttable[5]='\0';
LCD1602_Write_Str(0,0,Ttable); //液晶显示温度值
}
}