]> www.fi.muni.cz Git - bike-lights.git/blobdiff - firmware/main.c
main.c: split up the main() function
[bike-lights.git] / firmware / main.c
index a83884b86f9408101f9bbf3a2bc91fa010b7b1be..e6f03b01fafa1156aeb86cc01cb7da7eabc62f1c 100644 (file)
@@ -3,6 +3,7 @@
 #include <avr/sleep.h>
 #include <avr/interrupt.h>
 #include <avr/power.h>
+#include <avr/wdt.h>
 
 #include "lights.h"
 
@@ -23,7 +24,7 @@ static void hw_setup()
        set_sleep_mode(SLEEP_MODE_IDLE);
 }
 
-static void hw_suspend()
+static void inline hw_suspend()
 {
        susp_pwm();
        susp_adc();
@@ -33,11 +34,14 @@ static void hw_suspend()
        susp_buttons();
 }
 
-void power_down()
+void power_down(unsigned char err)
 {
        hw_suspend();
 
        do {
+               if (err)
+                       gpio_set(0, 1);
+
                // G'night
                set_sleep_mode(SLEEP_MODE_PWR_DOWN);
                sleep_enable();
@@ -56,9 +60,20 @@ void power_down()
        hw_setup();
 }
 
-int main(void)
+static void inline first_boot()
 {
-       init_log();
+       unsigned char mcusr_save;
+
+       // disable the WDT if running
+       wdt_reset();
+       mcusr_save = MCUSR;
+       MCUSR = 0;
+       wdt_disable();
+
+       if (mcusr_save & _BV(WDRF)) // was watchdog reset?
+               gpio_set(0, 1);
+
+       init_log(mcusr_save);
 
        power_usi_disable(); // Once for lifetime
        ACSRA |= _BV(ACD);   // disable analog comparator
@@ -66,27 +81,35 @@ int main(void)
        log_set_state(3);
 
        hw_setup();
-       power_down();
+       power_down(mcusr_save & _BV(WDRF));
 
        sei();
-#if 1
-       while (1) {
-               cli();
-               if (TIMER1_IS_ON()) {
-                       set_sleep_mode(SLEEP_MODE_IDLE);
-               } else if (adc_is_on) {
-                       set_sleep_mode(SLEEP_MODE_ADC);
-               } else {
-                       set_sleep_mode(SLEEP_MODE_PWR_DOWN);
-               }
+}
 
-               sleep_enable();
-               // keep BOD active, no sleep_bod_disable();
-               sei();
-               sleep_cpu();
-               sleep_disable();
+static void inline main_loop_iteration()
+{
+       cli();
+       if (TIMER1_IS_ON()) {
+               set_sleep_mode(SLEEP_MODE_IDLE);
+       } else if (adc_is_on) {
+               set_sleep_mode(SLEEP_MODE_ADC);
+       } else {
+               set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        }
-#endif
+
+       sleep_enable();
+       // keep BOD active, no sleep_bod_disable();
+       sei();
+       sleep_cpu();
+       sleep_disable();
+}
+
+int main(void)
+{
+       first_boot();
+
+       while (1)
+               main_loop_iteration();
 
 #if 0
        DDRB |= _BV(PB2);