]> www.fi.muni.cz Git - heater.git/blob - firmware/main.c
0d45ac93d9a6429bc040486f173f93a2f7d9b0bc
[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                 blink_on_time = 1;
394                 blink_off_time = 2;
395         } else {
396                 unsigned char b_level = battery_level();
397                 if (b_level) {
398                         battery_exhausted = 0;
399                 } else if (battery_exhausted) {
400                         if (!--battery_exhausted)
401                                 power_down();
402                 } else {
403                         battery_exhausted = LED_BATTEMPTY_COUNT;
404                 }
405
406                 n_blinks = b_level + 1;
407                 blink_on_time = 3;
408                 blink_off_time = 0;
409         }
410
411         blink_counter = 10;
412         display_power_level = !display_power_level;
413 }
414
415 static void timer_blink()
416 {
417         if (blink_counter) {
418                 blink_counter--;
419         } else if (!status_led_is_on()) {
420                 status_led_on();
421                 blink_counter = blink_on_time;
422         } else if (n_blinks) {
423                 --n_blinks;
424                 status_led_off();
425                 blink_counter = blink_off_time;
426         } else {
427                 status_led_next_pattern();
428         }
429 }
430
431 /* ======== Button press detection and  handling ===================== */
432 static void button_pressed(unsigned char button, unsigned char long_press)
433 {
434         // ignore simlultaneous button 1 and 2 press
435         if (long_press) {
436                 if (button == 1) {
437                         power_down();
438                         return;
439                 } else if (button == 2) {
440                         power_level = N_POWER_LEVELS-1;
441                 }
442         } else { // short press
443                 if (button == 1) {
444                         if (power_level > 0) {
445                                 --power_level;
446                         } else {
447                                 power_down();
448                                 return;
449                         }
450                 } else if (button == 2) {
451                         if (power_level < N_POWER_LEVELS-1) {
452                                 ++power_level;
453                         }
454                 }
455         }
456         status_led_next_pattern();
457 }
458
459 static unsigned char button_state, button_state_time;
460
461 static void timer_check_buttons()
462 {
463         unsigned char newstate = buttons_pressed();
464
465         if (newstate == button_state) {
466                 if (newstate && button_state_time < BUTTON_LONG_MIN)
467                         ++button_state_time;
468
469                 if (newstate && button_state_time >= BUTTON_LONG_MIN) {
470                         status_led_on();
471                 }
472                 return;
473         }
474
475         if (newstate) {
476                 button_state = newstate;
477                 button_state_time = 0;
478                 return;
479         }
480
481         // just released
482         if (button_state_time >= BUTTON_SHORT_MIN)
483                 button_pressed(button_state,
484                         button_state_time >= BUTTON_LONG_MIN ? 1 : 0);
485
486         button_state = newstate;
487         button_state_time = 0;
488 }
489
490 /* ===================== Output power control ======================== */
491 static void calculate_power_level()
492 {
493         uint32_t pwm;
494         unsigned char batt_on8;
495
496         if (battery_level() == 0) {
497                 pwm_set(0);
498                 // TODO power_down() after some time
499                 return;
500         }
501
502         if (!batt_on) {
503                 batt_on = batt_off;
504         };
505
506         batt_on8 = batt_on >> 8;
507
508         pwm = (uint32_t)PWM_TOP * power_levels[power_level]
509                 * power_levels[power_level];
510         pwm /= (uint32_t)batt_on8 * batt_on8;
511
512         if (pwm > PWM_MAX)
513                 pwm = PWM_MAX;
514
515         if (pwm < PWM_MIN)
516                 pwm = PWM_MIN;
517
518 #if 0
519         log_byte(0x10 + power_level);
520         log_byte(batt_on8);
521         log_byte(pwm & 0xFF);
522 #endif
523
524         pwm_set(pwm);
525 }
526
527 int main()
528 {
529         log_init();
530
531 #if 0
532         log_word(batt_levels[0]);
533         log_word(batt_levels[1]);
534         log_word(batt_levels[2]);
535         log_flush();
536 #endif
537         log_byte(power_levels[0]);
538         log_byte(power_levels[4]);
539         log_flush();
540
541         power_down();
542
543         sei();
544
545         // we try to be completely IRQ-driven, so just wait for IRQs here
546         while(1) {
547                 cli();
548                 set_sleep_mode(SLEEP_MODE_IDLE);
549                 sleep_enable();
550                 // keep BOD active, no sleep_bod_disable();
551                 sei();
552                 sleep_cpu();
553                 sleep_disable();
554
555                 // FIXME: Maybe handle new ADC readings as well?
556                 if (next_clock_tick) {
557                         next_clock_tick = 0;
558                         timer_blink();
559                         // this has to be after the timer_blink() call
560                         // to override the status LED during long button press
561                         timer_check_buttons();
562
563                         if ((jiffies & 0x0F) == 0) {
564                                 calculate_power_level();
565 #if 0
566                                 log_byte(0xcc);
567                                 log_byte(i);
568                                 log_byte(batt_off >> 8);
569                                 log_byte(batt_on >> 8);
570 #endif
571                         }
572                         log_flush();
573                 }
574         }
575 }