X-Git-Url: https://www.fi.muni.cz/~kas/git//home/kas/public_html/git/?p=bike-lights.git;a=blobdiff_plain;f=firmware%2Fmain.c;h=b3fcc654099c4adacf9dd0262dd6d18066e53499;hp=0fbdb1e9f804421fca1a07fe69f33d72bd0890a2;hb=02c4abfe1e23e2766971fa9616cc3e5396b9744f;hpb=a366ae18debc6e73c4946aa6290ed37c49bb1fc0 diff --git a/firmware/main.c b/firmware/main.c index 0fbdb1e..b3fcc65 100644 --- a/firmware/main.c +++ b/firmware/main.c @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -7,6 +8,8 @@ #include "lights.h" +static unsigned char prev_jiffies_8; + static void hw_setup() { init_battery(); @@ -24,7 +27,7 @@ static void hw_setup() set_sleep_mode(SLEEP_MODE_IDLE); } -static void hw_suspend() +static void inline hw_suspend() { susp_pwm(); susp_adc(); @@ -60,7 +63,7 @@ void power_down(unsigned char err) hw_setup(); } -int main(void) +static void inline first_boot() { unsigned char mcusr_save; @@ -83,25 +86,76 @@ int main(void) hw_setup(); power_down(mcusr_save & _BV(WDRF)); + prev_jiffies_8 = jiffies; + 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); +} + +static void inline do_timer() +{ + // For now, we run them all in their own atomic blocks + ATOMIC_BLOCK(ATOMIC_FORCEON) { + timer_check_buttons(); + } + ATOMIC_BLOCK(ATOMIC_FORCEON) { + patterns_next_tick(); + } + ATOMIC_BLOCK(ATOMIC_FORCEON) { + pwm_disable_if_not_needed(); + } + ATOMIC_BLOCK(ATOMIC_FORCEON) { + timer_start_slow_adcs(); + } + ATOMIC_BLOCK(ATOMIC_FORCEON) { + if ((jiffies & 0x7FF) == 0) + ambient_log_min_max(); + } +} + +static void inline main_loop_iteration() +{ + unsigned char jiffies_8; /* + * we use only lower 8-bits in order to + * avoid the need for locking of 16-bit + * accesses. + */ + + 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(); + + jiffies_8 = jiffies; + + if (jiffies_8 != prev_jiffies_8) { // was timer IRQ + if (jiffies_8 - prev_jiffies_8 > 1) { // overrun + log_byte(0xee); + log_byte(jiffies_8 - prev_jiffies_8); + log_flush(); } - sleep_enable(); - // keep BOD active, no sleep_bod_disable(); - sei(); - sleep_cpu(); - sleep_disable(); + prev_jiffies_8 = jiffies_8; + + do_timer(); } -#endif +} + +int main(void) +{ + first_boot(); + + while (1) + main_loop_iteration(); #if 0 DDRB |= _BV(PB2);