]> www.fi.muni.cz Git - heater.git/blob - firmware/main.c
95cf70aaf02f9dca561e08d34b55bb856aefc964
[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  * When running, the "-" button is used for decreasing the output power,
25  * the "+" button is for increasing it.
26  * Any long button press switches the system off.
27  *
28  * Status LED:
29  * When powering up by a button press, the LED goes on to provide a visual
30  * feedback, and is switched off after the button is released.
31  * It displays the current power level and current battery voltage
32  * using # of blinks with different blinking lengths.
33  * When the battery is completely exhausted, the output power is switched
34  * off, the LED keeps blinking for some time, and then the whole system is
35  * switched off to avoid deep discharge of the battery.
36  *
37  * Timing:
38  * The firmware is timed by the Watchdog Timer interrupt. Most of the
39  * processing is done from the main loop, IRQs only set various flags
40  * or trigger other events.
41  */
42
43 #include <avr/interrupt.h>
44 #include <avr/io.h>
45 #include <avr/power.h>
46 #include <avr/sleep.h>
47 #include <avr/wdt.h>
48 #include <util/delay.h>
49
50 #include "logging.h"
51
52 /* waking up from the power down state by a button press */
53 #define WAKEUP_POLL 50  // msec
54 #define WAKEUP_LIMIT 5  // times WAKEUP_POLL
55
56 // #define BUTTONS_REVERSE
57
58 #ifdef BUTTONS_REVERSE
59 #       define BUTTON1  PB0
60 #       define BUTTON2  PB1
61 #else
62 #       define BUTTON1  PB1
63 #       define BUTTON2  PB0
64 #endif /* !BUTTONS_REVERSE */
65
66 /* which state (output on or output off) are we measuring now */
67 static volatile unsigned char adc_type, adc_drop;
68 #define ADC_RUNAVG_SHIFT 5      // running average shift on batt_on, batt_off
69 static volatile uint16_t batt_on, batt_off; // measured voltage
70
71 /*
72  * The voltage divider has 1M5 and 300K resistors (i.e. it measures 1/6th of
73  * the real voltage), ADC uses 1.1V internal reference.
74  * Macro to calculate upper eight bits of the ADC running-averaged value
75  * from the voltage in milivolts.
76  */
77 #define ADC_1100MV_VALUE        1071    // measured, not exactly 1100
78 #define MV_TO_ADC8(mV)  ((unsigned char)(((uint32_t)(1UL << ADC_RUNAVG_SHIFT) \
79                                 * (1024UL * (mV)) \
80                                 / (6UL * ADC_1100MV_VALUE)) >> 8))
81 static unsigned char batt_levels[] = {
82         MV_TO_ADC8(3350),
83         MV_TO_ADC8(3700),
84         MV_TO_ADC8(3900),
85 };
86 #define BATT_N_LEVELS   (sizeof(batt_levels) / sizeof(batt_levels[0]))
87
88 /* output power and PWM calculation */
89 #define PWM_TOP 255
90 #define PWM_MAX (PWM_TOP - 8)   // to allow for ADC "batt_off" measurements
91 #define PWM_MIN 8               // to allow for ADC "batt_on" measurements
92
93 /*
94  * The values in power_levels[] array are voltages at which the load
95  * would give the expected power (we don't have sqrt() function,
96  * so we cannot use mW values directly. They can be calculated as
97  * voltage[V] = sqrt(load_resistance[Ohm] * expected_power[W])
98  * or
99  * voltage[mV] = sqrt(load_resistance[mOhm] * expected_power[mW])
100  *
101  * I use 1.25 W as minimum power, each step is sqrt(2)*previous_step,
102  * so the 5th step is 5 W.
103  */
104 static unsigned char power_levels[] = {
105         MV_TO_ADC8(1581),       // 1250 mW for 2 Ohm load
106         MV_TO_ADC8(1880),       // 1768 mW for 2 Ohm load
107         MV_TO_ADC8(2236),       // 2500 mW for 2 Ohm load
108         MV_TO_ADC8(2659),       // 3536 mW for 2 Ohm load
109         MV_TO_ADC8(3162),       // 5000 mW for 2 Ohm load
110 };
111 #define N_POWER_LEVELS  (sizeof(power_levels) / sizeof(power_levels[0]))
112
113 static unsigned char power_level = 0; // selected power level
114
115 #define LED_BATTEMPTY_COUNT     60
116
117 /* timing by WDT */
118 static volatile unsigned char jiffies, next_clock_tick;
119
120 /* button press duration (in jiffies) */
121 #define BUTTON_SHORT_MIN        1
122 #define BUTTON_LONG_MIN         10
123
124
125 /* ========= Analog to Digital Converter (battery voltage) ========== */
126 static void adc_init()
127 {
128         power_adc_enable();
129
130         ADCSRA = _BV(ADEN)                      // enable
131                 | _BV(ADPS1) | _BV(ADPS0);      // clk/8 = 125 kHz
132         ADMUX = _BV(REFS1) | _BV(MUX1) | _BV(MUX0);
133                 // 1.1V reference, PB3 pin, single-ended
134         DIDR0 |= _BV(ADC3D);    // PB3 pin as analog input
135 }
136
137 static void adc_susp()
138 {
139         ADCSRA = 0;             // disable ADC
140         DIDR0 &= ~_BV(ADC3D);   // disable analog input on PB3
141
142         power_adc_disable();
143 }
144
145 static void adc_start_measurement(unsigned char on)
146 {
147         adc_drop = 1;
148         adc_type = on;
149         ADCSRA |= _BV(ADSC) | _BV(ADIE);
150 }
151
152 ISR(ADC_vect)
153 {
154         uint16_t adcw = ADCW;
155
156         if (adc_drop) {
157                 adc_drop--;
158                 ADCSRA |= _BV(ADSC);
159                 return;
160         }
161
162         // TODO: We may want to disable ADC after here to save power,
163         // but compared to the heater power it would be negligible,
164         // so don't bother with it.
165         if (adc_type == 0) {
166                 if (batt_off) {
167                         batt_off += adcw - (batt_off >> ADC_RUNAVG_SHIFT);
168                 } else {
169                         batt_off = adcw << ADC_RUNAVG_SHIFT;
170                 }
171         } else {
172                 if (batt_on) {
173                         batt_on += adcw - (batt_on >> ADC_RUNAVG_SHIFT);
174                 } else {
175                         batt_on = adcw << ADC_RUNAVG_SHIFT;
176                 }
177         }
178         ADCSRA &= ~_BV(ADIE);
179 }
180
181 /* ===================== Timer/Counter1 for PWM ===================== */
182 static void pwm_init()
183 {
184         power_timer1_enable();
185
186         DDRB |= _BV(PB4);
187         PORTB &= ~_BV(PB4);
188
189         // TCCR1 = _BV(CS10); // clk/1 = 1 MHz
190         // TCCR1 = _BV(CS11) | _BV(CS13); // clk/512 = 2 kHz
191         /*
192          * clk/64 = 16 kHz. We use PWM_MIN and PWM_MAX, so we have at least
193          * 8 full T/C1 cycles to do two ADC measurements. The ADC with 125 kHz
194          * clock can do about 7000-9000 measurement per second, so we should
195          * be safe both on low and high OCR1B values with this clock
196          */
197         TCCR1 = _BV(CS12) | _BV(CS11) | _BV(CS10);
198
199         GTCCR = _BV(COM1B1) | _BV(PWM1B);
200         OCR1C = PWM_TOP;
201         // OCR1B = steps[0];
202         OCR1B = 0;
203         TIMSK = _BV(OCIE1B) | _BV(TOIE1);
204 }
205
206 static void pwm_susp()
207 {
208         TCCR1 = 0;
209         TIMSK = 0;
210         GTCCR = 0;
211         PORTB &= ~_BV(PB4);
212 }
213
214 ISR(TIM1_OVF_vect)
215 {
216         adc_start_measurement(1);
217 }
218
219 ISR(TIM1_COMPB_vect)
220 {
221         adc_start_measurement(0);
222 }
223
224 static void pwm_set(unsigned char pwm)
225 {
226         OCR1B = pwm;
227 }
228
229 /* ===================== Status LED on pin PB2 ======================= */
230 static void status_led_init()
231 {
232         DDRB |= _BV(PB2);
233         PORTB &= ~_BV(PB2);
234 }
235
236 static void status_led_on()
237 {
238         PORTB |= _BV(PB2);
239 }
240
241 static void status_led_off()
242 {
243         PORTB &= ~_BV(PB2);
244 }
245
246 static unsigned char status_led_is_on()
247 {
248         return PORTB & _BV(PB2) ? 1 : 0;
249 }
250
251 /* ================== Buttons on pin PB0 and PB1 ===================== */
252 static void buttons_init()
253 {
254         DDRB &= ~(_BV(PB0) | _BV(PB1)); // set as input
255         PORTB |= _BV(PB0) | _BV(PB1);   // internal pull-up
256
257         GIMSK &= ~_BV(PCIE); // disable pin-change IRQs
258         PCMSK = 0; // disable pin-change IRQs on all pins of port B
259 }
260
261 static void buttons_susp()
262 {
263         buttons_init();
264
265         GIMSK |= _BV(PCIE);
266         PCMSK |= _BV(PCINT0) | _BV(PCINT1);
267 }
268
269 static unsigned char buttons_pressed()
270 {
271         return (
272                 (PINB & _BV(BUTTON1) ? 0 : 1)
273                 |
274                 (PINB & _BV(BUTTON2) ? 0 : 2)
275         );
276 }
277
278 static unsigned char buttons_wait_for_release()
279 {
280         uint16_t wake_count = 0;
281
282         do {
283                 if (++wake_count > WAKEUP_LIMIT)
284                         status_led_on(); // inform the user
285
286                 _delay_ms(WAKEUP_POLL);
287         } while (buttons_pressed());
288
289         status_led_off();
290
291         return wake_count > WAKEUP_LIMIT;
292 }
293
294 ISR(PCINT0_vect)
295 {
296         // empty - let it wake us from sleep, but do nothing else
297 }
298
299 /* ==== Watchdog Timer for timing blinks and other periodic tasks ==== */
300 static void wdt_init()
301 {
302         next_clock_tick = 0;
303         jiffies = 0;
304         WDTCR = _BV(WDIE) | _BV(WDP1); // interrupt mode, 64 ms
305 }
306
307 static void wdt_susp()
308 {
309         wdt_disable();
310 }
311
312 ISR(WDT_vect) {
313         next_clock_tick = 1;
314         jiffies++;
315 }
316
317 /* ====== Hardware init, teardown, powering down and waking up ====== */
318 static void hw_setup()
319 {
320         power_all_disable();
321
322         pwm_init();
323         adc_init();
324         status_led_init();
325         wdt_init();
326 }
327
328 static void hw_suspend()
329 {
330         adc_susp();
331         pwm_susp();
332         status_led_init(); // we don't have a separate _susp() here
333         buttons_susp();
334         wdt_susp();
335
336         power_all_disable();
337 }
338
339 static void power_down()
340 {
341         hw_suspend();
342
343         do {
344                 // G'night
345                 set_sleep_mode(SLEEP_MODE_PWR_DOWN);
346                 sleep_enable();
347                 sleep_bod_disable();
348                 sei();
349                 sleep_cpu();
350
351                 // G'morning
352                 cli();
353                 sleep_disable();
354
355                 // allow wakeup by long button-press only
356         } while (!buttons_wait_for_release());
357
358         // OK, wake up now
359         hw_setup();
360 }
361
362 /* ============ Status LED blinking =================================== */
363 static unsigned char blink_on_time, blink_off_time, n_blinks;
364 static unsigned char blink_counter;
365
366 static unsigned char battery_level()
367 {
368         unsigned char i, adc8;
369
370         // NOTE: we use 8-bit value only, so we don't need lock to protect
371         // us against concurrently running ADC IRQ handler:
372         adc8 = batt_off >> 8;
373
374         for (i = 0; i < BATT_N_LEVELS; i++)
375                 if (batt_levels[i] > adc8)
376                         break;
377
378         return i;
379 }
380
381 static void status_led_next_pattern()
382 {
383         static unsigned char battery_exhausted;
384         static unsigned char display_power_level;
385
386         if (display_power_level) {
387                 n_blinks = power_level + 1;
388                 if (batt_on >> 8 == batt_off >> 8) { // load unplugged
389                         n_blinks = 2 * n_blinks;
390                         blink_on_time = 0;
391                         blink_off_time = 0;
392                 } else {
393                         blink_on_time = 2;
394                         blink_off_time = 2;
395                 }
396         } else {
397                 unsigned char b_level = battery_level();
398                 if (b_level) {
399                         battery_exhausted = 0;
400                 } else if (battery_exhausted) {
401                         if (!--battery_exhausted)
402                                 power_down();
403                 } else {
404                         battery_exhausted = LED_BATTEMPTY_COUNT;
405                 }
406
407                 n_blinks = b_level + 1;
408                 blink_on_time = 4;
409                 blink_off_time = 0;
410         }
411
412         blink_counter = 12;
413         display_power_level = !display_power_level;
414 }
415
416 static void timer_blink()
417 {
418         if (blink_counter) {
419                 blink_counter--;
420         } else if (!status_led_is_on()) {
421                 status_led_on();
422                 blink_counter = blink_on_time;
423         } else if (n_blinks) {
424                 --n_blinks;
425                 status_led_off();
426                 blink_counter = blink_off_time;
427         } else {
428                 status_led_next_pattern();
429         }
430 }
431
432 /* ======== Button press detection and  handling ===================== */
433 static void button_pressed(unsigned char button, unsigned char long_press)
434 {
435         // ignore simlultaneous button 1 and 2 press
436         if (long_press) {
437                 power_down();
438                 return;
439         } else { // short press
440                 if (button == 1) {
441                         if (power_level > 0) {
442                                 --power_level;
443                         }
444                 } else if (button == 2) {
445                         if (power_level < N_POWER_LEVELS-1) {
446                                 ++power_level;
447                         }
448                 }
449         }
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 }