stm32 驱动DS18B20温度传感器

来源:互联网 发布:淘宝上回收电脑靠谱吗 编辑:程序博客网 时间:2024/05/16 15:08
#include "temp.h"


#define u8 uint8_t
#define u16 uint16_t
#define u32 uint32_t


#define DS18B20_PORT GPIOA
#define DS18B20_PIN     GPIO_Pin_1                  
#define DS18B20_CLK     RCC_APB2Periph_GPIOA

#define RW1820_DQ_HIGH           GPIO_SetBits(DS18B20_PORT, DS18B20_PIN);
#define RW1820_DQ_LOW           GPIO_ResetBits(DS18B20_PORT, DS18B20_PIN);  

#define RW1820_DQ_VALUE GPIO_ReadInputDataBit(DS18B20_PORT,DS18B20_PIN)


//---------------------------------------------------------------------------//
void _delay_us(uint16_t nCount)
{
    nCount *= 3; 
    while(--nCount);
}
//-----------------------------------------------------------------------------//
static void RW1820_DQ_IN(void)
{
   GPIO_InitTypeDef GPIO_InitStructure;
  RCC_APB2PeriphClockCmd(DS18B20_CLK, ENABLE);
 GPIO_InitStructure.GPIO_Pin = DS18B20_PIN;
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
 GPIO_Init(DS18B20_PORT, &GPIO_InitStructure);
}
//--------------------------------------------------------
static void RW1820_DQ_OUT(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(DS18B20_CLK, ENABLE);
GPIO_InitStructure.GPIO_Pin = DS18B20_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(DS18B20_PORT, &GPIO_InitStructure);
}
//--------------------------------------------------------
void RW1820_Init(void)
{
u8 retry=0;
RW1820_DQ_OUT();
RW1820_DQ_HIGH; 
_delay_us(50);
RW1820_DQ_LOW;  

_delay_us(500); //480 - 960
  RW1820_DQ_HIGH; 

_delay_us(40);//15-60
RW1820_DQ_IN(); //
while(RW1820_DQ_VALUE==1&& (retry<100))
{
retry++;
_delay_us(10);
}
RW1820_DQ_OUT();
RW1820_DQ_HIGH;
_delay_us(400);
}
//-------------
void RW1820_WriteByte(unsigned char _data)
{
int i = 0;
RW1820_DQ_OUT();
_delay_us(10);
for (i = 0; i < 8; i++)
{
RW1820_DQ_LOW;          //
_delay_us(2);           //
if (_data & 0x01)
{
RW1820_DQ_HIGH;     //
}
else RW1820_DQ_LOW;
_delay_us(60);          //60
RW1820_DQ_HIGH;
_data = _data >> 1;
}
}
//-------------
unsigned char RW1820_ReadByte(void)
{
int i = 0, _data = 0;
_delay_us(10);
for (i = 0; i < 8; i++)
{
RW1820_DQ_OUT();
RW1820_DQ_LOW;  
_data >>= 1;
_delay_us(2);   
RW1820_DQ_HIGH; 
RW1820_DQ_IN(); 
if(RW1820_DQ_VALUE)
{
_data |= 0x80;
}
_delay_us(60);  //60us
}
return _data;
}

int RW1820_ReadTemperature(void)
{
unsigned char temp;
unsigned int t;

RW1820_Init();         //
RW1820_WriteByte(0xcc);//
RW1820_WriteByte(0x44);//
_delay_us(10);
RW1820_Init();
RW1820_WriteByte(0xcc);//
RW1820_WriteByte(0xbe);//

temp = RW1820_ReadByte();
t = (int)(((temp & 0xf0) >> 4) + (temp & 0x07) * 0.125); 
temp = RW1820_ReadByte();
t += ((temp & 0x0f) << 4);

return t;
}
原创粉丝点击