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