]> www.fi.muni.cz Git - heater.git/blobdiff - firmware/main.c
Low battery bugfix:
[heater.git] / firmware / main.c
index 78777866d1f88354bccdc2c2e68f21a1cf2132a2..65801e81b05fd74192238c0d9892c2d87c9c0b24 100644 (file)
+/*
+ * OVERVIEW
+ *
+ * Powering up:
+ * Immediately after reset, we power down the entire system.
+ * We wake up only after the button is pressed for a sufficiently long time.
+ *
+ * Heater output:
+ * The heater output is driven by Timer/Counter 1 in PWM mode.
+ * We want to be able to measure the battery voltage both when the
+ * output is on, and when the output is off. So we set the T/C1 clock
+ * prescaler so that the T/C1 is slow enough, we enable the T/C1 interrupts
+ * both on compare match and on overflow. After the interrupt, we trigger
+ * the battery voltage measurement with ADC.
+ *
+ * ADC:
+ * To avoid transients, we measure each battery state (when the heater is on
+ * and when it is off) separately, and we drop the first few readings.
+ * We calculate a running average of the readings to achieve higher accuracy.
+ *
+ * Buttons:
+ * There are two buttons (+ and -). Any button can wake the system up from
+ * the power-down state.
+ * When running, the "-" button is used for decreasing the output power,
+ * the "+" button is for increasing it.
+ * Any long button press switches the system off.
+ *
+ * Status LED:
+ * When powering up by a button press, the LED goes on to provide a visual
+ * feedback, and is switched off after the button is released.
+ * It displays the current power level and current battery voltage
+ * using # of blinks with different blinking lengths.
+ * When the battery is completely exhausted, the output power is switched
+ * off, the LED keeps blinking for some time, and then the whole system is
+ * switched off to avoid deep discharge of the battery.
+ *
+ * Timing:
+ * The firmware is timed by the Watchdog Timer interrupt. Most of the
+ * processing is done from the main loop, IRQs only set various flags
+ * or trigger other events.
+ */
+
+#include <avr/interrupt.h>
 #include <avr/io.h>
+#include <avr/power.h>
+#include <avr/sleep.h>
+#include <avr/wdt.h>
 #include <util/delay.h>
 
 #include "logging.h"
 
