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 * When running, the "-" button is used for decreasing the output power,
25 * the "+" button is for increasing it.
26 * Any long button press switches the system off.
29 * When powering up by a button press, the LED goes on to provide a visual
30 * feedback, and is switched off after the button is released.
31 * It displays the current power level and current battery voltage
32 * using # of blinks with different blinking lengths.
33 * When the battery is completely exhausted, the output power is switched
34 * off, the LED keeps blinking for some time, and then the whole system is
35 * switched off to avoid deep discharge of the battery.
38 * The firmware is timed by the Watchdog Timer interrupt. Most of the
39 * processing is done from the main loop, IRQs only set various flags
40 * or trigger other events.
43 #include <avr/interrupt.h>
45 #include <avr/power.h>
46 #include <avr/sleep.h>
48 #include <util/delay.h>
52 /* waking up from the power down state by a button press */
53 #define WAKEUP_POLL 50 // msec
54 #define WAKEUP_LIMIT 5 // times WAKEUP_POLL
56 // #define BUTTONS_REVERSE
58 #ifdef BUTTONS_REVERSE
64 #endif /* !BUTTONS_REVERSE */
66 /* which state (output on or output off) are we measuring now */
67 static volatile unsigned char adc_type, adc_drop;
68 #define ADC_RUNAVG_SHIFT 5 // running average shift on batt_on, batt_off
69 static volatile uint16_t batt_on, batt_off; // measured voltage
72 * The voltage divider has 1M5 and 300K resistors (i.e. it measures 1/6th of
73 * the real voltage), ADC uses 1.1V internal reference.
74 * Macro to calculate upper eight bits of the ADC running-averaged value
75 * from the voltage in milivolts.
77 #define ADC_1100MV_VALUE 1071 // measured, not exactly 1100
78 #define MV_TO_ADC8(mV) ((unsigned char)(((uint32_t)(1UL << ADC_RUNAVG_SHIFT) \
80 / (6UL * ADC_1100MV_VALUE)) >> 8))
81 static unsigned char batt_levels[] = {
82 MV_TO_ADC8(3000), // below this, do not enable load, and switch off
83 MV_TO_ADC8(3150), // below this, switch off after some time
84 MV_TO_ADC8(3450), // battery low
85 MV_TO_ADC8(3800), // battery ok, above that almost full
87 #define BATT_N_LEVELS (sizeof(batt_levels) / sizeof(batt_levels[0]))
89 /* output power and PWM calculation */
91 #define PWM_MAX (PWM_TOP - 8) // to allow for ADC "batt_off" measurements
92 #define PWM_MIN 8 // to allow for ADC "batt_on" measurements
95 * The values in power_levels[] array are voltages at which the load
96 * would give the expected power (we don't have sqrt() function,
97 * so we cannot use mW values directly. They can be calculated as
98 * voltage[V] = sqrt(load_resistance[Ohm] * expected_power[W])
100 * voltage[mV] = sqrt(load_resistance[mOhm] * expected_power[mW])
102 * I use 1.25 W as minimum power, each step is sqrt(2)*previous_step,
103 * so the 5th step is 5 W.
105 static unsigned char power_levels[] = {
106 MV_TO_ADC8(1581), // 1250 mW for 2 Ohm load
107 MV_TO_ADC8(1880), // 1768 mW for 2 Ohm load
108 MV_TO_ADC8(2236), // 2500 mW for 2 Ohm load
109 MV_TO_ADC8(2659), // 3536 mW for 2 Ohm load
110 MV_TO_ADC8(3162), // 5000 mW for 2 Ohm load
112 #define N_POWER_LEVELS (sizeof(power_levels) / sizeof(power_levels[0]))
114 static unsigned char power_level = 0; // selected power level
116 #define LED_BATTEMPTY_COUNT 60
119 static volatile unsigned char jiffies, next_clock_tick;
121 /* button press duration (in jiffies) */
122 #define BUTTON_SHORT_MIN 1
123 #define BUTTON_LONG_MIN 10
126 /* ========= Analog to Digital Converter (battery voltage) ========== */
127 static void adc_init()
131 ADCSRA = _BV(ADEN) // enable
132 | _BV(ADPS1) | _BV(ADPS0); // clk/8 = 125 kHz
133 ADMUX = _BV(REFS1) | _BV(MUX1) | _BV(MUX0);
134 // 1.1V reference, PB3 pin, single-ended
135 DIDR0 |= _BV(ADC3D); // PB3 pin as analog input
138 static void adc_susp()
140 ADCSRA = 0; // disable ADC
141 DIDR0 &= ~_BV(ADC3D); // disable analog input on PB3
146 static void adc_start_measurement(unsigned char on)
150 ADCSRA |= _BV(ADSC) | _BV(ADIE);
155 uint16_t adcw = ADCW;
163 // TODO: We may want to disable ADC after here to save power,
164 // but compared to the heater power it would be negligible,
165 // so don't bother with it.
168 batt_off += adcw - (batt_off >> ADC_RUNAVG_SHIFT);
170 batt_off = adcw << ADC_RUNAVG_SHIFT;
174 batt_on += adcw - (batt_on >> ADC_RUNAVG_SHIFT);
176 batt_on = adcw << ADC_RUNAVG_SHIFT;
179 ADCSRA &= ~_BV(ADIE);
182 /* ===================== Timer/Counter1 for PWM ===================== */
183 static void pwm_init()
185 power_timer1_enable();
190 // TCCR1 = _BV(CS10); // clk/1 = 1 MHz
191 // TCCR1 = _BV(CS11) | _BV(CS13); // clk/512 = 2 kHz
193 * clk/64 = 16 kHz. We use PWM_MIN and PWM_MAX, so we have at least
194 * 8 full T/C1 cycles to do two ADC measurements. The ADC with 125 kHz
195 * clock can do about 7000-9000 measurement per second, so we should
196 * be safe both on low and high OCR1B values with this clock
198 TCCR1 = _BV(CS12) | _BV(CS11) | _BV(CS10);
200 GTCCR = _BV(COM1B1) | _BV(PWM1B);
204 TIMSK = _BV(OCIE1B) | _BV(TOIE1);
207 static void pwm_susp()
217 adc_start_measurement(1);
222 adc_start_measurement(0);
225 static void pwm_set(unsigned char pwm)
230 /* ===================== Status LED on pin PB2 ======================= */
231 static void status_led_init()
237 static void status_led_on()
242 static void status_led_off()
247 static unsigned char status_led_is_on()
249 return PORTB & _BV(PB2) ? 1 : 0;
252 /* ================== Buttons on pin PB0 and PB1 ===================== */
253 static void buttons_init()
255 DDRB &= ~(_BV(PB0) | _BV(PB1)); // set as input
256 PORTB |= _BV(PB0) | _BV(PB1); // internal pull-up
258 GIMSK &= ~_BV(PCIE); // disable pin-change IRQs
259 PCMSK = 0; // disable pin-change IRQs on all pins of port B
262 static void buttons_susp()
267 PCMSK |= _BV(PCINT0) | _BV(PCINT1);
270 static unsigned char buttons_pressed()
273 (PINB & _BV(BUTTON1) ? 0 : 1)
275 (PINB & _BV(BUTTON2) ? 0 : 2)
279 static unsigned char buttons_wait_for_release()
281 uint16_t wake_count = 0;
284 if (++wake_count > WAKEUP_LIMIT)
285 status_led_on(); // inform the user
287 _delay_ms(WAKEUP_POLL);
288 } while (buttons_pressed());
292 return wake_count > WAKEUP_LIMIT;
297 // empty - let it wake us from sleep, but do nothing else
300 /* ==== Watchdog Timer for timing blinks and other periodic tasks ==== */
301 static void wdt_init()
305 WDTCR = _BV(WDIE) | _BV(WDP1); // interrupt mode, 64 ms
308 static void wdt_susp()
318 /* ====== Hardware init, teardown, powering down and waking up ====== */
319 static void hw_setup()
329 static void hw_suspend()
333 status_led_init(); // we don't have a separate _susp() here
340 static void power_down()
346 set_sleep_mode(SLEEP_MODE_PWR_DOWN);
356 // allow wakeup by long button-press only
357 } while (!buttons_wait_for_release());
363 /* ============ Status LED blinking =================================== */
364 static unsigned char blink_on_time, blink_off_time, n_blinks;
365 static unsigned char blink_counter;
367 static unsigned char battery_level()
369 unsigned char i, adc8;
371 // NOTE: we use 8-bit value only, so we don't need lock to protect
372 // us against concurrently running ADC IRQ handler:
373 adc8 = batt_off >> 8;
375 for (i = 0; i < BATT_N_LEVELS; i++)
376 if (batt_levels[i] > adc8)
382 static void status_led_next_pattern()
384 static unsigned char battery_exhausted;
385 static unsigned char display_power_level;
387 if (display_power_level) {
388 n_blinks = power_level + 1;
389 if (batt_on >> 8 == batt_off >> 8) { // load unplugged
390 n_blinks = 2 * n_blinks;
398 unsigned char b_level = battery_level();
400 battery_exhausted = 0;
401 } else if (battery_exhausted) {
402 if (!--battery_exhausted)
405 battery_exhausted = LED_BATTEMPTY_COUNT;
408 n_blinks = b_level ? b_level : 1;
409 blink_on_time = b_level ? 4 : 2;
414 display_power_level = !display_power_level;
417 static void timer_blink()
421 } else if (!status_led_is_on()) {
423 blink_counter = blink_on_time;
424 } else if (n_blinks) {
427 blink_counter = blink_off_time;
429 status_led_next_pattern();
433 /* ======== Button press detection and handling ===================== */
434 static void button_pressed(unsigned char button, unsigned char long_press)
436 // ignore simlultaneous button 1 and 2 press
440 } else { // short press
442 if (power_level > 0) {
445 } else if (button == 2) {
446 if (power_level < N_POWER_LEVELS-1) {
451 status_led_next_pattern();
454 static unsigned char button_state, button_state_time;
456 static void timer_check_buttons()
458 unsigned char newstate = buttons_pressed();
460 if (newstate == button_state) {
461 if (newstate && button_state_time < BUTTON_LONG_MIN)
464 if (newstate && button_state_time >= BUTTON_LONG_MIN) {
471 button_state = newstate;
472 button_state_time = 0;
477 if (button_state_time >= BUTTON_SHORT_MIN)
478 button_pressed(button_state,
479 button_state_time >= BUTTON_LONG_MIN ? 1 : 0);
481 button_state = newstate;
482 button_state_time = 0;
485 /* ===================== Output power control ======================== */
486 static void calculate_power_level()
489 unsigned char batt_on8;
491 if (battery_level() == 0) {
493 // TODO power_down() after some time
501 batt_on8 = batt_on >> 8;
503 pwm = (uint32_t)PWM_TOP * power_levels[power_level]
504 * power_levels[power_level];
505 pwm /= (uint32_t)batt_on8 * batt_on8;
514 log_byte(0x10 + power_level);
516 log_byte(pwm & 0xFF);
527 log_word(batt_levels[0]);
528 log_word(batt_levels[1]);
529 log_word(batt_levels[2]);
532 log_byte(power_levels[0]);
533 log_byte(power_levels[4]);
540 // we try to be completely IRQ-driven, so just wait for IRQs here
543 set_sleep_mode(SLEEP_MODE_IDLE);
545 // keep BOD active, no sleep_bod_disable();
550 // FIXME: Maybe handle new ADC readings as well?
551 if (next_clock_tick) {
554 // this has to be after the timer_blink() call
555 // to override the status LED during long button press
556 timer_check_buttons();
558 if ((jiffies & 0x0F) == 0) {
559 calculate_power_level();
563 log_byte(batt_off >> 8);
564 log_byte(batt_on >> 8);
568 log_byte(batt_on >> 8);
569 log_byte(batt_off >> 8);