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 * After a button press, the # of blinks of the LED reflects the
37 * chosen output power level for some time. Afterwards, it displays
39 * When the battery is completely exhausted, the output power is switched
40 * off, the LED keeps blinking for some time, and then the whole system is
41 * switched off to avoid deep discharge of the battery.
44 * The firmware is timed by the Watchdog Timer interrupt. Most of the
45 * processing is done from the main loop, IRQs only set various flags
46 * or trigger other events.
49 #include <avr/interrupt.h>
51 #include <avr/power.h>
52 #include <avr/sleep.h>
54 #include <util/delay.h>
58 /* waking up from the power down state by a button press */
59 #define WAKEUP_POLL 50 // msec
60 #define WAKEUP_LIMIT 5 // times WAKEUP_POLL
62 /* which state (output on or output off) are we measuring now */
63 static volatile unsigned char adc_type, adc_drop;
64 #define ADC_RUNAVG_SHIFT 5 // running average shift on batt_on, batt_off
65 static volatile uint16_t batt_on, batt_off; // measured voltage
68 * The voltage divider has 1M5 and 300K resistors (i.e. it measures 1/6th of
69 * the real voltage), ADC uses 1.1V internal reference.
70 * Macro to calculate upper eight bits of the ADC running-averaged value
71 * from the voltage in milivolts.
73 #define ADC_1100MV_VALUE 1071 // measured, not exactly 1100
74 #define MV_TO_ADC8(mV) ((unsigned char)(((uint32_t)(1UL << ADC_RUNAVG_SHIFT) \
76 / (6UL * ADC_1100MV_VALUE)) >> 8))
77 static unsigned char batt_levels[] = {
82 #define BATT_N_LEVELS (sizeof(batt_levels) / sizeof(batt_levels[0]))
84 /* output power and PWM calculation */
86 #define PWM_MAX (PWM_TOP - 8) // to allow for ADC "batt_off" measurements
87 #define PWM_MIN 8 // to allow for ADC "batt_on" measurements
90 * The values in power_levels[] array are voltages at which the load
91 * would give the expected power (we don't have sqrt() function,
92 * so we cannot use mW values directly. They can be calculated as
93 * voltage[V] = sqrt(load_resistance[Ohm] * expected_power[W])
95 * voltage[mV] = sqrt(load_resistance[mOhm] * expected_power[mW])
97 * I use 1.25 W as minimum power, each step is sqrt(2)*previous_step,
98 * so the 5th step is 5 W.
100 static unsigned char power_levels[] = {
101 MV_TO_ADC8(1581), // 1250 mW for 2 Ohm load
102 MV_TO_ADC8(1880), // 1768 mW for 2 Ohm load
103 MV_TO_ADC8(2236), // 2500 mW for 2 Ohm load
104 MV_TO_ADC8(2659), // 3536 mW for 2 Ohm load
105 MV_TO_ADC8(3162), // 5000 mW for 2 Ohm load
107 #define N_POWER_LEVELS (sizeof(power_levels) / sizeof(power_levels[0]))
109 static unsigned char power_level = 0; // selected power level
110 static unsigned char power_level_changed; // for visual feedback
112 #define LED_PWRCHANGE_COUNT 3
113 #define LED_BATTEMPTY_COUNT 60
116 static volatile unsigned char jiffies, next_clock_tick;
118 /* button press duration (in jiffies) */
119 #define BUTTON_SHORT_MIN 1
120 #define BUTTON_LONG_MIN 10
123 /* ========= Analog to Digital Converter (battery voltage) ========== */
124 static void adc_init()
128 ADCSRA = _BV(ADEN) // enable
129 | _BV(ADPS1) | _BV(ADPS0) // clk/8 = 125 kHz
130 | _BV(ADIE); // enable IRQ
131 ADMUX = _BV(REFS1) | _BV(MUX1) | _BV(MUX0);
132 // 1.1V reference, PB3 pin, single-ended
133 DIDR0 |= _BV(ADC3D); // PB3 pin as analog input
136 static void adc_susp()
138 ADCSRA &= ~_BV(ADEN); // disable ADC
139 DIDR0 &= ~_BV(ADC3D); // disable analog input on PB3
144 static void adc_start_measurement()
151 uint16_t adcw = ADCW;
159 // TODO: We may want to disable ADC after here to save power,
160 // but compared to the heater power it would be negligible,
161 // so don't bother with it.
164 batt_off += adcw - (batt_off >> ADC_RUNAVG_SHIFT);
166 batt_off = adcw << ADC_RUNAVG_SHIFT;
170 batt_on += adcw - (batt_on >> ADC_RUNAVG_SHIFT);
172 batt_on = adcw << ADC_RUNAVG_SHIFT;
177 /* ===================== Timer/Counter1 for PWM ===================== */
178 static void pwm_init()
180 power_timer1_enable();
185 // TCCR1 = _BV(CS10); // clk/1 = 1 MHz
186 // TCCR1 = _BV(CS11) | _BV(CS13); // clk/512 = 2 kHz
188 * clk/64 = 16 kHz. We use PWM_MIN and PWM_MAX, so we have at least
189 * 8 full T/C1 cycles to do two ADC measurements. The ADC with 125 kHz
190 * clock can do about 7000-9000 measurement per second, so we should
191 * be safe both on low and high OCR1B values with this clock
193 TCCR1 = _BV(CS12) | _BV(CS11) | _BV(CS10);
195 GTCCR = _BV(COM1B1) | _BV(PWM1B);
199 TIMSK = _BV(OCIE1B) | _BV(TOIE1);
202 static void pwm_susp()
214 adc_start_measurement();
221 adc_start_measurement();
224 static void pwm_set(unsigned char pwm)
229 /* ===================== Status LED on pin PB2 ======================= */
230 static void status_led_init()
236 static void status_led_on()
241 static void status_led_off()
246 static unsigned char status_led_is_on()
248 return PORTB & _BV(PB2) ? 1 : 0;
251 /* ================== Buttons on pin PB0 and PB1 ===================== */
252 static void buttons_init()
254 DDRB &= ~(_BV(PB0) | _BV(PB1)); // set as input
255 PORTB |= _BV(PB0) | _BV(PB1); // internal pull-up
257 GIMSK &= ~_BV(PCIE); // disable pin-change IRQs
258 PCMSK = 0; // disable pin-change IRQs on all pins of port B
261 static void buttons_susp()
266 PCMSK |= _BV(PCINT0) | _BV(PCINT1);
269 static unsigned char buttons_pressed()
272 (PINB & _BV(PB0) ? 0 : 1)
274 (PINB & _BV(PB1) ? 0 : 2)
278 static unsigned char buttons_wait_for_release()
280 uint16_t wake_count = 0;
283 if (++wake_count > WAKEUP_LIMIT)
284 status_led_on(); // inform the user
286 _delay_ms(WAKEUP_POLL);
287 } while (buttons_pressed());
291 return wake_count > WAKEUP_LIMIT;
296 // empty - let it wake us from sleep, but do nothing else
299 /* ==== Watchdog Timer for timing blinks and other periodic tasks ==== */
300 static void wdt_init()
304 WDTCR = _BV(WDIE) | _BV(WDP1); // interrupt mode, 64 ms
307 static void wdt_susp()
317 /* ====== Hardware init, teardown, powering down and waking up ====== */
318 static void hw_setup()
328 static void hw_suspend()
332 status_led_init(); // we don't have a separate _susp() here
339 static void power_down()
345 set_sleep_mode(SLEEP_MODE_PWR_DOWN);
355 // allow wakeup by long button-press only
356 } while (!buttons_wait_for_release());
362 /* ============ Status LED blinking =================================== */
363 static unsigned char blink_on_time, blink_off_time, n_blinks;
364 static unsigned char blink_counter;
366 static unsigned char battery_level()
368 unsigned char i, adc8;
370 // NOTE: we use 8-bit value only, so we don't need lock to protect
371 // us against concurrently running ADC IRQ handler:
372 adc8 = batt_off >> 8;
374 for (i = 0; i < BATT_N_LEVELS; i++)
375 if (batt_levels[i] > adc8)
381 static void status_led_next_pattern()
383 static unsigned char battery_exhausted;
385 if (power_level_changed) {
386 power_level_changed--;
387 n_blinks = power_level + 1;
389 unsigned char b_level = battery_level();
391 battery_exhausted = 0;
392 } else if (battery_exhausted) {
393 if (!--battery_exhausted)
396 battery_exhausted = LED_BATTEMPTY_COUNT;
399 n_blinks = b_level + 1;
407 static void timer_blink()
411 } else if (!status_led_is_on()) {
413 blink_counter = blink_on_time;
414 } else if (n_blinks) {
417 blink_counter = blink_off_time;
419 status_led_next_pattern();
423 /* ======== Button press detection and handling ===================== */
424 static void button_pressed(unsigned char button, unsigned char long_press)
426 // ignore simlultaneous button 1 and 2 press
427 // Note: we set power_level_changed after each button press,
428 // even when the power is at maximum, to provide visual feedback
434 } else if (button == 2) {
435 power_level = N_POWER_LEVELS-1;
437 } else { // short press
439 if (power_level > 0) {
445 } else if (button == 2) {
446 if (power_level < N_POWER_LEVELS-1) {
451 power_level_changed = LED_PWRCHANGE_COUNT;
452 status_led_next_pattern();
455 static unsigned char button_state, button_state_time;
457 static void timer_check_buttons()
459 unsigned char newstate = buttons_pressed();
461 if (newstate == button_state) {
462 if (newstate && button_state_time < BUTTON_LONG_MIN)
465 if (newstate && button_state_time >= BUTTON_LONG_MIN) {
472 button_state = newstate;
473 button_state_time = 0;
478 if (button_state_time >= BUTTON_SHORT_MIN)
479 button_pressed(button_state,
480 button_state_time >= BUTTON_LONG_MIN ? 1 : 0);
482 button_state = newstate;
483 button_state_time = 0;
486 /* ===================== Output power control ======================== */
487 static void calculate_power_level()
490 unsigned char batt_on8;
492 if (battery_level() == 0 || batt_on == 0) {
494 // TODO power_down() after some time
498 batt_on8 = batt_on >> 8;
500 pwm = (uint32_t)PWM_TOP * power_levels[power_level]
501 * power_levels[power_level];
502 pwm /= (uint32_t)batt_on8 * batt_on8;
510 log_byte(0x10 + power_level);
512 log_byte(pwm & 0xFF);
522 log_word(batt_levels[0]);
523 log_word(batt_levels[1]);
524 log_word(batt_levels[2]);
527 log_byte(power_levels[0]);
528 log_byte(power_levels[4]);
535 // we try to be completely IRQ-driven, so just wait for IRQs here
538 set_sleep_mode(SLEEP_MODE_IDLE);
540 // keep BOD active, no sleep_bod_disable();
545 // FIXME: Maybe handle new ADC readings as well?
546 if (next_clock_tick) {
549 // this has to be after the timer_blink() call
550 // to override the status LED during long button press
551 timer_check_buttons();
553 if ((jiffies & 0x0F) == 0) {
554 calculate_power_level();
558 log_byte(batt_off >> 8);
559 log_byte(batt_on >> 8);