18b20测量温度-lpc1114

  • 学习5094次
#include "ds18b20.h"
uint8_t temp_sign;
void delay_ds(uint16_t zz)
{
 uint8_t xx;
 uint16_t yy; 
 
 for(xx=0;xx<1;xx++)
 for(yy=0;yy<zz;yy++);
}
void DS18B20_Rst(void) 
{ 
 LPC_GPIO3->DIR|=(1<<5); 
 DQ_LOW;
 delay_ds(500); //主机拉低总线,520us(480~960uS)
 DQ_HIGH;
 delay_ds(70); //释放总线,(15~60uS)
}
uint8_t DS18B20_Check(void) 
{ 
 uint8_t retry=0;
 
 LPC_GPIO3->DIR&=~(1<<5); // 设置P3.5引脚为输入引脚 
 while(DQ_UP&&retry<200)
 {
 retry++;
 delay_ds(1);
 }; 
 if(retry>=200)return 1;
 else retry=0;
 while(DQ_DOWN&&retry<250)
 {
 retry++;
 delay_ds(1);
 };
 if(retry>=250)return 1; 
 return 0;
}
uint8_t DS18B20_Init(void)
{
 LPC_GPIO3->DIR|=(1<<5); // P3.5为输出,用作DS18B20数据引脚
 LPC_GPIO3->DATA|=(1<<5); // P3.5置高
 DS18B20_Rst();
 return DS18B20_Check();
}
void DS18B20_Write_Byte(uint8_t dat) 
{ 
 uint8_t j;
 uint8_t testb;
 LPC_GPIO3->DIR|=(1<<5); 
 for(j=1;j<=8;j++) 
 {
 testb=dat&0x01;
 dat=dat>>1;
 if (testb) 
 {
 DQ_LOW;// Write 1
 delay_ds(2); 
 DQ_HIGH;
 delay_ds(60); 
 }
 else 
 {
 DQ_LOW;// Write 0
 delay_ds(60); 
 DQ_HIGH;
 delay_ds(2); 
 }
 }
}
void DS18B20_Start(void)// ds1820 start convert
{ 
 DS18B20_Rst(); 
 DS18B20_Check(); 
 DS18B20_Write_Byte(0xcc);// skip rom
 DS18B20_Write_Byte(0x44);// convert
}
uint8_t DS18B20_Read_Bit(void) // read one bit
{
 uint8_t data;
 
 LPC_GPIO3->DIR|=(1<<5); 
 DQ_LOW; 
 delay_ds(2);
 DQ_HIGH; 
 LPC_GPIO3->DIR&=~(1<<5);//SET PG11 INPUT
 delay_ds(12);
 if(DQ_UP)data=1;
 else data=0; 
 delay_ds(50); 
 return data;
}
uint8_t DS18B20_Read_Byte(void) // read one byte
{ 
 uint8_t i,j,dat;
 
 dat=0;
 for(i=1;i<=8;i++) 
 {
 j=DS18B20_Read_Bit();
 dat=(j<<7)|(dat>>1);
 } 
 return dat;
}
// 返回值是十六位的温度值,精度1% 00.0
int16_t DS18B20_Get_Temp(void)
{
 uint8_t TL,TH;
 int16_t tem;
 DS18B20_Start(); // ds1820 start convert
 DS18B20_Rst();
 DS18B20_Check(); 
 DS18B20_Write_Byte(0xcc);// skip rom
 DS18B20_Write_Byte(0xbe);// convert 
 TL=DS18B20_Read_Byte(); // LSB 
 TH=DS18B20_Read_Byte(); // MSB 
 
 if(TH>7)
 {
 TH=~TH;
 TL=~TL; 
 temp_sign=0;
 }else temp_sign=1; 
 tem=TH; 
 tem<<=8; 
 tem+=TL;
 tem=(float)tem*0.625; 
 if(temp_sign)return tem;
 else return -tem; 
}

KEIL工程:

LPC1114-DS18B20源码