X-Git-Url: https://www.fi.muni.cz/~kas/git//home/kas/public_html/git/?p=bike-lights.git;a=blobdiff_plain;f=firmware%2Fambient.c;h=02377ccd46586ab1895083adeb09dbda77ff50e5;hp=ffe7740f7c1b4d4644d6c45763d910fffb5752bb;hb=65c3ad96cf307c3b77b36e6f6a2af5201c213a3c;hpb=e8f0df376c6df7eeec08010642c6ac4967e242f8 diff --git a/firmware/ambient.c b/firmware/ambient.c index ffe7740..02377cc 100644 --- a/firmware/ambient.c +++ b/firmware/ambient.c @@ -1,50 +1,116 @@ #include +#include #include "lights.h" +#define AMBIENT_VAL_SHIFT 2 static uint16_t ambient_val; volatile unsigned char ambient_zone; -static unsigned char ambient_zone_set; +static unsigned char ambient_min, ambient_max; -static uint16_t ambient_zones[] = { - 0x0c00, 0x0d00, 0x1000, 0x1800, 0x2800, 0x2f80, 0xffff +/* logging */ +#define AMBIENT_LOG_SIZE 128 +static unsigned char ambient_log_offset_stored EEMEM; +static unsigned char ambient_log_offset; +static unsigned char ambient_log[AMBIENT_LOG_SIZE] EEMEM; + +/* My photodiode reads 0x00C5 .. 0x033B */ +typedef struct { + uint16_t lo, hi; +} ambient_zone_t; + +/* + * Note: these have to be sorted, starting with 0, ending with 0xFFFF + * and having small overlaps in order to provide a bit of hysteresis. + */ +static ambient_zone_t ambient_zones[] = { + { 0x0000 , 0x0280<= AMBIENT_LOG_SIZE - 1) + return; + + eeprom_write_byte(&ambient_log[ambient_log_offset++], ambient_min); + eeprom_write_byte(&ambient_log[ambient_log_offset++], ambient_max); + + ambient_min = 0xFF; + ambient_max = 0; } void ambient_zone_changed() { +#if 1 log_byte(0xab); log_byte(ambient_zone); log_word(ambient_val); log_flush(); +#endif + + // led_set_pattern(N_PWMLEDS, status_led_pattern_select()); + // led_set_pattern(N_PWMLEDS+1, illumination_led_pattern_select()); + // pattern_reload(); } void ambient_adc(uint16_t adcval) { - unsigned char newzone; - - if (!ambient_zone_set) - ambient_val = adcval << 4; - else // running sum - ambient_val += adcval - (ambient_val >> 4); - - newzone = 0; - while (newzone < N_AMBIENT_ZONES-1 - && ambient_zones[newzone] < ambient_val) - newzone++; - - // TODO: implement hysteresis? - if (!ambient_zone_set || newzone != ambient_zone) { - ambient_zone = newzone; - ambient_zone_set = 1; - // ambient_zone_changed(); + unsigned char old_zone = ambient_zone; + unsigned char byte_val; + + ambient_val += adcval - (ambient_val + >> (AMBIENT_VAL_SHIFT - AMBIENT_ADC_SHIFT)); + + while (ambient_zones[ambient_zone].lo > ambient_val) + ambient_zone--; + + while (ambient_zones[ambient_zone].hi < ambient_val) + ambient_zone++; + + byte_val = adcval >> 2; + + if (ambient_min > byte_val) + ambient_min = byte_val; + + if (ambient_max < byte_val) + ambient_max = byte_val; +#if 0 + if (old_zone != ambient_zone) { + log_byte(0xab); + log_byte(ambient_zone); + log_word(adcval); + log_flush(); } + // ambient_zone_changed(); +#endif }