From 43b2e3a4a5042709e69f58b8b39b72a572d8ebba Mon Sep 17 00:00:00 2001 From: Gediminas Jakutis Date: Thu, 8 Feb 2018 23:37:19 +0200 Subject: tempmodule: add the logic to calculate voltages and temps. --- src/tempmodule/main.ino | 65 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) (limited to 'src/tempmodule/main.ino') diff --git a/src/tempmodule/main.ino b/src/tempmodule/main.ino index f295d40..58f749a 100644 --- a/src/tempmodule/main.ino +++ b/src/tempmodule/main.ino @@ -23,6 +23,12 @@ #include #include #include +#include + +struct temptuple { + short res; /* Resistance in ohms. */ + short temp; /* Temperatures in 0.1°K. */ +}; static const unsigned int iled = 2; static const unsigned int analog = A0; @@ -41,6 +47,9 @@ static void mpu_wakeup(const int i2caddr); static void wifi_connect(const char * const ssid, const char * const password, const char doblink, const int ledpin); static void blink_led(const int pin, const int ontime, const int offtime); static void discover_client(void); +static int get_resistance(int64_t vt, int64_t ra); +static int get_temperature(int res); +static int get_temp_subrange(short a, short b, int res); void setup(void) { @@ -173,3 +182,59 @@ static void discover_client(void) delay(95); } while (!done); } + +/* + * formula by applying Ohms law: + * + * Rt: Thermistor resistance + * Ra: Voltage divider resistor + * Vt: Tap voltage + * Vcc: Input Voltage (3.3V) + * + * Rt = Ra * Vcc / Vt - Ra + * + * Using 64-bit arithmetic as 32-bit would overflow. + * On WeMOS D1 Mini the A0 reads 3.3V as 1023, that is our Vcc. + * We shift the range by one to avoid division by zero. + */ +static int get_resistance(int64_t vt, int64_t ra) +{ + ++vt; + return ra * 1024 / vt - ra; +} + +static int get_temperature(int res) +{ + int ret; + size_t i; + static const struct temptuple lt[] = { + {1452, 2630}, {1613, 2730}, {1754, 2830}, {1903, 2930}, + {2059, 3030}, {2222, 3130}, {2393, 3230}, {2571, 3330}, + {2757, 3430}, {2950, 3530}, {3150, 3630}, {3358, 3730}, + {3571, 3830}}; + + for (i = 0; i < 9; ++i) { + /* If we have a matching resistance, nothing to calculate. */ + if (res == lt[i].res) { + ret = lt[i].temp; + break; + } else if (res == lt[i + 1].res) { + ret = lt[i + 1].temp; + break; + /* If no matching resistance is found, calculate temp from subrange. */ + } else if (res > lt[i].res && res < lt[i + 1].res) { + ret = lt[i].temp + get_temp_subrange(lt[i].res, lt[i + 1].res, res); + break + } + + return ret; + } + + return -1; +} + +/* Returns the last 0-10 part of the temperature, in 0.1°K. */ +static int get_temp_subrange(short a, short b, int res) +{ + return (res - a.res) * 100 / (b.res - a.res); +} -- cgit v1.2.3