#include "Arduino. h"
#define ONEWIRE_PIN PA2
static uint8_t ds18b20_read_byte (void)
{
uint8_t i, j, dat;
dat = 0;
for (i = 1; i = 8; i++)
{
j = ds18b20_read_bit () ;
dat = (j 7) | dat 1;
}
return dat;
}
static uint8_t ds18b20_read_bit (void)
{
pinMode (ONEWIRE_PIN, OUTPUT) ;
uint8_t result;
digitalWrite (ONEWIRE_PIN, LOW) ;
delayMicroseconds (2) ;
digitalWrite (ONEWIRE_PIN, HIGH) ;
delayMicroseconds (12) ;
pinMode (ONEWIRE_PIN, INPUT) ;
if (digitalRead (ONEWIRE_PIN) )
{
result = 1;
}
else
{
result = 0;
}
delayMicroseconds (50) ;
return result;
}
static void ds18b20_write_byte (uint8_t byte)
{
uint8_t i;
uint8_t first_bit;
pinMode (ONEWIRE_PIN, OUTPUT) ;
for (i = 1; i = 8; i++)
{
first_bit = byte & 0x01;
byte = byte 1;
if (first_bit)
{ // write 1
digitalWrite (ONEWIRE_PIN, LOW) ;
delayMicroseconds (2) ;
digitalWrite (ONEWIRE_PIN, HIGH) ;
delayMicroseconds (60) ;
}
else
{ // write 0
digitalWrite (ONEWIRE_PIN, LOW) ;
delayMicroseconds (60) ;
digitalWrite (ONEWIRE_PIN, HIGH) ;
delayMicroseconds (2) ;
}
}
}
/*******************************************************************************
* @biref Detected presence signal
* @retval result [1: inexistence, 0: existence]
*******************************************************************************
*/
static uint8_t ds18b20_check (void)
{
uint8_t result = 1;
uint8_t retry = 0;
pinMode (ONEWIRE_PIN, INPUT) ;
//If the presence of a signal is not detected (always high)
and it does not exceed 200 us, the loop is executed.
while (digitalRead (ONEWIRE_PIN) && retry 200)
{
retry++;
delayMicroseconds (1) ;
}
// If the retry exceeds 200, the DS18B20 does not exist.
if (retry = 200)
{
result = 1;
}
else
{
retry = 0;
while (! digitalRead (ONEWIRE_PIN) && retry 240)
{
retry++;
delayMicroseconds (1) ;
}
if (retry = 240)
{
result = 1;
}
else
{
result = 0;
}
}
// Serial. printf ("check: %d\n", result) ; To detect if there is a response.
return result;
}
static void ds18b20_rst (void)
{
pinMode (ONEWIRE_PIN, OUTPUT) ;
digitalWrite (ONEWIRE_PIN, LOW) ;
delayMicroseconds (750) ;
digitalWrite (ONEWIRE_PIN, HIGH) ;
delayMicroseconds (15) ; // 15us
}
float ds18b20_get_temp (void)
{
uint8_t temp;
uint8_t TL, TH;
short tem;
ds18b20_start () ;
ds18b20_rst () ;
ds18b20_check () ;
ds18b20_write_byte (0xcc) ;
ds18b20_write_byte (0xbe) ;
// Read the signal from the DS18B20 sensor.
TL = ds18b20_read_byte () ; // LSB
TH = ds18b20_read_byte () ; // MSB
if (TH 7)
{
TH = ~TH;
TL = ~TL;
temp = 0;
}
else
{
temp = 1;
}
tem = TH;
tem = 8;
tem += TL;
return (float) tem * 0. 0625;
}
static void ds18b20_start (void) // ds1820 start convert
{
ds18b20_rst () ;
ds18b20_check () ;
ds18b20_write_byte (0xcc) ; // skip rom
ds18b20_write_byte (0x44) ; // convert
}
void setup ()
{
Serial. begin (115200) ;
}
void loop ()
{
float control = ds18b20_get_temp () ;
Serial. printf ("temp: %f\n", control) ;
delay (1000) ;
}