5 * Immediately after reset, we power down the entire system.
6 * We wake up only after the button is pressed for a sufficiently long time.
9 * The heater output is driven by Timer/Counter 1 in PWM mode.
10 * We want to be able to measure the battery voltage both when the
11 * output is on, and when the output is off. So we set the T/C1 clock
12 * prescaler so that the T/C1 is slow enough, we enable the T/C1 interrupts
13 * both on compare match and on overflow. After the interrupt, we trigger
14 * the battery voltage measurement with ADC.
17 * To avoid transients, we measure each battery state (when the heater is on
18 * and when it is off) separately, and we drop the first few readings.
19 * We calculate a running average of the readings to achieve higher accuracy.
22 * There are two buttons (+ and -). Any button can wake the system up from
23 * the power-down state.
24 * TODO: When the system is woken up by the "-" button,
25 * it starts with the minimum output power, when it is woken up by the "+"
26 * button, it start with the maximum output power.
27 * When running, the "-" button is used for decreasing the output power,
28 * the "+" button is for increasing it.
29 * When on the lowest power state, the "-" button switches the system off.
30 * Long "-" button press switches the system off, long "+" button
31 * press sets the output power to maximum.
34 * When powering up by a button press, the LED goes on to provide a visual
35 * feedback, and is switched off after the button is released.
36 * It displays the current power level and current battery voltage
37 * using # of blinks with different blinking lengths.
38 * When the battery is completely exhausted, the output power is switched
39 * off, the LED keeps blinking for some time, and then the whole system is
40 * switched off to avoid deep discharge of the battery.
43 * The firmware is timed by the Watchdog Timer interrupt. Most of the
44 * processing is done from the main loop, IRQs only set various flags
45 * or trigger other events.
48 #include <avr/interrupt.h>
50 #include <avr/power.h>
51 #include <avr/sleep.h>
53 #include <util/delay.h>
57 /* waking up from the power down state by a button press */
58 #define WAKEUP_POLL 50 // msec
59 #define WAKEUP_LIMIT 5 // times WAKEUP_POLL
61 // #define BUTTONS_REVERSE
63 #ifdef BUTTONS_REVERSE
69 #endif /* !BUTTONS_REVERSE */
71 /* which state (output on or output off) are we measuring now */
72 static volatile unsigned char adc_type, adc_drop;
73 #define ADC_RUNAVG_SHIFT 5 // running average shift on batt_on, batt_off
74 static volatile uint16_t batt_on, batt_off; // measured voltage
77 * The voltage divider has 1M5 and 300K resistors (i.e. it measures 1/6th of
78 * the real voltage), ADC uses 1.1V internal reference.
79 * Macro to calculate upper eight bits of the ADC running-averaged value
80 * from the voltage in milivolts.
82 #define ADC_1100MV_VALUE 1071 // measured, not exactly 1100
83 #define MV_TO_ADC8(mV) ((unsigned char)(((uint32_t)(1UL << ADC_RUNAVG_SHIFT) \
85 / (6UL * ADC_1100MV_VALUE)) >> 8))
86 static unsigned char batt_levels[] = {
91 #define BATT_N_LEVELS (sizeof(batt_levels) / sizeof(batt_levels[0]))
93 /* output power and PWM calculation */
95 #define PWM_MAX (PWM_TOP - 8) // to allow for ADC "batt_off" measurements
96 #define PWM_MIN 8 // to allow for ADC "batt_on" measurements
99 * The values in power_levels[] array are voltages at which the load
100 * would give the expected power (we don't have sqrt() function,
101 * so we cannot use mW values directly. They can be calculated as
102 * voltage[V] = sqrt(load_resistance[Ohm] * expected_power[W])
104 * voltage[mV] = sqrt(load_resistance[mOhm] * expected_power[mW])
106 * I use 1.25 W as minimum power, each step is sqrt(2)*previous_step,
107 * so the 5th step is 5 W.
109 static unsigned char power_levels[] = {
110 MV_TO_ADC8(1581), // 1250 mW for 2 Ohm load
111 MV_TO_ADC8(1880), // 1768 mW for 2 Ohm load
112 MV_TO_ADC8(2236), // 2500 mW for 2 Ohm load
113 MV_TO_ADC8(2659), // 3536 mW for 2 Ohm load
114 MV_TO_ADC8(3162), // 5000 mW for 2 Ohm load
116 #define N_POWER_LEVELS (sizeof(power_levels) / sizeof(power_levels[0]))
118 static unsigned char power_level = 0; // selected power level
120 #define LED_BATTEMPTY_COUNT 60
123 static volatile unsigned char jiffies, next_clock_tick;
125 /* button press duration (in jiffies) */
126 #define BUTTON_SHORT_MIN 1
127 #define BUTTON_LONG_MIN 10
130 /* ========= Analog to Digital Converter (battery voltage) ========== */
131 static void adc_init()
135 ADCSRA = _BV(ADEN) // enable
136 | _BV(ADPS1) | _BV(ADPS0); // clk/8 = 125 kHz
137 ADMUX = _BV(REFS1) | _BV(MUX1) | _BV(MUX0);
138 // 1.1V reference, PB3 pin, single-ended
139 DIDR0 |= _BV(ADC3D); // PB3 pin as analog input
142 static void adc_susp()
144 ADCSRA = 0; // disable ADC
145 DIDR0 &= ~_BV(ADC3D); // disable analog input on PB3
150 static void adc_start_measurement(unsigned char on)
154 ADCSRA |= _BV(ADSC) | _BV(ADIE);
159 uint16_t adcw = ADCW;
167 // TODO: We may want to disable ADC after here to save power,
168 // but compared to the heater power it would be negligible,
169 // so don't bother with it.
172 batt_off += adcw - (batt_off >> ADC_RUNAVG_SHIFT);
174 batt_off = adcw << ADC_RUNAVG_SHIFT;
178 batt_on += adcw - (batt_on >> ADC_RUNAVG_SHIFT);
180 batt_on = adcw << ADC_RUNAVG_SHIFT;
183 ADCSRA &= ~_BV(ADIE);
186 /* ===================== Timer/Counter1 for PWM ===================== */
187 static void pwm_init()
189 power_timer1_enable();
194 // TCCR1 = _BV(CS10); // clk/1 = 1 MHz
195 // TCCR1 = _BV(CS11) | _BV(CS13); // clk/512 = 2 kHz
197 * clk/64 = 16 kHz. We use PWM_MIN and PWM_MAX, so we have at least
198 * 8 full T/C1 cycles to do two ADC measurements. The ADC with 125 kHz
199 * clock can do about 7000-9000 measurement per second, so we should
200 * be safe both on low and high OCR1B values with this clock
202 TCCR1 = _BV(CS12) | _BV(CS11) | _BV(CS10);
204 GTCCR = _BV(COM1B1) | _BV(PWM1B);
208 TIMSK = _BV(OCIE1B) | _BV(TOIE1);
211 static void pwm_susp()
221 adc_start_measurement(1);
226 adc_start_measurement(0);
229 static void pwm_set(unsigned char pwm)
234 /* ===================== Status LED on pin PB2 ======================= */
235 static void status_led_init()
241 static void status_led_on()
246 static void status_led_off()
251 static unsigned char status_led_is_on()
253 return PORTB & _BV(PB2) ? 1 : 0;
256 /* ================== Buttons on pin PB0 and PB1 ===================== */
257 static void buttons_init()
259 DDRB &= ~(_BV(PB0) | _BV(PB1)); // set as input
260 PORTB |= _BV(PB0) | _BV(PB1); // internal pull-up
262 GIMSK &= ~_BV(PCIE); // disable pin-change IRQs
263 PCMSK = 0; // disable pin-change IRQs on all pins of port B
266 static void buttons_susp()
271 PCMSK |= _BV(PCINT0) | _BV(PCINT1);
274 static unsigned char buttons_pressed()
277 (PINB & _BV(BUTTON1) ? 0 : 1)
279 (PINB & _BV(BUTTON2) ? 0 : 2)
283 static unsigned char buttons_wait_for_release()
285 uint16_t wake_count = 0;
288 if (++wake_count > WAKEUP_LIMIT)
289 status_led_on(); // inform the user
291 _delay_ms(WAKEUP_POLL);
292 } while (buttons_pressed());
296 return wake_count > WAKEUP_LIMIT;
301 // empty - let it wake us from sleep, but do nothing else
304 /* ==== Watchdog Timer for timing blinks and other periodic tasks ==== */
305 static void wdt_init()
309 WDTCR = _BV(WDIE) | _BV(WDP1); // interrupt mode, 64 ms
312 static void wdt_susp()
322 /* ====== Hardware init, teardown, powering down and waking up ====== */
323 static void hw_setup()
333 static void hw_suspend()
337 status_led_init(); // we don't have a separate _susp() here
344 static void power_down()
350 set_sleep_mode(SLEEP_MODE_PWR_DOWN);
360 // allow wakeup by long button-press only
361 } while (!buttons_wait_for_release());
367 /* ============ Status LED blinking =================================== */
368 static unsigned char blink_on_time, blink_off_time, n_blinks;
369 static unsigned char blink_counter;
371 static unsigned char battery_level()
373 unsigned char i, adc8;
375 // NOTE: we use 8-bit value only, so we don't need lock to protect
376 // us against concurrently running ADC IRQ handler:
377 adc8 = batt_off >> 8;
379 for (i = 0; i < BATT_N_LEVELS; i++)
380 if (batt_levels[i] > adc8)
386 static void status_led_next_pattern()
388 static unsigned char battery_exhausted;
389 static unsigned char display_power_level;
391 if (display_power_level) {
392 n_blinks = power_level + 1;
396 unsigned char b_level = battery_level();
398 battery_exhausted = 0;
399 } else if (battery_exhausted) {
400 if (!--battery_exhausted)
403 battery_exhausted = LED_BATTEMPTY_COUNT;
406 n_blinks = b_level + 1;
412 display_power_level = !display_power_level;
415 static void timer_blink()
419 } else if (!status_led_is_on()) {
421 blink_counter = blink_on_time;
422 } else if (n_blinks) {
425 blink_counter = blink_off_time;
427 status_led_next_pattern();
431 /* ======== Button press detection and handling ===================== */
432 static void button_pressed(unsigned char button, unsigned char long_press)
434 // ignore simlultaneous button 1 and 2 press
439 } else if (button == 2) {
440 power_level = N_POWER_LEVELS-1;
442 } else { // short press
444 if (power_level > 0) {
450 } else if (button == 2) {
451 if (power_level < N_POWER_LEVELS-1) {
456 status_led_next_pattern();
459 static unsigned char button_state, button_state_time;
461 static void timer_check_buttons()
463 unsigned char newstate = buttons_pressed();
465 if (newstate == button_state) {
466 if (newstate && button_state_time < BUTTON_LONG_MIN)
469 if (newstate && button_state_time >= BUTTON_LONG_MIN) {
476 button_state = newstate;
477 button_state_time = 0;
482 if (button_state_time >= BUTTON_SHORT_MIN)
483 button_pressed(button_state,
484 button_state_time >= BUTTON_LONG_MIN ? 1 : 0);
486 button_state = newstate;
487 button_state_time = 0;
490 /* ===================== Output power control ======================== */
491 static void calculate_power_level()
494 unsigned char batt_on8;
496 if (battery_level() == 0) {
498 // TODO power_down() after some time
506 batt_on8 = batt_on >> 8;
508 pwm = (uint32_t)PWM_TOP * power_levels[power_level]
509 * power_levels[power_level];
510 pwm /= (uint32_t)batt_on8 * batt_on8;
519 log_byte(0x10 + power_level);
521 log_byte(pwm & 0xFF);
532 log_word(batt_levels[0]);
533 log_word(batt_levels[1]);
534 log_word(batt_levels[2]);
537 log_byte(power_levels[0]);
538 log_byte(power_levels[4]);
545 // we try to be completely IRQ-driven, so just wait for IRQs here
548 set_sleep_mode(SLEEP_MODE_IDLE);
550 // keep BOD active, no sleep_bod_disable();
555 // FIXME: Maybe handle new ADC readings as well?
556 if (next_clock_tick) {
559 // this has to be after the timer_blink() call
560 // to override the status LED during long button press
561 timer_check_buttons();
563 if ((jiffies & 0x0F) == 0) {
564 calculate_power_level();
568 log_byte(batt_off >> 8);
569 log_byte(batt_on >> 8);