]> www.fi.muni.cz Git - bike-lights.git/blob - firmware/ambient.c
ambient.c: adjust the day/dawn values
[bike-lights.git] / firmware / ambient.c
1 #include <avr/io.h>
2
3 #include "lights.h"
4
5 #define AMBIENT_VAL_SHIFT 2
6 static uint16_t ambient_val;
7 volatile unsigned char ambient_zone;
8
9 /* My photodiode reads 0x00C5 .. 0x033B */
10 typedef struct {
11         uint16_t lo, hi;
12 } ambient_zone_t;
13
14 /*
15  * Note: these have to be sorted, starting with 0, ending with 0xFFFF
16  * and having small overlaps in order to provide a bit of hysteresis.
17  */
18 static ambient_zone_t ambient_zones[] = {
19         { 0x0000                   , 0x0290<<AMBIENT_VAL_SHIFT }, // dark
20         { 0x0280<<AMBIENT_VAL_SHIFT, 0x0300<<AMBIENT_VAL_SHIFT }, // evening
21         { 0x02f8<<AMBIENT_VAL_SHIFT, 0x0310<<AMBIENT_VAL_SHIFT }, // dawn
22         { 0x0308<<AMBIENT_VAL_SHIFT, 0xffff                    }, // day
23 };
24 #define N_AMBIENT_ZONES (sizeof(ambient_zones)/sizeof(ambient_zones[0]))
25
26 void init_ambient()
27 {
28         ambient_val = 0;
29         ambient_zone = 1;
30 }
31
32 void ambient_zone_changed()
33 {
34 #if 1
35         log_byte(0xab);
36         log_byte(ambient_zone);
37         log_word(ambient_val);
38         log_flush();
39 #endif
40
41         // led_set_pattern(N_PWMLEDS, status_led_pattern_select());
42         // led_set_pattern(N_PWMLEDS+1, illumination_led_pattern_select());
43         // pattern_reload();
44 }
45
46 void ambient_adc(uint16_t adcval)
47 {
48         unsigned char old_zone = ambient_zone;
49
50         ambient_val += adcval - (ambient_val
51                 >> (AMBIENT_VAL_SHIFT - AMBIENT_ADC_SHIFT));
52
53         while (ambient_zones[ambient_zone].lo > ambient_val)
54                 ambient_zone--;
55
56         while (ambient_zones[ambient_zone].hi < ambient_val)
57                 ambient_zone++;
58
59 #if 0
60         if (old_zone != ambient_zone) {
61                 log_byte(0xab);
62                 log_byte(ambient_zone);
63                 log_word(adcval);
64                 log_flush();
65         }
66                 // ambient_zone_changed();
67 #endif
68 }
69