]> www.fi.muni.cz Git - heater.git/blob - firmware/main.c
d35fb21cf91a1d76643298fa0b12dd90c109b78a
[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  * 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 /* 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
66
67 /*
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.
72  */
73 #define ADC_1100MV_VALUE        1071    // measured, not exactly 1100
74 #define MV_TO_ADC8(mV)  ((unsigned char)(((uint32_t)(1UL << ADC_RUNAVG_SHIFT) \
75                                 * (1024UL * (mV)) \
76                                 / (6UL * ADC_1100MV_VALUE)) >> 8))
77 static unsigned char batt_levels[] = {
78         MV_TO_ADC8(3350),
79         MV_TO_ADC8(3700),
80         MV_TO_ADC8(3900),
81 };
82 #define BATT_N_LEVELS   (sizeof(batt_levels) / sizeof(batt_levels[0]))
83
84 /* output power and PWM calculation */
85 #define PWM_TOP 255
86 #define PWM_MAX (PWM_TOP - 8)   // to allow for ADC "batt_off" measurements
87
88 /*
89  * The values in power_levels[] array are voltages at which the load
90  * would give the expected power (we don't have sqrt() function,
91  * so we cannot use mW values directly. They can be calculated as
92  * voltage[V] = sqrt(load_resistance[Ohm] * expected_power[W])
93  * or
94  * voltage[mV] = sqrt(load_resistance[mOhm] * expected_power[mW])
95  *
96  * I use 1.25 W as minimum power, each step is sqrt(2)*previous_step,
97  * so the 5th step is 5 W.
98  */
99 static unsigned char power_levels[] = {
100         MV_TO_ADC8(1581),       // 1250 mW for 2 Ohm load
101         MV_TO_ADC8(1880),       // 1768 mW for 2 Ohm load
102         MV_TO_ADC8(2236),       // 2500 mW for 2 Ohm load
103         MV_TO_ADC8(2659),       // 3536 mW for 2 Ohm load
104         MV_TO_ADC8(3162),       // 5000 mW for 2 Ohm load
105 };
106 #define N_POWER_LEVELS  (sizeof(power_levels) / sizeof(power_levels[0]))
107
108 static unsigned char power_level = 0; // selected power level
109
110 /* timing by WDT */
111 static volatile unsigned char jiffies, next_clock_tick;
112
113 /* button press duration (in jiffies) */
114 #define BUTTON_SHORT_MIN        1
115 #define BUTTON_LONG_MIN         10
116
117 /* ========= Analog to Digital Converter (battery voltage) ========== */
118 static void adc_init()
119 {
120         power_adc_enable();
121
122         ADCSRA = _BV(ADEN)                      // enable
123                 | _BV(ADPS1) | _BV(ADPS0)       // clk/8 = 125 kHz
124                 | _BV(ADIE);                    // enable IRQ
125         ADMUX = _BV(REFS1) | _BV(MUX1) | _BV(MUX0);
126                 // 1.1V reference, PB3 pin, single-ended
127         DIDR0 |= _BV(ADC3D);    // PB3 pin as analog input
128 }
129
130 static void adc_susp()
131 {
132         ADCSRA &= ~_BV(ADEN);   // disable ADC
133         DIDR0 &= ~_BV(ADC3D);   // disable analog input on PB3
134
135         power_adc_disable();
136 }
137
138 static void adc_start_measurement()
139 {
140         ADCSRA |= _BV(ADSC);
141 }
142
143 ISR(ADC_vect)
144 {
145         uint16_t adcw = ADCW;
146
147         if (adc_drop) {
148                 adc_drop--;
149                 ADCSRA |= _BV(ADSC);
150                 return;
151         }
152
153         // TODO: We may want to disable ADC after here to save power,
154         // but compared to the heater power it would be negligible,
155         // so don't bother with it.
156         if (adc_type == 0) {
157                 if (batt_off) {
158                         batt_off += adcw - (batt_off >> ADC_RUNAVG_SHIFT);
159                 } else {
160                         batt_off = adcw << ADC_RUNAVG_SHIFT;
161                 }
162         } else {
163                 if (batt_on) {
164                         batt_on += adcw - (batt_on >> ADC_RUNAVG_SHIFT);
165                 } else {
166                         batt_on = adcw << ADC_RUNAVG_SHIFT;
167                 }
168         }
169 }
170
171 /* ===================== Timer/Counter1 for PWM ===================== */
172 static void pwm_init()
173 {
174         power_timer1_enable();
175
176         DDRB |= _BV(PB4);
177
178         // TCCR1 = _BV(CS10); // clk/1 = 1 MHz
179         TCCR1 = _BV(CS11) | _BV(CS13); // clk/512 = 2 kHz
180         GTCCR = _BV(COM1B1) | _BV(PWM1B);
181         OCR1C = PWM_TOP;
182         // OCR1B = steps[0];
183         OCR1B = 0;
184         TIMSK = _BV(OCIE1B) | _BV(TOIE1);
185 }
186
187 static void pwm_susp()
188 {
189         TCCR1 = 0;
190 }
191
192 ISR(TIM1_OVF_vect)
193 {
194         adc_drop = 2;
195         adc_type = 1;
196         adc_start_measurement();
197 }
198
199 ISR(TIM1_COMPB_vect)
200 {
201         adc_drop = 2;
202         adc_type = 0;
203         adc_start_measurement();
204 }
205
206 static void pwm_set(unsigned char pwm)
207 {
208         OCR1B = pwm;
209 }
210
211 /* ===================== Status LED on pin PB2 ======================= */
212 static void status_led_init()
213 {
214         DDRB |= _BV(PB2);
215         PORTB &= ~_BV(PB2);
216 }
217
218 static void status_led_on()
219 {
220         PORTB |= _BV(PB2);
221 }
222
223 static void status_led_off()
224 {
225         PORTB &= ~_BV(PB2);
226 }
227
228 static unsigned char status_led_is_on()
229 {
230         return PORTB & _BV(PB2) ? 1 : 0;
231 }
232
233 /* ================== Buttons on pin PB0 and PB1 ===================== */
234 static void buttons_init()
235 {
236         DDRB &= ~(_BV(PB0) | _BV(PB1)); // set as input
237         PORTB |= _BV(PB0) | _BV(PB1);   // internal pull-up
238
239         GIMSK &= ~_BV(PCIE); // disable pin-change IRQs
240         PCMSK = 0; // disable pin-change IRQs on all pins of port B
241 }
242
243 static void buttons_susp()
244 {
245         buttons_init();
246
247         GIMSK |= _BV(PCIE);
248         PCMSK |= _BV(PCINT0) | _BV(PCINT1);
249 }
250
251 static unsigned char buttons_pressed()
252 {
253         return (
254                 (PINB & _BV(PB0) ? 0 : 1)
255                 |
256                 (PINB & _BV(PB1) ? 0 : 2)
257         );
258 }
259
260 static unsigned char buttons_wait_for_release()
261 {
262         uint16_t wake_count = 0;
263
264         do {
265                 if (++wake_count > WAKEUP_LIMIT)
266                         status_led_on(); // inform the user
267
268                 _delay_ms(WAKEUP_POLL);
269         } while (buttons_pressed());
270
271         status_led_off();
272
273         return wake_count > WAKEUP_LIMIT;
274 }
275
276 ISR(PCINT0_vect)
277 {
278         // empty - let it wake us from sleep, but do nothing else
279 }
280
281 /* ==== Watchdog Timer for timing blinks and other periodic tasks ==== */
282 static void wdt_init()
283 {
284         next_clock_tick = 0;
285         jiffies = 0;
286         WDTCR = _BV(WDIE) | _BV(WDP1); // interrupt mode, 64 ms
287 }
288
289 static void wdt_susp()
290 {
291         wdt_disable();
292 }
293
294 ISR(WDT_vect) {
295         next_clock_tick = 1;
296         jiffies++;
297 }
298
299 /* ====== Hardware init, teardown, powering down and waking up ====== */
300 static void hw_setup()
301 {
302         power_all_disable();
303
304         pwm_init();
305         adc_init();
306         status_led_init();
307         wdt_init();
308 }
309
310 static void hw_suspend()
311 {
312         adc_susp();
313         pwm_susp();
314         status_led_init(); // we don't have a separate _susp() here
315         buttons_susp();
316         wdt_susp();
317
318         power_all_disable();
319 }
320
321 static void power_down()
322 {
323         hw_suspend();
324
325         do {
326                 // G'night
327                 set_sleep_mode(SLEEP_MODE_PWR_DOWN);
328                 sleep_enable();
329                 sleep_bod_disable();
330                 sei();
331                 sleep_cpu();
332
333                 // G'morning
334                 cli();
335                 sleep_disable();
336
337                 // allow wakeup by long button-press only
338         } while (!buttons_wait_for_release());
339
340         // OK, wake up now
341         hw_setup();
342 }
343
344 /* ======== Button press detection and  handling ===================== */
345 static void button_pressed(unsigned char button, unsigned char long_press)
346 {
347         // ignore simlultaneous button 1 and 2 press
348         if (long_press) {
349                 if (button == 1) {
350                         power_down();
351                 } else if (button == 2) {
352                         power_level = N_POWER_LEVELS-1;
353                 }
354         } else { // short press
355                 if (button == 1) {
356                         if (power_level > 0) {
357                                 --power_level;
358                         } else {
359                                 power_down();
360                         }
361                 } else if (button == 2) {
362                         if (power_level < N_POWER_LEVELS-1) {
363                                 ++power_level;
364                         }
365                 }
366         }
367 }
368
369 static unsigned char button_state, button_state_time;
370
371 static void timer_check_buttons()
372 {
373         unsigned char newstate = buttons_pressed();
374
375         if (newstate == button_state) {
376                 if (newstate && button_state_time < BUTTON_LONG_MIN)
377                         ++button_state_time;
378
379                 if (newstate && button_state_time >= BUTTON_LONG_MIN) {
380                         status_led_on();
381                 }
382                 return;
383         }
384
385         if (newstate) {
386                 button_state = newstate;
387                 button_state_time = 0;
388                 return;
389         }
390
391         // just released
392         if (button_state_time >= BUTTON_SHORT_MIN)
393                 button_pressed(button_state,
394                         button_state_time >= BUTTON_LONG_MIN ? 1 : 0);
395
396         button_state = newstate;
397         button_state_time = 0;
398 }
399
400 /* ============ Status LED blinking =================================== */
401 static unsigned char blink_on_time, blink_off_time, n_blinks;
402 static unsigned char blink_counter;
403
404 static unsigned char battery_level()
405 {
406         unsigned char i, adc8;
407
408         // NOTE: we use 8-bit value only, so we don't need lock to protect
409         // us against concurrently running ADC IRQ handler:
410         adc8 = batt_off >> 8;
411
412         for (i = 0; i < BATT_N_LEVELS; i++)
413                 if (batt_levels[i] > adc8)
414                         break;
415
416         return i;
417 }
418
419 static void status_led_next_pattern()
420 {
421
422         // for now, display the selected intensity
423         // n_blinks = power_level + 1;
424         n_blinks = battery_level() + 1;
425         blink_on_time = 0;
426         blink_off_time = 2;
427         blink_counter = 10;
428 }
429
430 static void timer_blink()
431 {
432         if (blink_counter) {
433                 blink_counter--;
434         } else if (status_led_is_on()) {
435                 status_led_off();
436                 blink_counter = blink_off_time;
437         } else if (n_blinks) {
438                 --n_blinks;
439                 status_led_on();
440                 blink_counter = blink_on_time;
441         } else {
442                 status_led_next_pattern();
443         }
444 }
445
446 static void calculate_power_level()
447 {
448         uint32_t pwm;
449         unsigned char batt_on8;
450
451         if (battery_level() == 0 || batt_on == 0) {
452                 pwm_set(0);
453                 // TODO power_down() after some time
454                 return;
455         }
456
457         batt_on8 = batt_on >> 8;
458
459         pwm = (uint32_t)PWM_TOP * power_levels[power_level]
460                 * power_levels[power_level];
461         pwm /= (uint32_t)batt_on8 * batt_on8;
462
463         if (pwm > PWM_MAX)
464                 pwm = PWM_MAX;
465
466         log_byte(0x10 + power_level);
467         log_byte(batt_on8);
468         log_byte(pwm & 0xFF);
469
470         pwm_set(pwm);
471 }
472
473 int main()
474 {
475         log_init();
476
477 #if 0
478         log_word(batt_levels[0]);
479         log_word(batt_levels[1]);
480         log_word(batt_levels[2]);
481         log_flush();
482 #endif
483         log_byte(power_levels[0]);
484         log_byte(power_levels[4]);
485         log_flush();
486
487         power_down();
488
489         sei();
490
491         // we try to be completely IRQ-driven, so just wait for IRQs here
492         while(1) {
493                 cli();
494                 set_sleep_mode(SLEEP_MODE_IDLE);
495                 sleep_enable();
496                 // keep BOD active, no sleep_bod_disable();
497                 sei();
498                 sleep_cpu();
499                 sleep_disable();
500
501                 // FIXME: Maybe handle new ADC readings as well?
502                 if (next_clock_tick) {
503                         next_clock_tick = 0;
504                         timer_blink();
505                         // this has to be after the timer_blink() call
506                         // to override the status LED during long button press
507                         timer_check_buttons();
508
509                         if ((jiffies & 0x0F) == 0) {
510                                 calculate_power_level();
511 #if 0
512                                 log_byte(0xcc);
513                                 log_byte(i);
514                                 log_byte(batt_off >> 8);
515                                 log_byte(batt_on >> 8);
516 #endif
517                         }
518                         log_flush();
519                 }
520         }
521 }