DS18B20 基于STM32F103

  u8 DS18B20_Presence(void);// function declare


u8 DS18B20_Init(void)
{
GPIO_InitTypeDef GPPIO_Initstruce;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOG,ENABLE);

GPPIO_Initstruce.GPIO_Pin= GPIO_Pin_11;
GPPIO_Initstruce.GPIO_Mode= GPIO_Mode_Out_PP;
GPPIO_Initstruce.GPIO_Speed= GPIO_Speed_50MHz;
GPIO_Init(GPIOG,&GPPIO_Initstruce);
GPIO_SetBits(GPIOG,GPIO_Pin_11); //pull up high voltage ,chip edle
DS18B20_Reset();//Reset 

return DS18B20_Presence();

}


void DS18B20_Reset(void)
{
//DS18B20_OUT();//
DS18B20_OUT();
Mode_OUT =0;//pull low voltage 
delay_us(750);//delay 900 us 
Mode_OUT = 1;//Release DQ bus 
//DS18B20_IN();//relese DQ bus 

}

u8 DS18B20_Presence(void)
{
 u8 times = 0;
DS18B20_IN();//Input Mode 

while(Mode_IN && times <60)
{
times++;
delay_us(1);
}
if(times >=60)return 0;
times = 0;//
while(!Mode_IN &× <240)//keeping low voltage ,during 240 us 
{
times ++;
delay_us(1);//
}
if(times >=240)return 0;
//if(times <60 ||times >240)return 0;//fail  ,Testing DS18B20 times <60 is error!
//else 
return 1;//successfully

}


// First LSB
void DS18B20_WriteByte(u8 bytes)
{
u8 times = 0;
u8 temp = 0;

DS18B20_OUT();//output Mode 
//Mode_OUT = 1;//pull high voltage 
//delay_us();
for(;times<8;times++)
{
temp = (bytes & (0x01<if(temp)
{
Mode_OUT = 0;//
delay_us(2);
Mode_OUT = 1;// equal to relese Bus ?
//DS18B20_IN();
delay_us(60);
}
else 
{
Mode_OUT = 0;
delay_us(60);
Mode_OUT = 1;// equal to relese Bus ?
delay_us(2);
//DS18B20_IN();
}
}


}

u8 DS18B20_ReadBit(void)
{
u8 bit = 0;

DS18B20_OUT();
Mode_OUT = 0;
delay_us(2);
Mode_OUT = 1;
    DS18B20_IN();
delay_us(12);
if(Mode_IN)
{
bit = 1;
//return bit;
}
else 
{
 bit = 0;
//return bit; 
}
delay_us(50);
return bit; 
}


u8 DS18B20_ReadByte(void)
{
u8 times  = 0;
u8 bytes = 0;
u8 i;

for(i = 1;i<=8;i++)
{
times =DS18B20_ReadBit();
bytes = (times <<7)|(bytes >>1);
}

  return bytes ;
}




void DS18B20_ConvertTemperature(void)
{
DS18B20_Reset();
   //if()
DS18B20_Presence();

DS18B20_WriteByte (0XCC);
DS18B20_WriteByte (0X44);

}


void DS18B20_Read_Temperatrue(u8 *buffer)
{
u8 times = 0;
DS18B20_ConvertTemperature();
DS18B20_Reset();
//DS18B20_Presence();
DS18B20_Presence();

DS18B20_WriteByte(0XCC);//
DS18B20_WriteByte(0XBE);//
//*buffer  = DS18B20_ReadByte();//
for(;times<=8;times++)
{
*(buffer+times) = DS18B20_ReadByte();
//delay_us(1);
}
//return times;


}


float TemperatureVaule(u8 *buffer)
{
u16 vaule = 0;
u8 flag ;//
u8 times;
DS18B20_Read_Temperatrue(buffer);
// for(times=0;times<=8;times++)
// {
// //*(buffer+times) = DS18B20_Read_Temperatrue();
// }
//
//DS18B20_Read_Temperatrue(buffer);
if(buffer[1]&90)
{
vaule +=(u16)(buffer[1]&0x07 )<<8;
vaule += buffer[0];
flag = -1;
}
 else //if(buffer[1]&90)//postive voltage
{
flag = 1;
vaule += (((u16)buffer[1])&0x07)<<8;
vaule += buffer[0];
}
//*pVal =flag;
return (float)(flag*vaule *0.0625);
}

你可能感兴趣的:(DS18B20 基于STM32F103)