]> www.fi.muni.cz Git - heater.git/blob - firmware/main.c
Detect unplugged load
[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  * It displays the current power level and current battery voltage
37  * using # of blinks with different blinking lengths.
38  * When the battery is completely exhausted, the output power is switched
39  * off, the LED keeps blinking for some time, and then the whole system is
40  * switched off to avoid deep discharge of the battery.
41  *
42  * Timing:
43  * The firmware is timed by the Watchdog Timer interrupt. Most of the
44  * processing is done from the main loop, IRQs only set various flags
45  * or trigger other events.
46  */
47
48 #include <avr/interrupt.h>
49 #include <avr/io.h>
50 #include <avr/power.h>
51 #include <avr/sleep.h>
52 #include <avr/wdt.h>
53 #include <util/delay.h>
54
55 #include "logging.h"
56
57 /* waking up from the power down state by a button press */
58 #define WAKEUP_POLL 50  // msec
59 #define WAKEUP_LIMIT 5  // times WAKEUP_POLL
60
61 // #define BUTTONS_REVERSE
62
63 #ifdef BUTTONS_REVERSE
64 #       define BUTTON1  PB0
65 #       define BUTTON2  PB1
66 #else
67 #       define BUTTON1  PB1
68 #       define BUTTON2  PB0
69 #endif /* !BUTTONS_REVERSE */
70
71 /* which state (output on or output off) are we measuring now */
72 static volatile unsigned char adc_type, adc_drop;
73 #define ADC_RUNAVG_SHIFT 5      // running average shift on batt_on, batt_off
74 static volatile uint16_t batt_on, batt_off; // measured voltage
75
76 /*
77  * The voltage divider has 1M5 and 300K resistors (i.e. it measures 1/6th of
78  * the real voltage), ADC uses 1.1V internal reference.
79  * Macro to calculate upper eight bits of the ADC running-averaged value
80  * from the voltage in milivolts.
81  */
82 #define ADC_1100MV_VALUE        1071    // measured, not exactly 1100
83 #define MV_TO_ADC8(mV)  ((unsigned char)(((uint32_t)(1UL << ADC_RUNAVG_SHIFT) \
84                                 * (1024UL * (mV)) \
85                                 / (6UL * ADC_1100MV_VALUE)) >> 8))
86 static unsigned char batt_levels[] = {
87         MV_TO_ADC8(3350),
88         MV_TO_ADC8(3700),
89         MV_TO_ADC8(3900),
90 };
91 #define BATT_N_LEVELS   (sizeof(batt_levels) / sizeof(batt_levels[0]))
92
93 /* output power and PWM calculation */
94 #define PWM_TOP 255
95 #define PWM_MAX (PWM_TOP - 8)   // to allow for ADC "batt_off" measurements
96 #define PWM_MIN 8               // to allow for ADC "batt_on" measurements
97
98 /*
99  * The values in power_levels[] array are voltages at which the load
100  * would give the expected power (we don't have sqrt() function,
101  * so we cannot use mW values directly. They can be calculated as
102  * voltage[V] = sqrt(load_resistance[Ohm] * expected_power[W])
103  * or
104  * voltage[mV] = sqrt(load_resistance[mOhm] * expected_power[mW])
105  *
106  * I use 1.25 W as minimum power, each step is sqrt(2)*previous_step,
107  * so the 5th step is 5 W.
108  */
109 static unsigned char power_levels[] = {
110         MV_TO_ADC8(1581),       // 1250 mW for 2 Ohm load
111         MV_TO_ADC8(1880),       // 1768 mW for 2 Ohm load
112         MV_TO_ADC8(2236),       // 2500 mW for 2 Ohm load
113         MV_TO_ADC8(2659),       // 3536 mW for 2 Ohm load
114         MV_TO_ADC8(3162),       // 5000 mW for 2 Ohm load
115 };
116 #define N_POWER_LEVELS  (sizeof(power_levels) / sizeof(power_levels[0]))
117
118 static unsigned char power_level = 0; // selected power level
119
120 #define LED_BATTEMPTY_COUNT     60
121
122 /* timing by WDT */
123 static volatile unsigned char jiffies, next_clock_tick;
124
125 /* button press duration (in jiffies) */
126 #define BUTTON_SHORT_MIN        1
127 #define BUTTON_LONG_MIN         10
128
129
130 /* ========= Analog to Digital Converter (battery voltage) ========== */
131 static void adc_init()
132 {
133         power_adc_enable();
134
135         ADCSRA = _BV(ADEN)                      // enable
136                 | _BV(ADPS1) | _BV(ADPS0);      // clk/8 = 125 kHz
137         ADMUX = _BV(REFS1) | _BV(MUX1) | _BV(MUX0);
138                 // 1.1V reference, PB3 pin, single-ended
139         DIDR0 |= _BV(ADC3D);    // PB3 pin as analog input
140 }
141
142 static void adc_susp()
143 {
144         ADCSRA = 0;             // disable ADC
145         DIDR0 &= ~_BV(ADC3D);   // disable analog input on PB3
146
147         power_adc_disable();
148 }
149
150 static void adc_start_measurement(unsigned char on)
151 {
152         adc_drop = 1;
153         adc_type = on;
154         ADCSRA |= _BV(ADSC) | _BV(ADIE);
155 }
156
157 ISR(ADC_vect)
158 {
159         uint16_t adcw = ADCW;
160
161         if (adc_drop) {
162                 adc_drop--;
163                 ADCSRA |= _BV(ADSC);
164                 return;
165         }
166
167         // TODO: We may want to disable ADC after here to save power,
168         // but compared to the heater power it would be negligible,
169         // so don't bother with it.
170         if (adc_type == 0) {
171                 if (batt_off) {
172                         batt_off += adcw - (batt_off >> ADC_RUNAVG_SHIFT);
173                 } else {
174                         batt_off = adcw << ADC_RUNAVG_SHIFT;
175                 }
176         } else {
177                 if (batt_on) {
178                         batt_on += adcw - (batt_on >> ADC_RUNAVG_SHIFT);
179                 } else {
180                         batt_on = adcw << ADC_RUNAVG_SHIFT;
181                 }
182         }
183         ADCSRA &= ~_BV(ADIE);
184 }
185
186 /* ===================== Timer/Counter1 for PWM ===================== */
187 static void pwm_init()
188 {
189         power_timer1_enable();
190
191         DDRB |= _BV(PB4);
192         PORTB &= ~_BV(PB4);
193
194         // TCCR1 = _BV(CS10); // clk/1 = 1 MHz
195         // TCCR1 = _BV(CS11) | _BV(CS13); // clk/512 = 2 kHz
196         /*
197          * clk/64 = 16 kHz. We use PWM_MIN and PWM_MAX, so we have at least
198          * 8 full T/C1 cycles to do two ADC measurements. The ADC with 125 kHz
199          * clock can do about 7000-9000 measurement per second, so we should
200          * be safe both on low and high OCR1B values with this clock
201          */
202         TCCR1 = _BV(CS12) | _BV(CS11) | _BV(CS10);
203
204         GTCCR = _BV(COM1B1) | _BV(PWM1B);
205         OCR1C = PWM_TOP;
206         // OCR1B = steps[0];
207         OCR1B = 0;
208         TIMSK = _BV(OCIE1B) | _BV(TOIE1);
209 }
210
211 static void pwm_susp()
212 {
213         TCCR1 = 0;
214         TIMSK = 0;
215         GTCCR = 0;
216         PORTB &= ~_BV(PB4);
217 }
218
219 ISR(TIM1_OVF_vect)
220 {
221         adc_start_measurement(1);
222 }
223
224 ISR(TIM1_COMPB_vect)
225 {
226         adc_start_measurement(0);
227 }
228
229 static void pwm_set(unsigned char pwm)
230 {
231         OCR1B = pwm;
232 }
233
234 /* ===================== Status LED on pin PB2 ======================= */
235 static void status_led_init()
236 {
237         DDRB |= _BV(PB2);
238         PORTB &= ~_BV(PB2);
239 }
240
241 static void status_led_on()
242 {
243         PORTB |= _BV(PB2);
244 }
245
246 static void status_led_off()
247 {
248         PORTB &= ~_BV(PB2);
249 }
250
251 static unsigned char status_led_is_on()
252 {
253         return PORTB & _BV(PB2) ? 1 : 0;
254 }
255
256 /* ================== Buttons on pin PB0 and PB1 ===================== */
257 static void buttons_init()
258 {
259         DDRB &= ~(_BV(PB0) | _BV(PB1)); // set as input
260         PORTB |= _BV(PB0) | _BV(PB1);   // internal pull-up
261
262         GIMSK &= ~_BV(PCIE); // disable pin-change IRQs
263         PCMSK = 0; // disable pin-change IRQs on all pins of port B
264 }
265
266 static void buttons_susp()
267 {
268         buttons_init();
269
270         GIMSK |= _BV(PCIE);
271         PCMSK |= _BV(PCINT0) | _BV(PCINT1);
272 }
273
274 static unsigned char buttons_pressed()
275 {
276         return (
277                 (PINB & _BV(BUTTON1) ? 0 : 1)
278                 |
279                 (PINB & _BV(BUTTON2) ? 0 : 2)
280         );
281 }
282
283 static unsigned char buttons_wait_for_release()
284 {
285         uint16_t wake_count = 0;
286
287         do {
288                 if (++wake_count > WAKEUP_LIMIT)
289                         status_led_on(); // inform the user
290
291                 _delay_ms(WAKEUP_POLL);
292         } while (buttons_pressed());
293
294         status_led_off();
295
296         return wake_count > WAKEUP_LIMIT;
297 }
298
299 ISR(PCINT0_vect)
300 {
301         // empty - let it wake us from sleep, but do nothing else
302 }
303
304 /* ==== Watchdog Timer for timing blinks and other periodic tasks ==== */
305 static void wdt_init()
306 {
307         next_clock_tick = 0;
308         jiffies = 0;
309         WDTCR = _BV(WDIE) | _BV(WDP1); // interrupt mode, 64 ms
310 }
311
312 static void wdt_susp()
313 {
314         wdt_disable();
315 }
316
317 ISR(WDT_vect) {
318         next_clock_tick = 1;
319         jiffies++;
320 }
321
322 /* ====== Hardware init, teardown, powering down and waking up ====== */
323 static void hw_setup()
324 {
325         power_all_disable();
326
327         pwm_init();
328         adc_init();
329         status_led_init();
330         wdt_init();
331 }
332
333 static void hw_suspend()
334 {
335         adc_susp();
336         pwm_susp();
337         status_led_init(); // we don't have a separate _susp() here
338         buttons_susp();
339         wdt_susp();
340
341         power_all_disable();
342 }
343
344 static void power_down()
345 {
346         hw_suspend();
347
348         do {
349                 // G'night
350                 set_sleep_mode(SLEEP_MODE_PWR_DOWN);
351                 sleep_enable();
352                 sleep_bod_disable();
353                 sei();
354                 sleep_cpu();
355
356                 // G'morning
357                 cli();
358                 sleep_disable();
359
360                 // allow wakeup by long button-press only
361         } while (!buttons_wait_for_release());
362
363         // OK, wake up now
364         hw_setup();
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         static unsigned char battery_exhausted;
389         static unsigned char display_power_level;
390
391         if (display_power_level) {
392                 n_blinks = power_level + 1;
393                 if (batt_on >> 8 == batt_off >> 8) { // load unplugged
394                         n_blinks = 2 * n_blinks;
395                         blink_on_time = 0;
396                         blink_off_time = 0;
397                 } else {
398                         blink_on_time = 2;
399                         blink_off_time = 2;
400                 }
401         } else {
402                 unsigned char b_level = battery_level();
403                 if (b_level) {
404                         battery_exhausted = 0;
405                 } else if (battery_exhausted) {
406                         if (!--battery_exhausted)
407                                 power_down();
408                 } else {
409                         battery_exhausted = LED_BATTEMPTY_COUNT;
410                 }
411
412                 n_blinks = b_level + 1;
413                 blink_on_time = 4;
414                 blink_off_time = 0;
415         }
416
417         blink_counter = 12;
418         display_power_level = !display_power_level;
419 }
420
421 static void timer_blink()
422 {
423         if (blink_counter) {
424                 blink_counter--;
425         } else if (!status_led_is_on()) {
426                 status_led_on();
427                 blink_counter = blink_on_time;
428         } else if (n_blinks) {
429                 --n_blinks;
430                 status_led_off();
431                 blink_counter = blink_off_time;
432         } else {
433                 status_led_next_pattern();
434         }
435 }
436
437 /* ======== Button press detection and  handling ===================== */
438 static void button_pressed(unsigned char button, unsigned char long_press)
439 {
440         // ignore simlultaneous button 1 and 2 press
441         if (long_press) {
442                 if (button == 1) {
443                         power_down();
444                         return;
445                 } else if (button == 2) {
446                         power_level = N_POWER_LEVELS-1;
447                 }
448         } else { // short press
449                 if (button == 1) {
450                         if (power_level > 0) {
451                                 --power_level;
452                         } else {
453                                 power_down();
454                                 return;
455                         }
456                 } else if (button == 2) {
457                         if (power_level < N_POWER_LEVELS-1) {
458                                 ++power_level;
459                         }
460                 }
461         }
462         status_led_next_pattern();
463 }
464
465 static unsigned char button_state, button_state_time;
466
467 static void timer_check_buttons()
468 {
469         unsigned char newstate = buttons_pressed();
470
471         if (newstate == button_state) {
472                 if (newstate && button_state_time < BUTTON_LONG_MIN)
473                         ++button_state_time;
474
475                 if (newstate && button_state_time >= BUTTON_LONG_MIN) {
476                         status_led_on();
477                 }
478                 return;
479         }
480
481         if (newstate) {
482                 button_state = newstate;
483                 button_state_time = 0;
484                 return;
485         }
486
487         // just released
488         if (button_state_time >= BUTTON_SHORT_MIN)
489                 button_pressed(button_state,
490                         button_state_time >= BUTTON_LONG_MIN ? 1 : 0);
491
492         button_state = newstate;
493         button_state_time = 0;
494 }
495
496 /* ===================== Output power control ======================== */
497 static void calculate_power_level()
498 {
499         uint32_t pwm;
500         unsigned char batt_on8;
501
502         if (battery_level() == 0) {
503                 pwm_set(0);
504                 // TODO power_down() after some time
505                 return;
506         }
507
508         if (!batt_on) {
509                 batt_on = batt_off;
510         };
511
512         batt_on8 = batt_on >> 8;
513
514         pwm = (uint32_t)PWM_TOP * power_levels[power_level]
515                 * power_levels[power_level];
516         pwm /= (uint32_t)batt_on8 * batt_on8;
517
518         if (pwm > PWM_MAX)
519                 pwm = PWM_MAX;
520
521         if (pwm < PWM_MIN)
522                 pwm = PWM_MIN;
523
524 #if 0
525         log_byte(0x10 + power_level);
526         log_byte(batt_on8);
527         log_byte(pwm & 0xFF);
528 #endif
529
530         pwm_set(pwm);
531 }
532
533 int main()
534 {
535         log_init();
536
537 #if 0
538         log_word(batt_levels[0]);
539         log_word(batt_levels[1]);
540         log_word(batt_levels[2]);
541         log_flush();
542 #endif
543         log_byte(power_levels[0]);
544         log_byte(power_levels[4]);
545         log_flush();
546
547         power_down();
548
549         sei();
550
551         // we try to be completely IRQ-driven, so just wait for IRQs here
552         while(1) {
553                 cli();
554                 set_sleep_mode(SLEEP_MODE_IDLE);
555                 sleep_enable();
556                 // keep BOD active, no sleep_bod_disable();
557                 sei();
558                 sleep_cpu();
559                 sleep_disable();
560
561                 // FIXME: Maybe handle new ADC readings as well?
562                 if (next_clock_tick) {
563                         next_clock_tick = 0;
564                         timer_blink();
565                         // this has to be after the timer_blink() call
566                         // to override the status LED during long button press
567                         timer_check_buttons();
568
569                         if ((jiffies & 0x0F) == 0) {
570                                 calculate_power_level();
571 #if 0
572                                 log_byte(0xcc);
573                                 log_byte(i);
574                                 log_byte(batt_off >> 8);
575                                 log_byte(batt_on >> 8);
576 #endif
577                         }
578                         log_flush();
579                 }
580         }
581 }