From 9d87c925a9eaa4fc256be3173c14a20d1469472d Mon Sep 17 00:00:00 2001 From: fishsoupisgood Date: Wed, 9 Sep 2020 11:53:37 +0100 Subject: everything, mostly, working --- radiator-plc/stm32/app/ds18b20.c | 128 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 radiator-plc/stm32/app/ds18b20.c (limited to 'radiator-plc/stm32/app/ds18b20.c') diff --git a/radiator-plc/stm32/app/ds18b20.c b/radiator-plc/stm32/app/ds18b20.c new file mode 100644 index 0000000..3bd63ed --- /dev/null +++ b/radiator-plc/stm32/app/ds18b20.c @@ -0,0 +1,128 @@ +#include "project.h" + +#define DS18B20_CONVERT 0x44 +#define DS18B20_WRITE_SCRATCHPAD 0x4e +#define DS18B20_READ_SCRATCHPAD 0xbe + + +#define TIMEOUT 150 + + +unsigned extract_leu16 (uint8_t *d) +{ + uint32_t u; + + u = (uint32_t) d[0] | (((uint32_t) d[1]) << 8); + return u; +} + + +int extract_les16 (uint8_t *d) +{ + uint32_t u; + u = extract_leu16 (d); + + if (u & 0x8000) u |= 0xffff0000; + + return (int) u; +} + + +/* do not call from interrupt context (ie ticker)*/ +int +ds18b20_read_sp (const Onewire_addr *a, uint8_t *buf, unsigned len) +{ + if (onewire_reset_and_select (a)) + return ~0U; + + onewire_write_byte (DS18B20_READ_SCRATCHPAD); + onewire_read_bytes (buf, len); + + + if ((len == 9) && onewire_check_crc (buf, 8, buf[8])) + return ~0U; + + return 0; +} + +int +ds18b20_write_sp (const Onewire_addr *a, uint8_t *buf, unsigned len) +{ + if (onewire_reset_and_select (a)) + return ~0U; + + onewire_write_byte (DS18B20_WRITE_SCRATCHPAD); + onewire_write_bytes (buf, len); + + return 0; +} + +int ds18b20_convert (const Onewire_addr *a, unsigned timeout) +{ + + if (onewire_reset_and_select (a)) + return ~0U; + + onewire_write_byte (DS18B20_CONVERT); + + if (timeout && onewire_wait_complete (timeout)) + return ~0U; + + return 0; +} + +int +ds18b20_set_12 (const Onewire_addr *a) +{ + uint8_t buf[9]; + + + if (ds18b20_read_sp (a, buf, 9)) + return 1; + + buf[0] = 0x0; + buf[1] = 0x0; + buf[2] = 0x7f; /* 12 bit conversions */ + + return ds18b20_write_sp (a, buf, 3); + +} + +int ds18b20_read (const Onewire_addr *a, int *temp) +{ + uint8_t buf[9]; + + if (ds18b20_read_sp (a, buf, 9)) + return 1; + + *temp = (extract_les16 (buf) * 500) >> 3; + return 0; +} + + +int +ds18b20_set_12_convert (const Onewire_addr *a) +{ + + if (ds18b20_set_12 (a)) + return 1; + + if (ds18b20_convert (a, 0)) + return 1; + + return 0; +} + +/* do not call from interrupt context (ie ticker)*/ +int +ds18b20_set_12_convert_and_read (const Onewire_addr *a, int *temp) +{ + if (ds18b20_set_12 (a)) + return 1; + + if (ds18b20_convert (a, TIMEOUT)) + return 1; + + return ds18b20_read (a, temp); +} + -- cgit v1.2.3