#include"ds18b20.h"
uint8_ttemp_sign;
voiddelay_ds(uint16_tzz){uint8_txx;uint16_tyy;for(xx=0;xx<1;xx++)for(yy=0;yyvoidDS18B20_Rst(void){LPC_GPIO3->DIR|=(1<<5);DQ_LOW;delay_ds(500);//主機(jī)拉低總線,520us(480~960uS)DQ_HIGH;delay_ds(70);//釋放總線,(15~60uS)}
uint8_tDS18B20_Check(void){uint8_tretry=0;LPC_GPIO3->DIR&=~(1<<5);//設(shè)置P3.5引腳為輸入引腳while(DQ_UP&&retry<200){retry++;delay_ds(1);};if(retry>=200)return1;elseretry=0;while(DQ_DOWN&&retry<250){retry++;delay_ds(1);};if(retry>=250)return1;return0;}
uint8_tDS18B20_Init(void){LPC_GPIO3->DIR|=(1<<5);//P3.5為輸出,用作DS18B20數(shù)據(jù)引腳LPC_GPIO3->DATA|=(1<<5);//P3.5置高DS18B20_Rst();returnDS18B20_Check();}
voidDS18B20_Write_Byte(uint8_tdat){uint8_tj;uint8_ttestb;LPC_GPIO3->DIR|=(1<<5);for(j=1;j<=8;j++){testb=dat&0x01;dat=dat>>1;if(testb){DQ_LOW;//Write1delay_ds(2);DQ_HIGH;delay_ds(60);}else{DQ_LOW;//Write0delay_ds(60);DQ_HIGH;delay_ds(2);}}}
voidDS18B20_Start(void)//ds1820startconvert{DS18B20_Rst();DS18B20_Check();DS18B20_Write_Byte(0xcc);//skipromDS18B20_Write_Byte(0x44);//convert}
uint8_tDS18B20_Read_Bit(void)//readonebit{uint8_tdata;LPC_GPIO3->DIR|=(1<<5);DQ_LOW;delay_ds(2);DQ_HIGH;LPC_GPIO3->DIR&=~(1<<5);//SETPG11INPUTdelay_ds(12);if(DQ_UP)data=1;elsedata=0;delay_ds(50);returndata;}
uint8_tDS18B20_Read_Byte(void)//readonebyte{uint8_ti,j,dat;dat=0;for(i=1;i<=8;i++){j=DS18B20_Read_Bit();dat=(j<<7)|(dat>>1);}returndat;}
//返回值是十六位的溫度值,精度1%00.0int16_tDS18B20_Get_Temp(void){uint8_tTL,TH;int16_ttem;DS18B20_Start();//ds1820startconvertDS18B20_Rst();DS18B20_Check();DS18B20_Write_Byte(0xcc);//skipromDS18B20_Write_Byte(0xbe);//convertTL=DS18B20_Read_Byte();//LSBTH=DS18B20_Read_Byte();//MSBif(TH>7){TH=~TH;TL=~TL;temp_sign=0;}elsetemp_sign=1;tem=TH;tem<<=8;tem+=TL;tem=(float)tem*0.625;if(temp_sign)returntem;elsereturn-tem;}