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