2 #include <avr/eeprom.h>
6 #define AMBIENT_VAL_SHIFT 2
7 static uint16_t ambient_val, ambient_val16;
8 volatile unsigned char ambient_zone;
9 static unsigned char ambient_min, ambient_max, ambient_16drop;
12 #define AMBIENT_LOG_SIZE 128
13 static unsigned char ambient_log_offset_stored EEMEM;
14 static unsigned char ambient_log_offset;
15 static unsigned char ambient_log[AMBIENT_LOG_SIZE] EEMEM;
17 /* My photodiode reads 0x00C5 .. 0x033B */
23 * Note: these have to be sorted, starting with 0, ending with 0xFFFF
24 * and having small overlaps in order to provide a bit of hysteresis.
26 static ambient_zone_t ambient_zones[] = {
27 { 0x0000 , 0x0270<<AMBIENT_VAL_SHIFT }, // dark
28 { 0x0260<<AMBIENT_VAL_SHIFT, 0x02f0<<AMBIENT_VAL_SHIFT }, // evening
29 { 0x02e8<<AMBIENT_VAL_SHIFT, 0x0306<<AMBIENT_VAL_SHIFT }, // dawn
30 { 0x0300<<AMBIENT_VAL_SHIFT, 0xffff }, // day
32 #define N_AMBIENT_ZONES (sizeof(ambient_zones)/sizeof(ambient_zones[0]))
43 ambient_log_offset = eeprom_read_byte(&ambient_log_offset_stored);
45 if (ambient_log_offset == AMBIENT_LOG_SIZE)
46 ambient_log_offset = 0; // start over
51 unsigned char stored_offset;
53 ambient_log_min_max();
55 stored_offset = eeprom_read_byte(&ambient_log_offset_stored);
56 if (stored_offset != ambient_log_offset)
57 eeprom_write_byte(&ambient_log_offset_stored,
61 void ambient_log_min_max()
63 if (ambient_log_offset >= AMBIENT_LOG_SIZE - 1)
66 // eeprom_write_byte(&ambient_log[ambient_log_offset++], ambient_min);
67 eeprom_write_byte(&ambient_log[ambient_log_offset++], ambient_max);
68 eeprom_write_byte(&ambient_log[ambient_log_offset++], ambient_16drop);
75 void ambient_zone_changed()
79 log_byte(ambient_zone);
80 log_word(ambient_val);
84 // led_set_pattern(N_PWMLEDS, status_led_pattern_select());
85 // led_set_pattern(N_PWMLEDS+1, illumination_led_pattern_select());
89 void ambient_adc(uint16_t adcval)
91 unsigned char old_zone = ambient_zone;
92 unsigned char byte_val, byte_val16;
94 ambient_val += adcval - (ambient_val
95 >> (AMBIENT_VAL_SHIFT - AMBIENT_ADC_SHIFT));
97 while (ambient_zones[ambient_zone].lo > ambient_val)
100 while (ambient_zones[ambient_zone].hi < ambient_val)
103 byte_val = ambient_val >> (2 + AMBIENT_VAL_SHIFT - AMBIENT_ADC_SHIFT);
105 ambient_val16 += byte_val - (ambient_val16 >> 4);
106 byte_val16 = ambient_val16 >> 4;
108 if (byte_val16 > byte_val) {
109 byte_val16 -= byte_val;
110 if (byte_val16 > ambient_16drop)
111 ambient_16drop = byte_val16;
114 if (ambient_min > byte_val)
115 ambient_min = byte_val;
117 if (ambient_max < byte_val)
118 ambient_max = byte_val;
120 if (old_zone != ambient_zone) {
122 log_byte(ambient_zone);
126 // ambient_zone_changed();