-int main()
+/* waking up from the power down state by a button press */
+#define WAKEUP_POLL 50 // msec
+#define WAKEUP_LIMIT 5 // times WAKEUP_POLL
+
+// #define BUTTONS_REVERSE
+
+#ifdef BUTTONS_REVERSE
+#      define BUTTON1  PB0
+#      define BUTTON2  PB1
+#else
+#      define BUTTON1  PB1
+#      define BUTTON2  PB0
+#endif /* !BUTTONS_REVERSE */
+
+/* which state (output on or output off) are we measuring now */
+static volatile unsigned char adc_type, adc_drop;
+#define ADC_RUNAVG_SHIFT 5     // running average shift on batt_on, batt_off
+static volatile uint16_t batt_on, batt_off; // measured voltage
+
+/*
+ * The voltage divider has 1M5 and 300K resistors (i.e. it measures 1/6th of
+ * the real voltage), ADC uses 1.1V internal reference.
+ * Macro to calculate upper eight bits of the ADC running-averaged value
+ * from the voltage in milivolts.
+ */
+#define ADC_1100MV_VALUE       1071    // measured, not exactly 1100
+#define MV_TO_ADC8(mV) ((unsigned char)(((uint32_t)(1UL << ADC_RUNAVG_SHIFT) \
+                               * (1024UL * (mV)) \
+                               / (6UL * ADC_1100MV_VALUE)) >> 8))
+static unsigned char batt_levels[] = {
+       MV_TO_ADC8(3000), // below this, do not enable load, and switch off
+       MV_TO_ADC8(3150), // below this, switch off after some time
+       MV_TO_ADC8(3450), // battery low
+       MV_TO_ADC8(3800), // battery ok, above that almost full
+};
+#define BATT_N_LEVELS  (sizeof(batt_levels) / sizeof(batt_levels[0]))
+
+/* output power and PWM calculation */
+#define PWM_TOP        255
+#define PWM_MAX        (PWM_TOP - 8)   // to allow for ADC "batt_off" measurements
+#define PWM_MIN        8               // to allow for ADC "batt_on" measurements
+
+/*
+ * The values in power_levels[] array are voltages at which the load
+ * would give the expected power (we don't have sqrt() function,
+ * so we cannot use mW values directly. They can be calculated as
+ * voltage[V] = sqrt(load_resistance[Ohm] * expected_power[W])
+ * or
+ * voltage[mV] = sqrt(load_resistance[mOhm] * expected_power[mW])
+ *
+ * I use 1.25 W as minimum power, each step is sqrt(2)*previous_step,
+ * so the 5th step is 5 W.
+ */
+static unsigned char power_levels[] = {
+       MV_TO_ADC8(1581),       // 1250 mW for 2 Ohm load
+       MV_TO_ADC8(1880),       // 1768 mW for 2 Ohm load
+       MV_TO_ADC8(2236),       // 2500 mW for 2 Ohm load
+       MV_TO_ADC8(2659),       // 3536 mW for 2 Ohm load
+       MV_TO_ADC8(3162),       // 5000 mW for 2 Ohm load
+};
+#define N_POWER_LEVELS (sizeof(power_levels) / sizeof(power_levels[0]))
+
+static unsigned char power_level = 0; // selected power level
+
+#define LED_BATTEMPTY_COUNT    60
+
+/* timing by WDT */
+static volatile unsigned char jiffies, next_clock_tick;
+
+/* button press duration (in jiffies) */
+#define BUTTON_SHORT_MIN       1
+#define BUTTON_LONG_MIN                10
+
+
+/* ========= Analog to Digital Converter (battery voltage) ========== */
+static void adc_init()
 {
-       log_init();
+       power_adc_enable();
+
+       ADCSRA = _BV(ADEN)                      // enable
+               | _BV(ADPS1) | _BV(ADPS0);      // clk/8 = 125 kHz
+       ADMUX = _BV(REFS1) | _BV(MUX1) | _BV(MUX0);
+               // 1.1V reference, PB3 pin, single-ended
+       DIDR0 |= _BV(ADC3D);    // PB3 pin as analog input
+}
+
+static void adc_susp()
+{
+       ADCSRA = 0;             // disable ADC
+       DIDR0 &= ~_BV(ADC3D);   // disable analog input on PB3
+
+       power_adc_disable();
+}
+
+static void adc_start_measurement(unsigned char on)
+{
+       adc_drop = 1;
+       adc_type = on;
+       ADCSRA |= _BV(ADSC) | _BV(ADIE);
+}
+
+ISR(ADC_vect)
+{
+       uint16_t adcw = ADCW;
+
+       if (adc_drop) {
+               adc_drop--;
+               ADCSRA |= _BV(ADSC);
+               return;
+       }
+
+       // TODO: We may want to disable ADC after here to save power,
+       // but compared to the heater power it would be negligible,
+       // so don't bother with it.
+       if (adc_type == 0) {
+               if (batt_off) {
+                       batt_off += adcw - (batt_off >> ADC_RUNAVG_SHIFT);
+               } else {
+                       batt_off = adcw << ADC_RUNAVG_SHIFT;
+               }
+       } else {
+               if (batt_on) {
+                       batt_on += adcw - (batt_on >> ADC_RUNAVG_SHIFT);
+               } else {
+                       batt_on = adcw << ADC_RUNAVG_SHIFT;
+               }
+       }
+       ADCSRA &= ~_BV(ADIE);
+}
+
+/* ===================== Timer/Counter1 for PWM ===================== */
+static void pwm_init()
+{
+       power_timer1_enable();
 
-       DDRB |= _BV(PB2) | _BV(PB4);
-       TCCR1 = _BV(CS10); // clk/1 = 1 MHz
+       DDRB |= _BV(PB4);
+       PORTB &= ~_BV(PB4);
+
+       // TCCR1 = _BV(CS10); // clk/1 = 1 MHz
        // TCCR1 = _BV(CS11) | _BV(CS13); // clk/512 = 2 kHz
+       /*
+        * clk/64 = 16 kHz. We use PWM_MIN and PWM_MAX, so we have at least
+        * 8 full T/C1 cycles to do two ADC measurements. The ADC with 125 kHz
+        * clock can do about 7000-9000 measurement per second, so we should
+        * be safe both on low and high OCR1B values with this clock
+        */
+       TCCR1 = _BV(CS12) | _BV(CS11) | _BV(CS10);
+
        GTCCR = _BV(COM1B1) | _BV(PWM1B);
-       OCR1C = 255;
-       OCR1B = 9;
-
-       ADCSRA = _BV(ADEN) | _BV(ADPS1) | _BV(ADPS0); // clk/8 = 125 kHz
-       ADMUX = _BV(REFS1) | _BV(MUX1) | _BV(MUX0); // 1.1V ref., PB3 single-ended
-       DIDR0 = _BV(ADC3D);
-       ADCSRA |= _BV(ADSC);
-       while (!(ADCSRA & _BV(ADIF)))
-               ;
-       log_word(ADCW);
-       ADCSRA |= _BV(ADSC);
-       while (!(ADCSRA & _BV(ADIF)))
-               ;
-       log_word(ADCW);
+       OCR1C = PWM_TOP;
+       // OCR1B = steps[0];
+       OCR1B = 0;
+       TIMSK = _BV(OCIE1B) | _BV(TOIE1);
+}
+
+static void pwm_susp()
+{
+       TCCR1 = 0;
+       TIMSK = 0;
+       GTCCR = 0;
+       PORTB &= ~_BV(PB4);
+}
+
+ISR(TIM1_OVF_vect)
+{
+       adc_start_measurement(1);
+}
+
+ISR(TIM1_COMPB_vect)
+{
+       adc_start_measurement(0);
+}
+
+static void pwm_set(unsigned char pwm)
+{
+       OCR1B = pwm;
+}
+
+/* ===================== Status LED on pin PB2 ======================= */
+static void status_led_init()
+{
+       DDRB |= _BV(PB2);
+       PORTB &= ~_BV(PB2);
+}
+
+static void status_led_on()
+{
+       PORTB |= _BV(PB2);
+}
+
+static void status_led_off()
+{
+       PORTB &= ~_BV(PB2);
+}
+
+static unsigned char status_led_is_on()
+{
+       return PORTB & _BV(PB2) ? 1 : 0;
+}
+
+/* ================== Buttons on pin PB0 and PB1 ===================== */
+static void buttons_init()
+{
+       DDRB &= ~(_BV(PB0) | _BV(PB1)); // set as input
+       PORTB |= _BV(PB0) | _BV(PB1);   // internal pull-up
+
+        GIMSK &= ~_BV(PCIE); // disable pin-change IRQs
+        PCMSK = 0; // disable pin-change IRQs on all pins of port B
+}
+
+static void buttons_susp()
+{
+       buttons_init();
+
+       GIMSK |= _BV(PCIE);
+       PCMSK |= _BV(PCINT0) | _BV(PCINT1);
+}
+
+static unsigned char buttons_pressed()
+{
+       return (
+               (PINB & _BV(BUTTON1) ? 0 : 1)
+               |
+               (PINB & _BV(BUTTON2) ? 0 : 2)
+       );
+}
+
+static unsigned char buttons_wait_for_release()
+{
+       uint16_t wake_count = 0;
+
+       do {
+               if (++wake_count > WAKEUP_LIMIT)
+                       status_led_on(); // inform the user
+
+               _delay_ms(WAKEUP_POLL);
+       } while (buttons_pressed());
+
+       status_led_off();
+
+       return wake_count > WAKEUP_LIMIT;
+}
+
+ISR(PCINT0_vect)
+{
+        // empty - let it wake us from sleep, but do nothing else
+}
+
+/* ==== Watchdog Timer for timing blinks and other periodic tasks ==== */
+static void wdt_init()
+{
+       next_clock_tick = 0;
+       jiffies = 0;
+       WDTCR = _BV(WDIE) | _BV(WDP1); // interrupt mode, 64 ms
+}
+
+static void wdt_susp()
+{
+       wdt_disable();
+}
+
+ISR(WDT_vect) {
+       next_clock_tick = 1;
+       jiffies++;
+}
+
+/* ====== Hardware init, teardown, powering down and waking up ====== */
+static void hw_setup()
+{
+       power_all_disable();
+
+       pwm_init();
+       adc_init();
+       status_led_init();
+       wdt_init();
+}
+
+static void hw_suspend()
+{
+       adc_susp();
+       pwm_susp();
+       status_led_init(); // we don't have a separate _susp() here
+       buttons_susp();
+       wdt_susp();
+
+       power_all_disable();
+}
+
+static void power_down()
+{
+       hw_suspend();
+
+       do {
+               // G'night
+               set_sleep_mode(SLEEP_MODE_PWR_DOWN);
+               sleep_enable();
+               sleep_bod_disable();
+               sei();
+               sleep_cpu();
+
+               // G'morning
+               cli();
+               sleep_disable();
+
+               // allow wakeup by long button-press only
+       } while (!buttons_wait_for_release());
+
+       // OK, wake up now
+       hw_setup();
+}
+
+/* ============ Status LED blinking =================================== */
+static unsigned char blink_on_time, blink_off_time, n_blinks;
+static unsigned char blink_counter;
+
+static unsigned char battery_level()
+{
+       unsigned char i, adc8;
+
+       // NOTE: we use 8-bit value only, so we don't need lock to protect
+       // us against concurrently running ADC IRQ handler:
+       adc8 = batt_off >> 8;
+
+       for (i = 0; i < BATT_N_LEVELS; i++)
+               if (batt_levels[i] > adc8)
+                       break;
+
+       return i;
+}
+
+static void status_led_next_pattern()
+{
+       static unsigned char battery_exhausted;
+       static unsigned char display_power_level;
+
+       if (display_power_level) {
+               n_blinks = power_level + 1;
+               if (batt_on >> 8 == batt_off >> 8) { // load unplugged
+                       n_blinks = 2 * n_blinks;
+                       blink_on_time = 0;
+                       blink_off_time = 0;
+               } else {
+                       blink_on_time = 2;
+                       blink_off_time = 2;
+               }
+       } else {
+               unsigned char b_level = battery_level();
+               if (b_level > 1) {
+                       battery_exhausted = 0;
+               } else if (battery_exhausted) {
+                       if (!--battery_exhausted)
+                               power_down();
+               } else {
+                       battery_exhausted = LED_BATTEMPTY_COUNT;
+               }
+
+               n_blinks = b_level ? b_level : 1;
+               blink_on_time = b_level ? 4 : 2;
+               blink_off_time = 0;
+       }
+
+       blink_counter = 12;
+       display_power_level = !display_power_level;
+}
+
+static void timer_blink()
+{
+       if (blink_counter) {
+               blink_counter--;
+       } else if (!status_led_is_on()) {
+               status_led_on();
+               blink_counter = blink_on_time;
+       } else if (n_blinks) {
+               --n_blinks;
+               status_led_off();
+               blink_counter = blink_off_time;
+       } else {
+               status_led_next_pattern();
+       }
+}
+
+/* ======== Button press detection and  handling ===================== */
+static void button_pressed(unsigned char button, unsigned char long_press)
+{
+       // ignore simlultaneous button 1 and 2 press
+       if (long_press) {
+               power_down();
+               return;
+       } else { // short press
+               if (button == 1) {
+                       if (power_level > 0) {
+                               --power_level;
+                       }
+               } else if (button == 2) {
+                       if (power_level < N_POWER_LEVELS-1) {
+                               ++power_level;
+                       }
+               }
+       }
+       status_led_next_pattern();
+}
+
+static unsigned char button_state, button_state_time;
+
+static void timer_check_buttons()
+{
+       unsigned char newstate = buttons_pressed();
+
+       if (newstate == button_state) {
+               if (newstate && button_state_time < BUTTON_LONG_MIN)
+                       ++button_state_time;
+
+               if (newstate && button_state_time >= BUTTON_LONG_MIN) {
+                       status_led_on();
+               }
+               return;
+       }
+
+       if (newstate) {
+               button_state = newstate;
+               button_state_time = 0;
+               return;
+       }
+
+       // just released
+       if (button_state_time >= BUTTON_SHORT_MIN)
+               button_pressed(button_state,
+                       button_state_time >= BUTTON_LONG_MIN ? 1 : 0);
+
+       button_state = newstate;
+       button_state_time = 0;
+}
+
+/* ===================== Output power control ======================== */
+static void calculate_power_level()
+{
+       uint32_t pwm;
+       unsigned char batt_on8;
+
+       if (battery_level() == 0) {
+               pwm_set(0);
+               // TODO power_down() after some time
+               return;
+       }
+
+       if (!batt_on) {
+               batt_on = batt_off;
+       };
+
+       batt_on8 = batt_on >> 8;
+
+       pwm = (uint32_t)PWM_TOP * power_levels[power_level]
+               * power_levels[power_level];
+       pwm /= (uint32_t)batt_on8 * batt_on8;
+
+       if (pwm > PWM_MAX)
+               pwm = PWM_MAX;
+
+       if (pwm < PWM_MIN)
+               pwm = PWM_MIN;
+
+#if 0
+       log_byte(0x10 + power_level);
+       log_byte(batt_on8);
+       log_byte(pwm & 0xFF);
+#endif
+
+       pwm_set(pwm);
+}
+
+int main()
+{
+       log_init();
+
+#if 0
+       log_word(batt_levels[0]);
+       log_word(batt_levels[1]);
+       log_word(batt_levels[2]);
+       log_flush();
+#endif
+       log_byte(power_levels[0]);
+       log_byte(power_levels[4]);
        log_flush();
 
+       power_down();
+
+       sei();
+
+       // we try to be completely IRQ-driven, so just wait for IRQs here
        while(1) {
-               PORTB |= _BV(PB2);
-               _delay_ms(500);
-               PORTB &= ~_BV(PB2);
-               _delay_ms(1000);
+               cli();
+               set_sleep_mode(SLEEP_MODE_IDLE);
+               sleep_enable();
+               // keep BOD active, no sleep_bod_disable();
+               sei();
+               sleep_cpu();
+               sleep_disable();
+
+               // FIXME: Maybe handle new ADC readings as well?
+               if (next_clock_tick) {
+                       next_clock_tick = 0;
+                       timer_blink();
+                       // this has to be after the timer_blink() call
+                       // to override the status LED during long button press
+                       timer_check_buttons();
+
+                       if ((jiffies & 0x0F) == 0) {
+                               calculate_power_level();
+#if 0
+                               log_byte(0xcc);
+                               log_byte(i);
+                               log_byte(batt_off >> 8);
+                               log_byte(batt_on >> 8);
+#endif
+                       }
+                       if (jiffies == 0) {
+                               log_byte(batt_on >> 8);
+                               log_byte(batt_off >> 8);
+                       }
+                       log_flush();
+               }
        }
 }