]> www.fi.muni.cz Git - heater.git/blob - firmware/main.c
Battery voltage measurement and reporting
[heater.git] / firmware / main.c
1 /*
2  * OVERVIEW
3  *
4  * Powering up:
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.
7  *
8  * Heater output:
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.
15  *
16  * 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.
20  *
21  * Buttons:
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  * TODO: Long "-" button press switches the system off, long "+" button
31  * press sets the output power to maximum.
32  *
33  * Status LED:
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  * TODO: After a button press, the # of blinks of the LED reflects the
37  * chosen output power level for some time. Afterwards, it displays
38  * the battery level.
39  * TODO: 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.
42  *
43  * Timing:
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.
47  */
48
49 #include <avr/interrupt.h>
50 #include <avr/io.h>
51 #include <avr/power.h>
52 #include <avr/sleep.h>
53 #include <avr/wdt.h>
54 #include <util/delay.h>
55
56 #include "logging.h"
57
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
61
62 /* output power levels */
63 #define N_STEPS 5
64 static unsigned char steps[] = { 60, 85, 121, 171, 242 };
65 static unsigned char intensity = 0; // selected power level
66
67 /* which state (output on or output off) are we measuring now */
68 static volatile unsigned char adc_type, adc_drop;
69 #define ADC_RUNAVG_SHIFT 5      // running average shift on batt_on, batt_off
70 static volatile uint16_t batt_on, batt_off; // measured voltage
71
72 /*
73  * The voltage divider has 1M5 and 300K resistors (i.e. it measures 1/6th of
74  * the real voltage), ADC uses 1.1V internal reference.
75  * Macro to calculate upper eight bits of the ADC running-averaged value
76  * from the voltage in milivolts.
77  */
78 #define ADC_1100MV_VALUE        1071    // measured, not exactly 1100
79 #define MV_TO_ADC8(mV)  ((unsigned char)(((uint32_t)(1UL << ADC_RUNAVG_SHIFT) \
80                                 * (1024UL * (mV)) \
81                                 / (6UL * ADC_1100MV_VALUE)) >> 8))
82 #define BATT_N_LEVELS   3
83 static unsigned char batt_levels[BATT_N_LEVELS] = {
84         MV_TO_ADC8(3500),
85         MV_TO_ADC8(3700),
86         MV_TO_ADC8(3900),
87 };
88
89 /* timing by WDT */
90 static volatile unsigned char jiffies, next_clock_tick;
91
92 /* ========= Analog to Digital Converter (battery voltage) ========== */
93 static void adc_init()
94 {
95         power_adc_enable();
96
97         ADCSRA = _BV(ADEN)                      // enable
98                 | _BV(ADPS1) | _BV(ADPS0)       // clk/8 = 125 kHz
99                 | _BV(ADIE);                    // enable IRQ
100         ADMUX = _BV(REFS1) | _BV(MUX1) | _BV(MUX0);
101                 // 1.1V reference, PB3 pin, single-ended
102         DIDR0 |= _BV(ADC3D);    // PB3 pin as analog input
103 }
104
105 static void adc_susp()
106 {
107         ADCSRA &= ~_BV(ADEN);   // disable ADC
108         DIDR0 &= ~_BV(ADC3D);   // disable analog input on PB3
109
110         power_adc_disable();
111 }
112
113 static void adc_start_measurement()
114 {
115         ADCSRA |= _BV(ADSC);
116 }
117
118 ISR(ADC_vect)
119 {
120         uint16_t adcw = ADCW;
121
122         if (adc_drop) {
123                 adc_drop--;
124                 ADCSRA |= _BV(ADSC);
125                 return;
126         }
127
128         // TODO: We may want to disable ADC after here to save power,
129         // but compared to the heater power it would be negligible,
130         // so don't bother with it.
131         if (adc_type == 0) {
132                 if (batt_off) {
133                         batt_off += adcw - (batt_off >> ADC_RUNAVG_SHIFT);
134                 } else {
135                         batt_off = adcw << ADC_RUNAVG_SHIFT;
136                 }
137         } else {
138                 if (batt_on) {
139                         batt_on += adcw - (batt_on >> ADC_RUNAVG_SHIFT);
140                 } else {
141                         batt_on = adcw << ADC_RUNAVG_SHIFT;
142                 }
143         }
144 }
145
146 /* ===================== Timer/Counter1 for PWM ===================== */
147 static void pwm_init()
148 {
149         power_timer1_enable();
150
151         DDRB |= _BV(PB4);
152
153         // TCCR1 = _BV(CS10); // clk/1 = 1 MHz
154         TCCR1 = _BV(CS11) | _BV(CS13); // clk/512 = 2 kHz
155         GTCCR = _BV(COM1B1) | _BV(PWM1B);
156         OCR1C = 255;
157         // OCR1B = steps[0];
158         OCR1B = 0;
159         TIMSK = _BV(OCIE1B) | _BV(TOIE1);
160 }
161
162 static void pwm_susp()
163 {
164         TCCR1 = 0;
165 }
166
167 ISR(TIM1_OVF_vect)
168 {
169         adc_drop = 2;
170         adc_type = 1;
171         adc_start_measurement();
172 }
173
174 ISR(TIM1_COMPB_vect)
175 {
176         adc_drop = 2;
177         adc_type = 0;
178         adc_start_measurement();
179 }
180
181 static void pwm_set(unsigned char pwm)
182 {
183         OCR1B = pwm;
184 }
185
186 /* ===================== Status LED on pin PB2 ======================= */
187 static void status_led_init()
188 {
189         DDRB |= _BV(PB2);
190         PORTB &= ~_BV(PB2);
191 }
192
193 static void status_led_on()
194 {
195         PORTB |= _BV(PB2);
196 }
197
198 static void status_led_off()
199 {
200         PORTB &= ~_BV(PB2);
201 }
202
203 static unsigned char status_led_is_on()
204 {
205         return PORTB & _BV(PB2) ? 1 : 0;
206 }
207
208 /* ================== Buttons on pin PB0 and PB1 ===================== */
209 static void buttons_init()
210 {
211         DDRB &= ~(_BV(PB0) | _BV(PB1)); // set as input
212         PORTB |= _BV(PB0) | _BV(PB1);   // internal pull-up
213
214         GIMSK &= ~_BV(PCIE); // disable pin-change IRQs
215         PCMSK = 0; // disable pin-change IRQs on all pins of port B
216 }
217
218 static void buttons_susp()
219 {
220         buttons_init();
221
222         GIMSK |= _BV(PCIE);
223         PCMSK |= _BV(PCINT0) | _BV(PCINT1);
224 }
225
226 static unsigned char buttons_pressed()
227 {
228         return (
229                 (PINB & _BV(PB0) ? 0 : 1)
230                 |
231                 (PINB & _BV(PB1) ? 0 : 2)
232         );
233 }
234
235 static unsigned char buttons_wait_for_release()
236 {
237         uint16_t wake_count = 0;
238
239         do {
240                 if (++wake_count > WAKEUP_LIMIT)
241                         status_led_on(); // inform the user
242
243                 _delay_ms(WAKEUP_POLL);
244         } while (buttons_pressed());
245
246         status_led_off();
247
248         return wake_count > WAKEUP_LIMIT;
249 }
250
251 ISR(PCINT0_vect)
252 {
253         // empty - let it wake us from sleep, but do nothing else
254 }
255
256 /* ==== Watchdog Timer for timing blinks and other periodic tasks ==== */
257 static void wdt_init()
258 {
259         next_clock_tick = 0;
260         jiffies = 0;
261         WDTCR = _BV(WDIE) | _BV(WDP1); // interrupt mode, 64 ms
262 }
263
264 static void wdt_susp()
265 {
266         wdt_disable();
267 }
268
269 ISR(WDT_vect) {
270         next_clock_tick = 1;
271         jiffies++;
272 }
273
274 /* ====== Hardware init, teardown, powering down and waking up ====== */
275 static void hw_setup()
276 {
277         power_all_disable();
278
279         pwm_init();
280         adc_init();
281         status_led_init();
282         wdt_init();
283 }
284
285 static void hw_suspend()
286 {
287         adc_susp();
288         pwm_susp();
289         status_led_init(); // we don't have a separate _susp() here
290         buttons_susp();
291         wdt_susp();
292
293         power_all_disable();
294 }
295
296 static void power_down()
297 {
298         hw_suspend();
299
300         do {
301                 // G'night
302                 set_sleep_mode(SLEEP_MODE_PWR_DOWN);
303                 sleep_enable();
304                 sleep_bod_disable();
305                 sei();
306                 sleep_cpu();
307
308                 // G'morning
309                 cli();
310                 sleep_disable();
311
312                 // allow wakeup by long button-press only
313         } while (!buttons_wait_for_release());
314
315         // OK, wake up now
316         hw_setup();
317 }
318
319 /* ======== Button press detection and  handling ===================== */
320 static void button_one_pressed()
321 {
322         if (intensity > 0) {
323                 pwm_set(steps[--intensity]);
324         } else {
325                 power_down();
326         }
327 }
328
329 static void button_two_pressed()
330 {
331         if (intensity < N_STEPS-1) {
332                 pwm_set(steps[++intensity]);
333         }
334 }
335
336 static unsigned char button_state, button_state_time;
337
338 static void timer_check_buttons()
339 {
340         unsigned char newstate = buttons_pressed();
341
342         if (newstate == button_state) {
343                 if (newstate && button_state_time < 4)
344                         ++button_state_time;
345                 return;
346         }
347
348         if (newstate) {
349                 button_state = newstate;
350                 button_state_time = 0;
351                 return;
352         }
353
354         // just released
355         switch (button_state) {
356         case 1: button_one_pressed();
357                 break;
358         case 2: button_two_pressed();
359                 break;
360         default: // ignore when both are preseed
361                 break;
362         }
363
364         button_state = newstate;
365 }
366
367 /* ============ Status LED blinking =================================== */
368 static unsigned char blink_on_time, blink_off_time, n_blinks;
369 static unsigned char blink_counter;
370
371 static unsigned char battery_level()
372 {
373         unsigned char i, adc8;
374
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;
378
379         for (i = 0; i < BATT_N_LEVELS; i++)
380                 if (batt_levels[i] > adc8)
381                         break;
382
383         return i;
384 }
385
386 static void status_led_next_pattern()
387 {
388
389         // for now, display the selected intensity
390         // n_blinks = intensity + 1;
391         n_blinks = battery_level() + 1;
392         blink_on_time = 0;
393         blink_off_time = 2;
394         blink_counter = 10;
395 }
396
397 static void timer_blink()
398 {
399         if (blink_counter) {
400                 blink_counter--;
401         } else if (status_led_is_on()) {
402                 status_led_off();
403                 blink_counter = blink_off_time;
404         } else if (n_blinks) {
405                 --n_blinks;
406                 status_led_on();
407                 blink_counter = blink_on_time;
408         } else {
409                 status_led_next_pattern();
410         }
411 }
412
413 int main()
414 {
415         log_init();
416
417 #if 0
418         log_word(batt_levels[0]);
419         log_word(batt_levels[1]);
420         log_word(batt_levels[2]);
421         log_flush();
422 #endif
423
424         power_down();
425
426         sei();
427
428         // we try to be completely IRQ-driven, so just wait for IRQs here
429         while(1) {
430                 cli();
431                 set_sleep_mode(SLEEP_MODE_IDLE);
432                 sleep_enable();
433                 // keep BOD active, no sleep_bod_disable();
434                 sei();
435                 sleep_cpu();
436                 sleep_disable();
437
438                 // FIXME: Maybe handle new ADC readings as well?
439                 if (next_clock_tick) {
440                         next_clock_tick = 0;
441                         timer_check_buttons();
442                         timer_blink();
443                         if ((jiffies & 0x0F) == 0) {
444                                 unsigned char i;
445
446                                 for (i = 0; i < BATT_N_LEVELS; i++)
447                                         if (batt_levels[i] > batt_off)
448                                                 break;
449
450 #if 0
451                                 log_byte(0xcc);
452                                 log_byte(i);
453                                 log_byte(batt_off >> 8);
454                                 log_byte(batt_on >> 8);
455 #endif
456                         }
457                         log_flush();
458                 }
459         }
460 }