stm32f407-openocd/Core/Src/temp_sensor/ds18b20.c

124 lines
2.7 KiB
C
Raw Permalink Normal View History

2024-06-13 08:01:47 +00:00
/**
* @ Author: Yifan Chen
* @ Create Time: 2024-06-13 09:04:07
* @ Modified by: Yifan Chen
* @ Modified time: 2024-06-13 15:03:03
* @ Description:
*/
#include "ds18b20.h"
#include <stdio.h>
extern void ds18b20_io_out(unsigned char ch);
extern void ds18b20_write(unsigned char ch, unsigned char value);
extern unsigned char ds18b20_read(unsigned char ch);
__attribute__((weak)) void delay_us(unsigned int us)
{
for (volatile int i = 0; i < us; i++)
{
for (volatile int j = 0; j < 13; j++)
{
;
}
}
}
/*
DS18B20写入数据
*/
void ds18b20_write_data(unsigned char ch, unsigned char byte)
{
unsigned char tempIndex, tempData;
// ds18b20_io_out(ch);
for (tempIndex = 1; tempIndex <= 8; tempIndex++)
{
tempData = (byte & 0x01);
byte >>= 1;
if (tempData == 1)
{
ds18b20_write(ch, 0); // 低电平
delay_us(2);
ds18b20_write(ch, 1); // 高电平
delay_us(60); // 延时60us
}
else
{
ds18b20_write(ch, 0); // 低电平
delay_us(60); // 延时60us
ds18b20_write(ch, 1); // 高电平
delay_us(2);
}
}
}
/*
DS18B20一位数据
*/
unsigned char ds18b20_read_bit(unsigned char ch)
{
unsigned char data = 0;
ds18b20_write(ch, 0); // 低电平
delay_us(2);
ds18b20_write(ch, 1); // 高电平
delay_us(15);
data = ds18b20_read(ch);
// ds18b20_io_out(ch); // 设置为输出
ds18b20_write(ch, 1); // 高电平
delay_us(45);
return data;
}
/*
DS18B20的数据
*/
unsigned char ds18b20_read_data(unsigned char ch)
{
unsigned char i, j, data = 0;
for (i = 1; i <= 8; i++)
{
j = ds18b20_read_bit(ch);
data = (j << 7) | (data >> 1);
}
return data;
}
/**
* return 0 : rst success return 1 : rst failure
*/
char ds18b20_rst(unsigned char io)
{
// ds18b20_io_out(io);
ds18b20_write(io, 0);
delay_us(480);
ds18b20_write(io, 1);
delay_us(120);
unsigned char val = ds18b20_read(io);
// ds18b20_io_out(io);
ds18b20_write(io, 1);
delay_us(360);
return val;
}
float ds18b20_read_temp(unsigned char ch)
{
unsigned short temp = 0;
ds18b20_rst(ch);
ds18b20_write_data(ch, 0xcc);
ds18b20_write_data(ch, 0xbe);
delay_us(1000);
temp = ds18b20_read_data(ch);
temp |= (ds18b20_read_data(ch) << 8);
float temp_f = 0.0625 * (float)temp;
return temp_f;
}
void ds18b20_start_convert(unsigned char ch)
{
ds18b20_rst(ch);
ds18b20_write_data(ch, 0xcc);
ds18b20_write_data(ch, 0x44);
}
void ds18b20_io_init(unsigned char ch)
{
ds18b20_io_out(ch);
ds18b20_write(ch, 1);
}