comparison main.c @ 0:8705acff2494

lots of stuff
author Matt Johnston <matt@ucc.asn.au>
date Sat, 01 Jun 2013 01:38:42 +0800
parents
children e23c1b6f6080
comparison
equal deleted inserted replaced
-1:000000000000 0:8705acff2494
1 #include <stdio.h>
2 #include <string.h>
3 #include <stddef.h>
4 #include <stdbool.h>
5 #include <stdlib.h>
6 #include <avr/io.h>
7 #include <avr/interrupt.h>
8 #include <avr/sleep.h>
9 #include <util/delay.h>
10 #include <avr/pgmspace.h>
11 #include <avr/eeprom.h>
12 #include <avr/wdt.h>
13 #include <util/atomic.h>
14 #include <util/crc16.h>
15
16 #include "simple_ds18b20.h"
17 #include "onewire.h"
18
19 // configuration params
20 // - measurement interval
21 // - transmit interval
22 // - bluetooth params
23 // - number of sensors (and range?)
24
25 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
26 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
27
28 // TICK should be 8 or less (8 untested). all timers need
29 // to be a multiple.
30
31 #define TICK 6
32 // we have 1024 prescaler, 32768 crystal.
33 #define SLEEP_COMPARE (32*TICK-1)
34
35 #define VALUE_NOSENSOR 0x07D0 // 125 degrees
36 #define VALUE_BROKEN 0x07D1 // 125.0625
37
38 #define OVERSHOOT_MAX_DIV 1800.0 // 30 mins
39 #define WORT_INVALID_TIME 900 // 15 mins
40 // fridge min/max are only used if the wort sensor is invalid
41 #define FRIDGE_AIR_MIN_RANGE 40 // 4º
42 #define FRIDGE_AIR_MAX_RANGE 40 // 4º
43
44 #define BAUD 19200
45 #define UBRR ((F_CPU)/8/(BAUD)-1)
46
47 #define PORT_LED PORTC
48 #define DDR_LED DDRC
49 #define PIN_LED PC4
50
51 #define PORT_SHDN PORTD
52 #define DDR_SHDN DDRD
53 #define PIN_SHDN PD7
54
55 #define PORT_FRIDGE PORTD
56 #define DDR_FRIDGE DDRD
57 #define PIN_FRIDGE PD6
58
59 // total amount of 16bit values available for measurements.
60 // adjust emperically, be sure to allow enough stack space too
61 #define TOTAL_MEASUREMENTS 800
62
63 // each sensor slot uses 8 bytes
64 #define MAX_SENSORS 6
65
66 // fixed at 8, have a shorter name
67 #define ID_LEN OW_ROMCODE_SIZE
68
69 // #define HAVE_UART_ECHO
70
71 // stores a value of clock_epoch combined with the remainder of TCNT2,
72 // for 1/32 second accuracy
73 struct epoch_ticks
74 {
75 uint32_t ticks;
76 // remainder
77 uint8_t rem;
78 };
79
80 // eeprom-settable parameters. all timeouts should
81 // be a multiple of TICK (6 seconds probably)
82 static uint16_t measure_wake = 61; // not a divisor of comms_wake
83 static uint16_t comms_wake = 600;
84 static uint8_t wake_secs = 30;
85 // decidegrees
86 static int16_t fridge_setpoint = 180; // 18.0ºC
87 static uint16_t fridge_difference = 3; // 0.3ºC
88 static uint16_t fridge_delay = 600; // seconds
89
90 static uint16_t overshoot_delay = 720; // 12 mins
91 static uint8_t overshoot_factor = 10; // 1.0ºC
92
93 // ---- Atomic guards required accessing these variables
94 // clock_epoch in seconds
95 static uint32_t clock_epoch;
96 static uint16_t comms_count;
97 static uint16_t measure_count;
98 // ---- End atomic guards required
99
100 static uint16_t n_measurements;
101
102 // calculated at startup as TOTAL_MEASUREMENTS/n_sensors
103 static uint16_t max_measurements;
104
105 static uint16_t measurements[TOTAL_MEASUREMENTS];
106
107 static struct epoch_ticks first_measurement_clock;
108 // last_measurement_clock is redundant but checks that we're not missing
109 // samples
110 static struct epoch_ticks last_measurement_clock;
111 static struct epoch_ticks last_comms_clock;
112
113 // boolean flags
114 static uint8_t need_measurement;
115 static uint8_t need_comms;
116 static uint8_t uart_enabled;
117 static uint8_t stay_awake;
118 static uint8_t button_pressed;
119
120 // counts down from WAKE_SECS to 0, goes to deep sleep when hits 0
121 static uint8_t comms_timeout;
122
123 static uint8_t readpos;
124 static char readbuf[30];
125 static uint8_t have_cmd;
126
127 static uint8_t n_sensors;
128 static uint8_t sensor_id[MAX_SENSORS][ID_LEN];
129
130 static int16_t last_fridge = DS18X20_INVALID_DECICELSIUS;
131 static int16_t last_wort = DS18X20_INVALID_DECICELSIUS;
132 static struct epoch_ticks fridge_off_clock = {0};
133 static struct epoch_ticks fridge_on_clock = {0};
134 static struct epoch_ticks wort_valid_clock = {0};
135
136 int uart_putchar(char c, FILE *stream);
137 static void long_delay(int ms);
138 static void blink();
139 static uint16_t adc_vcc();
140
141 static FILE mystdout = FDEV_SETUP_STREAM(uart_putchar, NULL,
142 _FDEV_SETUP_WRITE);
143
144 static uint16_t crc_out;
145 static FILE _crc_stdout = FDEV_SETUP_STREAM(uart_putchar, NULL,
146 _FDEV_SETUP_WRITE);
147 // convenience
148 static FILE *crc_stdout = &_crc_stdout;
149
150
151 // thanks to http://projectgus.com/2010/07/eeprom-access-with-arduino/
152 #define eeprom_read_to(dst_p, eeprom_field, dst_size) eeprom_read_block((dst_p), (void *)offsetof(struct __eeprom_data, eeprom_field), (dst_size))
153 #define eeprom_read(dst, eeprom_field) eeprom_read_to((&dst), eeprom_field, sizeof(dst))
154 #define eeprom_write_from(src_p, eeprom_field, src_size) eeprom_write_block((src_p), (void *)offsetof(struct __eeprom_data, eeprom_field), (src_size))
155 #define eeprom_write(src, eeprom_field) { eeprom_write_from(&src, eeprom_field, sizeof(src)); }
156
157 #define EXPECT_MAGIC 0x67c9
158
159 struct __attribute__ ((__packed__)) __eeprom_data {
160 uint16_t measure_wake;
161 uint16_t comms_wake;
162 uint8_t wake_secs;
163
164 int16_t fridge_setpoint; // decidegrees
165 uint16_t fridge_difference; // decidegrees
166 uint16_t fridge_delay;
167
168 uint16_t overshoot_delay;
169 uint8_t overshoot_factor; // decidegrees
170
171 #if 0
172 static uint8_t wort_id[ID_LEN];
173 static uint8_t fridge_id[ID_LEN];
174 #endif
175
176 uint16_t magic;
177 };
178
179 static const uint8_t fridge_id[ID_LEN] =
180 {0x28,0xCE,0xB2,0x1A,0x03,0x00,0x00,0x99};
181 static const uint8_t wort_id[ID_LEN] =
182 {0x28,0x49,0xBC,0x1A,0x03,0x00,0x00,0x54};
183
184 static void deep_sleep();
185
186 // 0 or 1
187 static uint8_t
188 is_fridge_on()
189 {
190 if (PORT_FRIDGE & _BV(PIN_FRIDGE))
191 {
192 return 1;
193 }
194 else
195 {
196 return 0;
197 }
198 }
199
200 // Very first setup
201 static void
202 setup_chip()
203 {
204 cli();
205
206 // stop watchdog timer (might have been used to cause a reset)
207 wdt_reset();
208 MCUSR &= ~_BV(WDRF);
209 WDTCSR |= _BV(WDCE) | _BV(WDE);
210 WDTCSR = 0;
211
212 // Set clock to 2mhz
213 CLKPR = _BV(CLKPCE);
214 // divide by 4
215 CLKPR = _BV(CLKPS1);
216
217 // enable pullups
218 PORTB = 0xff; // XXX change when using SPI
219 PORTD = 0xff;
220 PORTC = 0xff;
221
222 // 3.3v power for bluetooth and SD
223 DDR_LED |= _BV(PIN_LED);
224 DDR_SHDN |= _BV(PIN_SHDN);
225
226 PORT_FRIDGE &= ~_BV(PIN_FRIDGE);
227 DDR_FRIDGE |= _BV(PIN_FRIDGE);
228
229 // set pullup
230 PORTD |= _BV(PD2);
231 // INT0 setup
232 EICRA = (1<<ISC01); // falling edge - data sheet says it won't work?
233 EIMSK = _BV(INT0);
234
235 // comparator disable
236 ACSR = _BV(ACD);
237
238 // disable adc pin input buffers
239 DIDR0 = 0x3F; // acd0-adc5
240 DIDR1 = (1<<AIN1D)|(1<<AIN0D); // ain0/ain1
241
242 sei();
243 }
244
245 static void
246 set_aux_power(uint8_t on)
247 {
248 if (on)
249 {
250 PORT_SHDN &= ~_BV(PIN_SHDN);
251 }
252 else
253 {
254 PORT_SHDN |= _BV(PIN_SHDN);
255 }
256 }
257
258 static void
259 get_epoch_ticks(struct epoch_ticks *t)
260 {
261 ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
262 {
263 t->ticks = clock_epoch;
264 t->rem = TCNT2;
265 }
266 }
267
268 static void
269 set_measurement(uint8_t sensor, uint16_t measurement, uint16_t reading)
270 {
271 measurements[sensor*max_measurements + measurement] = reading;
272 }
273
274 static uint16_t
275 get_measurement(uint8_t sensor, uint16_t measurement)
276 {
277 return measurements[sensor*max_measurements + measurement];
278 }
279
280 static void
281 setup_tick_counter()
282 {
283 // set up counter2.
284 // COM21 COM20 Set OC2 on Compare Match (p116)
285 // WGM21 Clear counter on compare
286 //TCCR2A = _BV(COM2A1) | _BV(COM2A0) | _BV(WGM21);
287 // toggle on match
288 TCCR2A = _BV(COM2A0);
289 // CS22 CS21 CS20 clk/1024
290 TCCR2B = _BV(CS22) | _BV(CS21) | _BV(CS20);
291 // set async mode
292 ASSR |= _BV(AS2);
293 TCNT2 = 0;
294 OCR2A = SLEEP_COMPARE;
295 // interrupt
296 TIMSK2 = _BV(OCIE2A);
297 }
298
299 static void
300 uart_on()
301 {
302 // Power reduction register
303 PRR &= ~_BV(PRUSART0);
304
305 // All of this needs to be done each time after turning off the PRR
306 // baud rate
307 UBRR0H = (unsigned char)(UBRR >> 8);
308 UBRR0L = (unsigned char)UBRR;
309 // set 2x clock, improves accuracy of UBRR
310 UCSR0A |= _BV(U2X0);
311 UCSR0B = _BV(RXCIE0) | _BV(RXEN0) | _BV(TXEN0);
312 //8N1
313 UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);
314 uart_enabled = 1;
315 }
316
317 static void
318 uart_off()
319 {
320 // Turn off interrupts and disable tx/rx
321 UCSR0B = 0;
322 uart_enabled = 0;
323
324 // Power reduction register
325 PRR |= _BV(PRUSART0);
326 }
327
328 int
329 uart_putchar(char c, FILE *stream)
330 {
331 if (!uart_enabled)
332 {
333 return EOF;
334 }
335 // XXX could perhaps sleep in the loop for power.
336 if (c == '\n')
337 {
338 loop_until_bit_is_set(UCSR0A, UDRE0);
339 UDR0 = '\r';
340 }
341 loop_until_bit_is_set(UCSR0A, UDRE0);
342 UDR0 = c;
343 if (stream == crc_stdout)
344 {
345 crc_out = _crc_ccitt_update(crc_out, c);
346 }
347 if (c == '\r')
348 {
349 loop_until_bit_is_set(UCSR0A, UDRE0);
350 UDR0 = '\n';
351 if (stream == crc_stdout)
352 {
353 crc_out = _crc_ccitt_update(crc_out, '\n');
354 }
355 }
356 return (unsigned char)c;
357 }
358
359 static void
360 cmd_fetch()
361 {
362 crc_out = 0;
363
364 fprintf_P(crc_stdout, PSTR("START\n"));
365 {
366 struct epoch_ticks now;
367 get_epoch_ticks(&now);
368 fprintf_P(crc_stdout, PSTR("now=%lu\n"), now.ticks);
369 fprintf_P(crc_stdout, PSTR("now_rem=%hhu\n"), now.rem);
370 }
371 fprintf_P(crc_stdout, PSTR("time_step=%hu\n"), measure_wake);
372 fprintf_P(crc_stdout, PSTR("first_time=%lu\n"), first_measurement_clock.ticks);
373 fprintf_P(crc_stdout, PSTR("first_time_rem=%hhu\n"), first_measurement_clock.rem);
374 fprintf_P(crc_stdout, PSTR("last_time=%lu\n"), last_measurement_clock.ticks);
375 fprintf_P(crc_stdout, PSTR("last_time_rem=%hhu\n"), last_measurement_clock.rem);
376 fprintf_P(crc_stdout, PSTR("comms_time=%lu\n"), last_comms_clock.ticks);
377 fprintf_P(crc_stdout, PSTR("comms_time_rem=%hhu\n"), last_comms_clock.rem);
378 fprintf_P(crc_stdout, PSTR("voltage=%hu\n"), adc_vcc());
379 fprintf_P(crc_stdout, PSTR("measure=%hu\n"), measure_wake);
380 fprintf_P(crc_stdout, PSTR("comms=%hu\n"), comms_wake);
381 fprintf_P(crc_stdout, PSTR("wake=%hhu\n"), wake_secs);
382 fprintf_P(crc_stdout, PSTR("fridge=%.1f\n"), fridge_setpoint/10.0);
383 fprintf_P(crc_stdout, PSTR("fridge_diff=%.1f\n"), fridge_difference/10.0);
384 fprintf_P(crc_stdout, PSTR("fridge_delay=%hu\n"), fridge_delay);
385 fprintf_P(crc_stdout, PSTR("overshoot_factor=%.1f\n"), overshoot_factor/10.0);
386 fprintf_P(crc_stdout, PSTR("overshoot_delay=%hu\n"), overshoot_delay);
387 fprintf_P(crc_stdout, PSTR("fridge_status=%hhu\n"), is_fridge_on());
388 fprintf_P(crc_stdout, PSTR("fridge_last_on=%lu\n"), fridge_on_clock.ticks);
389 fprintf_P(crc_stdout, PSTR("fridge_last_off=%lu\n"), fridge_off_clock.ticks);
390 fprintf_P(crc_stdout, PSTR("last_fridge=%hu\n"), last_fridge);
391 fprintf_P(crc_stdout, PSTR("last_wort=%hu\n"), last_wort);
392 fprintf_P(crc_stdout, PSTR("tick_secs=%d\n"), TICK);
393 fprintf_P(crc_stdout, PSTR("tick_wake=%d\n"), SLEEP_COMPARE);
394 fprintf_P(crc_stdout, PSTR("maxsens=%hhu\n"), MAX_SENSORS);
395 fprintf_P(crc_stdout, PSTR("totalmeas=%hu\n"), TOTAL_MEASUREMENTS);
396 fprintf_P(crc_stdout, PSTR("sensors=%hhu\n"), n_sensors);
397 for (uint8_t s = 0; s < n_sensors; s++)
398 {
399 fprintf_P(crc_stdout, PSTR("sensor_id%hhu="), s);
400 printhex(sensor_id[s], ID_LEN, crc_stdout);
401 fputc('\n', crc_stdout);
402 }
403 fprintf_P(crc_stdout, PSTR("measurements=%hu\n"), n_measurements);
404 for (uint16_t n = 0; n < n_measurements; n++)
405 {
406 fprintf_P(crc_stdout, PSTR("meas%hu="), n);
407 for (uint8_t s = 0; s < n_sensors; s++)
408 {
409 fprintf_P(crc_stdout, PSTR(" %04hx"), get_measurement(s, n));
410 }
411 fputc('\n', crc_stdout);
412 }
413 fprintf_P(crc_stdout, PSTR("END\n"));
414 fprintf_P(stdout, PSTR("CRC=%hu\n"), crc_out);
415 }
416
417 static void
418 cmd_clear()
419 {
420 n_measurements = 0;
421 printf_P(PSTR("cleared\n"));
422 }
423
424 static void
425 cmd_btoff()
426 {
427 uint8_t rem;
428 uint16_t count_copy;
429 ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
430 {
431 count_copy = comms_count;
432 rem = TCNT2;
433 }
434 printf_P(PSTR("next_wake=%hu,"), comms_wake-count_copy);
435 printf_P(PSTR("rem=%hhu,"), rem);
436 printf_P(PSTR("tick_secs=%hhu,"), TICK);
437 printf_P(PSTR("tick_wake=%hhu\n"), SLEEP_COMPARE);
438 _delay_ms(100);
439 comms_timeout = 0;
440 stay_awake = 0;
441 }
442
443 static void
444 cmd_reset()
445 {
446 printf_P(PSTR("reset\n"));
447 _delay_ms(100);
448 cli(); // disable interrupts
449 wdt_enable(WDTO_15MS); // enable watchdog
450 while(1); // wait for watchdog to reset processor
451 }
452
453 static void
454 cmd_measure()
455 {
456 printf_P(PSTR("measuring\n"));
457 need_measurement = 1;
458 }
459
460 static void
461 cmd_sensors()
462 {
463 uint8_t ret = simple_ds18b20_start_meas(NULL);
464 printf_P(PSTR("All sensors, ret %hhu, waiting...\n"), ret);
465 long_delay(DS18B20_TCONV_12BIT);
466 simple_ds18b20_read_all();
467 }
468
469 static void
470 init_sensors()
471 {
472 uint8_t id[OW_ROMCODE_SIZE];
473 printf_P(PSTR("init sensors\n"));
474 ow_reset();
475 for( uint8_t diff = OW_SEARCH_FIRST; diff != OW_LAST_DEVICE; )
476 {
477 diff = ow_rom_search( diff, &id[0] );
478 if( diff == OW_PRESENCE_ERR ) {
479 printf_P( PSTR("No Sensor found\r") );
480 return;
481 }
482
483 if( diff == OW_DATA_ERR ) {
484 printf_P( PSTR("Bus Error\r") );
485 return;
486 }
487
488 if (n_sensors < MAX_SENSORS)
489 {
490 memcpy(sensor_id[n_sensors], id, ID_LEN);
491 printf_P(PSTR("Added sensor %hhu : "), n_sensors);
492 printhex(id, ID_LEN, stdout);
493 putchar('\n');
494 n_sensors++;
495 }
496 else
497 {
498 printf_P(PSTR("Too many sensors\n"));
499 }
500 }
501
502 max_measurements = TOTAL_MEASUREMENTS / n_sensors;
503 }
504
505 static void
506 load_params()
507 {
508 uint16_t magic;
509 eeprom_read(magic, magic);
510 if (magic == EXPECT_MAGIC)
511 {
512 eeprom_read(measure_wake, measure_wake);
513 eeprom_read(comms_wake, comms_wake);
514 eeprom_read(wake_secs, wake_secs);
515 eeprom_read(fridge_setpoint, fridge_setpoint);
516 eeprom_read(fridge_difference, fridge_difference);
517 eeprom_read(fridge_delay, fridge_delay);
518 eeprom_read(overshoot_delay, overshoot_delay);
519 eeprom_read(overshoot_factor, overshoot_factor);
520 }
521 }
522
523 static void
524 cmd_get_params()
525 {
526 printf_P(PSTR("measure %hu\n"), measure_wake);
527 printf_P(PSTR("comms %hu\n"), comms_wake);
528 printf_P(PSTR("wake %hhu\n"), wake_secs);
529 printf_P(PSTR("tick %d\n"), TICK);
530 printf_P(PSTR("fridge %.1fº\n"), fridge_setpoint / 10.0f);
531 printf_P(PSTR("fridge difference %.1fº\n"), fridge_difference / 10.0f);
532 printf_P(PSTR("fridge_delay %hu\n"), fridge_delay);
533 printf_P(PSTR("overshoot factor %.1fº\n"), overshoot_factor / 10.0f);
534 printf_P(PSTR("overshoot delay %hu\n"), overshoot_delay);
535 printf_P(PSTR("sensors %hhu (%hhu)\n"),
536 n_sensors, MAX_SENSORS);
537 printf_P(PSTR("meas %hu (%hu)\n"),
538 max_measurements, TOTAL_MEASUREMENTS);
539 }
540
541 static void
542 cmd_set_params(const char *params)
543 {
544 uint16_t new_measure_wake;
545 uint16_t new_comms_wake;
546 uint8_t new_wake_secs;
547 int ret = sscanf_P(params, PSTR("%hu %hu %hhu"),
548 &new_measure_wake, &new_comms_wake, &new_wake_secs);
549
550 if (ret != 3)
551 {
552 printf_P(PSTR("Bad values\n"));
553 }
554 else
555 {
556 ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
557 {
558 eeprom_write(new_measure_wake, measure_wake);
559 eeprom_write(new_comms_wake, comms_wake);
560 eeprom_write(new_wake_secs, wake_secs);
561 uint16_t magic = EXPECT_MAGIC;
562 eeprom_write(magic, magic);
563 }
564 printf_P(PSTR("set_params for next boot\n"));
565 printf_P(PSTR("measure %hu comms %hu wake %hhu\n"),
566 new_measure_wake, new_comms_wake, new_wake_secs);
567 }
568 }
569
570 // returns true if eeprom was written
571 static bool
572 set_initial_eeprom()
573 {
574 uint16_t magic;
575 eeprom_read(magic, magic);
576 if (magic == EXPECT_MAGIC)
577 {
578 return false;
579 }
580
581 ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
582 {
583 eeprom_write(measure_wake, measure_wake);
584 eeprom_write(comms_wake, comms_wake);
585 eeprom_write(wake_secs, wake_secs);
586 eeprom_write(fridge_setpoint, fridge_setpoint);
587 eeprom_write(fridge_difference, fridge_difference);
588 eeprom_write(fridge_delay, fridge_delay);
589 eeprom_write(overshoot_delay, overshoot_delay);
590 eeprom_write(overshoot_factor, overshoot_factor);
591 magic = EXPECT_MAGIC;
592 eeprom_write(magic, magic);
593 }
594
595 return true;
596 }
597
598 static void
599 cmd_set_fridge_setpoint(char *params)
600 {
601 float new_f = atof(params);
602 if (new_f < 2 || new_f > 30)
603 {
604 printf_P(PSTR("Bad fridge value %f\n"), new_f);
605 return;
606 }
607
608 int16_t old_setpoint = fridge_setpoint;
609
610 fridge_setpoint = new_f * 10;
611 bool written = set_initial_eeprom();
612 if (!written)
613 {
614 if (old_setpoint != fridge_setpoint)
615 {
616 ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
617 {
618 eeprom_write(fridge_setpoint, fridge_setpoint);
619 }
620 }
621 }
622 printf_P(PSTR("old fridge %.1fº new fridge %.1fº\n"),
623 old_setpoint / 10.0f, fridge_setpoint / 10.0f);
624 }
625
626 static void
627 cmd_set_fridge_difference(char *params)
628 {
629 float new_f = atof(params);
630 if (new_f < 0 || new_f > 30)
631 {
632 printf_P(PSTR("Bad fridge value %f\n"), new_f);
633 return;
634 }
635
636 fridge_difference = new_f * 10;
637 bool written = set_initial_eeprom();
638 if (!written)
639 {
640 ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
641 {
642 eeprom_write(fridge_difference, fridge_difference);
643 }
644 }
645 printf_P(PSTR("new fridge difference %.1fº\n"), fridge_difference / 10.0f);
646 }
647
648 static void
649 cmd_set_fridge_delay(char *params)
650 {
651 uint16_t new_delay = atoi(params);
652 if (new_delay < 5)
653 {
654 printf_P(PSTR("Bad fridge delay %d\n"), new_delay);
655 return;
656 }
657
658 fridge_delay = new_delay;
659 bool written = set_initial_eeprom();
660 if (!written)
661 {
662 ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
663 {
664 eeprom_write(fridge_delay, fridge_delay);
665 }
666 }
667 printf_P(PSTR("new fridge delay %hu\n"), fridge_delay);
668 }
669
670 static void
671 cmd_set_overshoot_factor(char *params)
672 {
673 float new_f = atof(params);
674 if (new_f <= 0 || new_f > 20)
675 {
676 printf_P(PSTR("Bad overshoot factor %f\n"), new_f);
677 return;
678 }
679
680 uint8_t old = overshoot_factor;
681
682 overshoot_factor = new_f * 10;
683 bool written = set_initial_eeprom();
684 if (!written)
685 {
686 if (old != overshoot_factor)
687 {
688 ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
689 {
690 eeprom_write(overshoot_factor, overshoot_factor);
691 }
692 }
693 }
694 printf_P(PSTR("old factor %.1fº new factor %.1fº\n"),
695 old / 10.0f, overshoot_factor / 10.0f);
696 }
697
698 static void
699 cmd_set_overshoot_delay(char *params)
700 {
701 uint16_t new_delay = atoi(params);
702 if (new_delay < 5)
703 {
704 printf_P(PSTR("Bad overshoot delay %d\n"), new_delay);
705 return;
706 }
707
708 overshoot_delay = new_delay;
709 bool written = set_initial_eeprom();
710 if (!written)
711 {
712 ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
713 {
714 eeprom_write(overshoot_delay, overshoot_delay);
715 }
716 }
717 printf_P(PSTR("new overshoot delay %hu\n"), overshoot_delay);
718 }
719
720 static void
721 cmd_awake()
722 {
723 stay_awake = 1;
724 printf_P(PSTR("awake\n"));
725 }
726
727 static void
728 read_handler()
729 {
730 if (strcmp_P(readbuf, PSTR("fetch")) == 0)
731 {
732 cmd_fetch();
733 }
734 else if (strcmp_P(readbuf, PSTR("clear")) == 0)
735 {
736 cmd_clear();
737 }
738 else if (strcmp_P(readbuf, PSTR("btoff")) == 0)
739 {
740 cmd_btoff();
741 }
742 else if (strcmp_P(readbuf, PSTR("measure")) == 0)
743 {
744 cmd_measure();
745 }
746 else if (strcmp_P(readbuf, PSTR("sensors")) == 0)
747 {
748 cmd_sensors();
749 }
750 else if (strcmp_P(readbuf, PSTR("get_params")) == 0)
751 {
752 cmd_get_params();
753 }
754 else if (strncmp_P(readbuf, PSTR("set_params "), 11) == 0)
755 {
756 cmd_set_params(&readbuf[11]);
757 }
758 else if (strcmp_P(readbuf, PSTR("awake")) == 0)
759 {
760 cmd_awake();
761 }
762 else if (strncmp_P(readbuf, PSTR("fridge_setpoint "), 16) == 0)
763 {
764 cmd_set_fridge_setpoint(&readbuf[16]);
765 }
766 else if (strncmp_P(readbuf, PSTR("fridge_diff "), 12) == 0)
767 {
768 cmd_set_fridge_difference(&readbuf[12]);
769 }
770 else if (strncmp_P(readbuf, PSTR("fridge_delay "), 13) == 0)
771 {
772 cmd_set_fridge_delay(&readbuf[13]);
773 }
774 else if (strncmp_P(readbuf, PSTR("overshoot_delay "), 16) == 0)
775 {
776 cmd_set_overshoot_delay(&readbuf[16]);
777 }
778 else if (strncmp_P(readbuf, PSTR("overshoot_factor "), 17) == 0)
779 {
780 cmd_set_overshoot_factor(&readbuf[17]);
781 }
782 else if (strcmp_P(readbuf, PSTR("reset")) == 0)
783 {
784 cmd_reset();
785 }
786 else
787 {
788 printf_P(PSTR("Bad command '%s'\n"), readbuf);
789 }
790 }
791
792 ISR(INT0_vect)
793 {
794 button_pressed = 1;
795 blink();
796 _delay_ms(100);
797 blink();
798 }
799
800
801 ISR(USART_RX_vect)
802 {
803 char c = UDR0;
804 #ifdef HAVE_UART_ECHO
805 uart_putchar(c, NULL);
806 #endif
807 if (c == '\r' || c == '\n')
808 {
809 if (readpos > 0)
810 {
811 readbuf[readpos] = '\0';
812 have_cmd = 1;
813 readpos = 0;
814 }
815 }
816 else
817 {
818 readbuf[readpos] = c;
819 readpos++;
820 if (readpos >= sizeof(readbuf))
821 {
822 readpos = 0;
823 }
824 }
825 }
826
827 ISR(TIMER2_COMPA_vect)
828 {
829 TCNT2 = 0;
830 measure_count += TICK;
831 comms_count += TICK;
832
833 clock_epoch += TICK;
834
835 if (comms_timeout != 0)
836 {
837 comms_timeout -= TICK;
838 }
839
840 if (measure_count >= measure_wake)
841 {
842 measure_count = 0;
843 need_measurement = 1;
844 }
845
846 if (comms_count >= comms_wake)
847 {
848 comms_count = 0;
849 need_comms = 1;
850 }
851 }
852
853 static void
854 deep_sleep()
855 {
856 // p119 of manual
857 OCR2A = SLEEP_COMPARE;
858 loop_until_bit_is_clear(ASSR, OCR2AUB);
859
860 set_sleep_mode(SLEEP_MODE_PWR_SAVE);
861 sleep_mode();
862 }
863
864 static void
865 idle_sleep()
866 {
867 set_sleep_mode(SLEEP_MODE_IDLE);
868 sleep_mode();
869 }
870
871 static uint16_t
872 adc_vcc()
873 {
874 PRR &= ~_BV(PRADC);
875
876 // /16 prescaler
877 ADCSRA = _BV(ADEN) | _BV(ADPS2);
878
879 // set to measure 1.1 reference
880 ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
881 // average a number of samples
882 uint16_t sum = 0;
883 uint8_t num = 0;
884 for (uint8_t n = 0; n < 20; n++)
885 {
886 ADCSRA |= _BV(ADSC);
887 loop_until_bit_is_clear(ADCSRA, ADSC);
888
889 uint8_t low_11 = ADCL;
890 uint8_t high_11 = ADCH;
891 uint16_t val = low_11 + (high_11 << 8);
892
893 if (n >= 4)
894 {
895 sum += val;
896 num++;
897 }
898 }
899 ADCSRA = 0;
900 PRR |= _BV(PRADC);
901
902 //float res_volts = 1.1 * 1024 * num / sum;
903 //return 1000 * res_volts;
904 return ((uint32_t)1100*1024*num) / sum;
905 }
906
907 static void
908 do_fridge()
909 {
910 struct epoch_ticks now;
911 get_epoch_ticks(&now);
912 uint32_t off_time = now.ticks - fridge_off_clock.ticks;
913 bool wort_valid = last_wort != DS18X20_INVALID_DECICELSIUS;
914 bool fridge_valid = last_fridge != DS18X20_INVALID_DECICELSIUS;
915
916 int16_t wort_max = fridge_setpoint + fridge_difference;
917 int16_t wort_min = fridge_setpoint;
918
919 // the fridge min/max only apply if the wort sensor is broken
920 int16_t fridge_min = fridge_setpoint - FRIDGE_AIR_MIN_RANGE;
921 int16_t fridge_max = fridge_setpoint + FRIDGE_AIR_MAX_RANGE;
922
923 uint8_t fridge_on = PORT_FRIDGE & _BV(PIN_FRIDGE);
924 printf_P(PSTR("last_wort %hd (%hd, %hd), last_fridge %hd (%hd, %hd), setpoint %hd, diff %hd, fridge_on %hhu\n"),
925 last_wort, wort_min, wort_max,
926 last_fridge, fridge_min, fridge_max,
927 fridge_setpoint, fridge_difference, fridge_on);
928
929 if (off_time < fridge_delay)
930 {
931 printf_P(PSTR("waiting for fridge delay current %hu, wait %hu\n"),
932 off_time, fridge_delay);
933 return;
934 }
935
936 // handle failure of the wort sensor. if it is a short (intermittent?)
937 // failure we wait until it has been broken for a period of time
938 // (WORT_INVALID_TIME) before doing anything.
939 if (wort_valid)
940 {
941 wort_valid_clock = now;
942 }
943 else
944 {
945 printf_P(PSTR("wort sensor is invalid\n"));
946 uint32_t invalid_time = now.ticks - wort_valid_clock.ticks;
947 if (invalid_time < WORT_INVALID_TIME)
948 {
949 printf("only been invalid for %ld, waiting\n", invalid_time);
950 return;
951 }
952 }
953
954 if (!fridge_valid)
955 {
956 printf_P(PSTR("fridge sensor is invalid\n"));
957 }
958
959 if (fridge_on)
960 {
961 bool turn_off = false;
962 uint16_t on_time = now.ticks - fridge_on_clock.ticks;
963
964 uint16_t overshoot = 0;
965 if (on_time > overshoot_delay)
966 {
967 overshoot = overshoot_factor * MIN(OVERSHOOT_MAX_DIV, on_time) / OVERSHOOT_MAX_DIV;
968 }
969
970 printf_P(PSTR("on_time %hu, overshoot %hu\n"), on_time, overshoot);
971
972 // wort has cooled enough. will probably cool a bit more by itself
973 if (wort_valid)
974 {
975 if ((last_wort - overshoot) < fridge_setpoint)
976 {
977 printf_P(PSTR("wort has cooled enough, overshoot %hu on_time %hu\n"), overshoot, on_time);
978 turn_off = true;
979 }
980 }
981 else
982 {
983 if (fridge_valid && last_fridge < fridge_min)
984 {
985 printf_P(PSTR("fridge off fallback\n"));
986 turn_off = true;
987 }
988 }
989
990 if (turn_off)
991 {
992 // too cold, turn off
993 printf_P(PSTR("Turning fridge off\n"));
994 PORT_FRIDGE &= ~_BV(PIN_FRIDGE);
995 fridge_off_clock = now;
996 }
997 }
998 else
999 {
1000 bool turn_on = false;
1001
1002 if (wort_valid)
1003 {
1004 if (last_wort >= wort_max)
1005 {
1006 printf_P(PSTR("wort is too hot\n"));
1007 turn_on = true;
1008 }
1009 }
1010 else
1011 {
1012 if (fridge_valid && last_fridge >= fridge_max)
1013 {
1014 printf_P(PSTR("fridge on fallback\n"));
1015 turn_on = true;
1016 }
1017 }
1018
1019 if (turn_on)
1020 {
1021 // too hot, turn on
1022 printf_P(PSTR("Turning fridge on\n"));
1023 PORT_FRIDGE |= _BV(PIN_FRIDGE);
1024 fridge_on_clock = now;
1025 }
1026 }
1027 }
1028
1029 static void
1030 do_measurement()
1031 {
1032 blink();
1033
1034 /* Take the timer here since deep_sleep() below could take 6 seconds */
1035 get_epoch_ticks(&last_measurement_clock);
1036 if (n_measurements == 0)
1037 {
1038 first_measurement_clock = last_measurement_clock;
1039 }
1040
1041 simple_ds18b20_start_meas(NULL);
1042 _delay_ms(DS18B20_TCONV_12BIT);
1043
1044 if (n_measurements == max_measurements)
1045 {
1046 n_measurements = 0;
1047 }
1048
1049 for (uint8_t s = 0; s < n_sensors; s++)
1050 {
1051 uint16_t reading;
1052 uint8_t ret = simple_ds18b20_read_raw(sensor_id[s], &reading);
1053 if (ret != DS18X20_OK)
1054 {
1055 reading = VALUE_BROKEN;
1056 }
1057 set_measurement(s, n_measurements, reading);
1058
1059 if (memcmp(sensor_id[s], fridge_id, sizeof(fridge_id)) == 0)
1060 {
1061 last_fridge = ds18b20_raw16_to_decicelsius(reading);
1062 }
1063 if (memcmp(sensor_id[s], wort_id, sizeof(wort_id)) == 0)
1064 {
1065 last_wort = ds18b20_raw16_to_decicelsius(reading);
1066 }
1067 }
1068
1069 n_measurements++;
1070 }
1071
1072 static void
1073 do_comms()
1074 {
1075 get_epoch_ticks(&last_comms_clock);
1076
1077 // turn on bluetooth
1078 set_aux_power(1);
1079 // avoid receiving rubbish, perhaps
1080 _delay_ms(50);
1081 uart_on();
1082
1083 // write sd card here? same 3.3v regulator...
1084
1085 for (comms_timeout = wake_secs;
1086 comms_timeout > 0 || stay_awake;
1087 )
1088 {
1089 if (need_measurement)
1090 {
1091 need_measurement = 0;
1092 do_measurement();
1093 do_fridge();
1094 continue;
1095 }
1096
1097 if (have_cmd)
1098 {
1099 have_cmd = 0;
1100 read_handler();
1101 continue;
1102 }
1103
1104 // wait for commands from the master
1105 idle_sleep();
1106 }
1107
1108 uart_off();
1109 // in case bluetooth takes time to flush
1110 _delay_ms(100);
1111 set_aux_power(0);
1112 }
1113
1114 static void
1115 blink()
1116 {
1117 PORT_LED &= ~_BV(PIN_LED);
1118 _delay_ms(1);
1119 PORT_LED |= _BV(PIN_LED);
1120 }
1121
1122 static void
1123 long_delay(int ms)
1124 {
1125 int iter = ms / 100;
1126
1127 for (int i = 0; i < iter; i++)
1128 {
1129 _delay_ms(100);
1130 }
1131 }
1132
1133 ISR(BADISR_vect)
1134 {
1135 //uart_on();
1136 printf_P(PSTR("Bad interrupt\n"));
1137 }
1138
1139 int main(void)
1140 {
1141 setup_chip();
1142 blink();
1143
1144 set_aux_power(0);
1145
1146 stdout = &mystdout;
1147 uart_on();
1148
1149 printf(PSTR("Started.\n"));
1150
1151 load_params();
1152
1153 init_sensors();
1154
1155 uart_off();
1156
1157 // turn off everything except timer2
1158 PRR = _BV(PRTWI) | _BV(PRTIM0) | _BV(PRTIM1) | _BV(PRSPI) | _BV(PRUSART0) | _BV(PRADC);
1159
1160 setup_tick_counter();
1161
1162 sei();
1163
1164 need_comms = 1;
1165 need_measurement = 1;
1166
1167 stay_awake = 1;
1168
1169 for(;;)
1170 {
1171 if (button_pressed)
1172 {
1173 // debounce
1174 _delay_ms(200);
1175 need_comms = 1;
1176 comms_timeout = wake_secs;
1177 button_pressed = 0;
1178 continue;
1179 }
1180
1181 if (need_comms)
1182 {
1183 need_comms = 0;
1184 do_comms();
1185 continue;
1186 }
1187
1188 if (need_measurement)
1189 {
1190 need_measurement = 0;
1191 do_measurement();
1192 do_fridge();
1193 continue;
1194 }
1195
1196 deep_sleep();
1197 }
1198
1199 return 0; /* never reached */
1200 }