]> www.fi.muni.cz Git - heater.git/blob - firmware/main.c
5c9a566ffc0ea20afb54abefc0330cd0795f2a7e
[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  * TODO: 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  * TODO: 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 /* output power levels */
63 #define N_POWER_LEVELS 5
64 static unsigned char power_levels[N_POWER_LEVELS] = {
65
66 };
67
68 static unsigned char power_level = 0; // selected power level
69
70 /* which state (output on or output off) are we measuring now */
71 static volatile unsigned char adc_type, adc_drop;
72 #define ADC_RUNAVG_SHIFT 5      // running average shift on batt_on, batt_off
73 static volatile uint16_t batt_on, batt_off; // measured voltage
74
75 /*
76  * The voltage divider has 1M5 and 300K resistors (i.e. it measures 1/6th of
77  * the real voltage), ADC uses 1.1V internal reference.
78  * Macro to calculate upper eight bits of the ADC running-averaged value
79  * from the voltage in milivolts.
80  */
81 #define ADC_1100MV_VALUE        1071    // measured, not exactly 1100
82 #define MV_TO_ADC8(mV)  ((unsigned char)(((uint32_t)(1UL << ADC_RUNAVG_SHIFT) \
83                                 * (1024UL * (mV)) \
84                                 / (6UL * ADC_1100MV_VALUE)) >> 8))
85 #define BATT_N_LEVELS   3
86 static unsigned char batt_levels[BATT_N_LEVELS] = {
87         MV_TO_ADC8(3500),
88         MV_TO_ADC8(3700),
89         MV_TO_ADC8(3900),
90 };
91
92 /* timing by WDT */
93 static volatile unsigned char jiffies, next_clock_tick;
94
95 /* button press duration (in jiffies) */
96 #define BUTTON_SHORT_MIN        1
97 #define BUTTON_LONG_MIN         10
98
99 /* ========= Analog to Digital Converter (battery voltage) ========== */
100 static void adc_init()
101 {
102         power_adc_enable();
103
104         ADCSRA = _BV(ADEN)                      // enable
105                 | _BV(ADPS1) | _BV(ADPS0)       // clk/8 = 125 kHz
106                 | _BV(ADIE);                    // enable IRQ
107         ADMUX = _BV(REFS1) | _BV(MUX1) | _BV(MUX0);
108                 // 1.1V reference, PB3 pin, single-ended
109         DIDR0 |= _BV(ADC3D);    // PB3 pin as analog input
110 }
111
112 static void adc_susp()
113 {
114         ADCSRA &= ~_BV(ADEN);   // disable ADC
115         DIDR0 &= ~_BV(ADC3D);   // disable analog input on PB3
116
117         power_adc_disable();
118 }
119
120 static void adc_start_measurement()
121 {
122         ADCSRA |= _BV(ADSC);
123 }
124
125 ISR(ADC_vect)
126 {
127         uint16_t adcw = ADCW;
128
129         if (adc_drop) {
130                 adc_drop--;
131                 ADCSRA |= _BV(ADSC);
132                 return;
133         }
134
135         // TODO: We may want to disable ADC after here to save power,
136         // but compared to the heater power it would be negligible,
137         // so don't bother with it.
138         if (adc_type == 0) {
139                 if (batt_off) {
140                         batt_off += adcw - (batt_off >> ADC_RUNAVG_SHIFT);
141                 } else {
142                         batt_off = adcw << ADC_RUNAVG_SHIFT;
143                 }
144         } else {
145                 if (batt_on) {
146                         batt_on += adcw - (batt_on >> ADC_RUNAVG_SHIFT);
147                 } else {
148                         batt_on = adcw << ADC_RUNAVG_SHIFT;
149                 }
150         }
151 }
152
153 /* ===================== Timer/Counter1 for PWM ===================== */
154 static void pwm_init()
155 {
156         power_timer1_enable();
157
158         DDRB |= _BV(PB4);
159
160         // TCCR1 = _BV(CS10); // clk/1 = 1 MHz
161         TCCR1 = _BV(CS11) | _BV(CS13); // clk/512 = 2 kHz
162         GTCCR = _BV(COM1B1) | _BV(PWM1B);
163         OCR1C = 255;
164         // OCR1B = steps[0];
165         OCR1B = 0;
166         TIMSK = _BV(OCIE1B) | _BV(TOIE1);
167 }
168
169 static void pwm_susp()
170 {
171         TCCR1 = 0;
172 }
173
174 ISR(TIM1_OVF_vect)
175 {
176         adc_drop = 2;
177         adc_type = 1;
178         adc_start_measurement();
179 }
180
181 ISR(TIM1_COMPB_vect)
182 {
183         adc_drop = 2;
184         adc_type = 0;
185         adc_start_measurement();
186 }
187
188 static void pwm_set(unsigned char pwm)
189 {
190         OCR1B = pwm;
191 }
192
193 /* ===================== Status LED on pin PB2 ======================= */
194 static void status_led_init()
195 {
196         DDRB |= _BV(PB2);
197         PORTB &= ~_BV(PB2);
198 }
199
200 static void status_led_on()
201 {
202         PORTB |= _BV(PB2);
203 }
204
205 static void status_led_off()
206 {
207         PORTB &= ~_BV(PB2);
208 }
209
210 static unsigned char status_led_is_on()
211 {
212         return PORTB & _BV(PB2) ? 1 : 0;
213 }
214
215 /* ================== Buttons on pin PB0 and PB1 ===================== */
216 static void buttons_init()
217 {
218         DDRB &= ~(_BV(PB0) | _BV(PB1)); // set as input
219         PORTB |= _BV(PB0) | _BV(PB1);   // internal pull-up
220
221         GIMSK &= ~_BV(PCIE); // disable pin-change IRQs
222         PCMSK = 0; // disable pin-change IRQs on all pins of port B
223 }
224
225 static void buttons_susp()
226 {
227         buttons_init();
228
229         GIMSK |= _BV(PCIE);
230         PCMSK |= _BV(PCINT0) | _BV(PCINT1);
231 }
232
233 static unsigned char buttons_pressed()
234 {
235         return (
236                 (PINB & _BV(PB0) ? 0 : 1)
237                 |
238                 (PINB & _BV(PB1) ? 0 : 2)
239         );
240 }
241
242 static unsigned char buttons_wait_for_release()
243 {
244         uint16_t wake_count = 0;
245
246         do {
247                 if (++wake_count > WAKEUP_LIMIT)
248                         status_led_on(); // inform the user
249
250                 _delay_ms(WAKEUP_POLL);
251         } while (buttons_pressed());
252
253         status_led_off();
254
255         return wake_count > WAKEUP_LIMIT;
256 }
257
258 ISR(PCINT0_vect)
259 {
260         // empty - let it wake us from sleep, but do nothing else
261 }
262
263 /* ==== Watchdog Timer for timing blinks and other periodic tasks ==== */
264 static void wdt_init()
265 {
266         next_clock_tick = 0;
267         jiffies = 0;
268         WDTCR = _BV(WDIE) | _BV(WDP1); // interrupt mode, 64 ms
269 }
270
271 static void wdt_susp()
272 {
273         wdt_disable();
274 }
275
276 ISR(WDT_vect) {
277         next_clock_tick = 1;
278         jiffies++;
279 }
280
281 /* ====== Hardware init, teardown, powering down and waking up ====== */
282 static void hw_setup()
283 {
284         power_all_disable();
285
286         pwm_init();
287         adc_init();
288         status_led_init();
289         wdt_init();
290 }
291
292 static void hw_suspend()
293 {
294         adc_susp();
295         pwm_susp();
296         status_led_init(); // we don't have a separate _susp() here
297         buttons_susp();
298         wdt_susp();
299
300         power_all_disable();
301 }
302
303 static void power_down()
304 {
305         hw_suspend();
306
307         do {
308                 // G'night
309                 set_sleep_mode(SLEEP_MODE_PWR_DOWN);
310                 sleep_enable();
311                 sleep_bod_disable();
312                 sei();
313                 sleep_cpu();
314
315                 // G'morning
316                 cli();
317                 sleep_disable();
318
319                 // allow wakeup by long button-press only
320         } while (!buttons_wait_for_release());
321
322         // OK, wake up now
323         hw_setup();
324 }
325
326 /* ======== Button press detection and  handling ===================== */
327 static void button_pressed(unsigned char button, unsigned char long_press)
328 {
329         // ignore simlultaneous button 1 and 2 press
330         if (long_press) {
331                 if (button == 1) {
332                         power_down();
333                 } else if (button == 2) {
334                         power_level = N_POWER_LEVELS-1;
335                 }
336         } else { // short press
337                 if (button == 1) {
338                         if (power_level > 0) {
339                                 --power_level;
340                         } else {
341                                 power_down();
342                         }
343                 } else if (button == 2) {
344                         if (power_level < N_POWER_LEVELS-1) {
345                                 ++power_level;
346                         }
347                 }
348         }
349 }
350
351 static unsigned char button_state, button_state_time;
352
353 static void timer_check_buttons()
354 {
355         unsigned char newstate = buttons_pressed();
356
357         if (newstate == button_state) {
358                 if (newstate && button_state_time < BUTTON_LONG_MIN)
359                         ++button_state_time;
360
361                 if (newstate && button_state_time >= BUTTON_LONG_MIN) {
362                         status_led_on();
363                 }
364                 return;
365         }
366
367         if (newstate) {
368                 button_state = newstate;
369                 button_state_time = 0;
370                 return;
371         }
372
373         // just released
374         if (button_state_time >= BUTTON_SHORT_MIN)
375                 button_pressed(button_state,
376                         button_state_time >= BUTTON_LONG_MIN ? 1 : 0);
377
378         button_state = newstate;
379         button_state_time = 0;
380 }
381
382 /* ============ Status LED blinking =================================== */
383 static unsigned char blink_on_time, blink_off_time, n_blinks;
384 static unsigned char blink_counter;
385
386 static unsigned char battery_level()
387 {
388         unsigned char i, adc8;
389
390         // NOTE: we use 8-bit value only, so we don't need lock to protect
391         // us against concurrently running ADC IRQ handler:
392         adc8 = batt_off >> 8;
393
394         for (i = 0; i < BATT_N_LEVELS; i++)
395                 if (batt_levels[i] > adc8)
396                         break;
397
398         return i;
399 }
400
401 static void status_led_next_pattern()
402 {
403
404         // for now, display the selected intensity
405         n_blinks = power_level + 1;
406         // n_blinks = battery_level() + 1;
407         blink_on_time = 0;
408         blink_off_time = 2;
409         blink_counter = 10;
410 }
411
412 static void timer_blink()
413 {
414         if (blink_counter) {
415                 blink_counter--;
416         } else if (status_led_is_on()) {
417                 status_led_off();
418                 blink_counter = blink_off_time;
419         } else if (n_blinks) {
420                 --n_blinks;
421                 status_led_on();
422                 blink_counter = blink_on_time;
423         } else {
424                 status_led_next_pattern();
425         }
426 }
427
428 int main()
429 {
430         log_init();
431
432 #if 0
433         log_word(batt_levels[0]);
434         log_word(batt_levels[1]);
435         log_word(batt_levels[2]);
436         log_flush();
437 #endif
438
439         power_down();
440
441         sei();
442
443         // we try to be completely IRQ-driven, so just wait for IRQs here
444         while(1) {
445                 cli();
446                 set_sleep_mode(SLEEP_MODE_IDLE);
447                 sleep_enable();
448                 // keep BOD active, no sleep_bod_disable();
449                 sei();
450                 sleep_cpu();
451                 sleep_disable();
452
453                 // FIXME: Maybe handle new ADC readings as well?
454                 if (next_clock_tick) {
455                         next_clock_tick = 0;
456                         timer_blink();
457                         // this has to be after the timer_blink() call
458                         // to override the status LED during long button press
459                         timer_check_buttons();
460
461                         if ((jiffies & 0x0F) == 0) {
462                                 unsigned char i;
463
464                                 for (i = 0; i < BATT_N_LEVELS; i++)
465                                         if (batt_levels[i] > batt_off)
466                                                 break;
467
468 #if 0
469                                 log_byte(0xcc);
470                                 log_byte(i);
471                                 log_byte(batt_off >> 8);
472                                 log_byte(batt_on >> 8);
473 #endif
474                         }
475                         log_flush();
476                 }
477         }
478 }