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