From a39605248760a1acdb6850ef9e7f289bee7cb6fd Mon Sep 17 00:00:00 2001 From: Markus Koch Date: Fri, 31 Jul 2020 18:23:58 +0200 Subject: [PATCH] fw: Implement power-on battery check --- firmware/batmon.c | 25 +++++++++++++++++++++++++ firmware/batmon.h | 1 + firmware/main.c | 1 + firmware/pm.c | 6 +++++- 4 files changed, 32 insertions(+), 1 deletion(-) diff --git a/firmware/batmon.c b/firmware/batmon.c index c70e9ca..f1a150f 100644 --- a/firmware/batmon.c +++ b/firmware/batmon.c @@ -49,3 +49,28 @@ inline uint8_t batmon_get_voltage() { return vbat; } + +static uint8_t batmon_get_voltage_sync() +{ + uint16_t sum = 0; + uint8_t cnt = 255; + + ADCSRA |= (1 << ADSC); + + do { + if (ADCSRA & (1 << ADIF)) { + sum += ADCH; + ADCSRA &= ~(1 << ADIF); + ADCSRA |= (1 << ADSC); + cnt--; + } + } while (cnt); + + return (sum >> 8); +} + +// Note: Call batmon_init() after using this function before using batmon_proc() again +inline uint8_t batmon_ok_to_boot() +{ + return (batmon_get_voltage_sync() > BAT_THRES_POWER_ON); +} diff --git a/firmware/batmon.h b/firmware/batmon.h index fd5976f..7acc2b5 100644 --- a/firmware/batmon.h +++ b/firmware/batmon.h @@ -12,5 +12,6 @@ void batmon_init(); uint8_t batmon_get_voltage(); uint8_t batmon_proc(); +uint8_t batmon_ok_to_boot(); #endif // BATMON_H diff --git a/firmware/main.c b/firmware/main.c index 8c94a35..afafecd 100644 --- a/firmware/main.c +++ b/firmware/main.c @@ -88,6 +88,7 @@ int main() MCUSR &= ~(1 << WDRF); WDTCSR = (1 << WDCE); cli(); + _delay_ms(25); suspend(); diff --git a/firmware/pm.c b/firmware/pm.c index c81a535..dc4af6f 100644 --- a/firmware/pm.c +++ b/firmware/pm.c @@ -4,6 +4,7 @@ #include #include #include "pm.h" +#include "batmon.h" static void disable_periphery() { @@ -58,7 +59,10 @@ void reset() char* post() { - // TODO: Implement battery voltage check _delay_ms(500); + + if (!batmon_ok_to_boot()) + return PSTR("Low battery."); + return 0; }