From: Jan "Yenya" Kasprzak Date: Thu, 13 Jun 2013 19:14:30 +0000 (+0200) Subject: ambient.c: detect drop of ambient light X-Git-Url: https://www.fi.muni.cz/~kas/git//home/kas/public_html/git/?a=commitdiff_plain;h=1dcbf67055a7a51031a57db46d899ade790b2d30;p=bike-lights.git ambient.c: detect drop of ambient light Measure also longer-term running average of ambient light values, and log instead of minima and maxima of adc readings the diffrence between this longer-term average and normal avereage (ambient_val). This is so that we would be able to switch the front light on when entering a darkish area from the bright sun. --- diff --git a/firmware/ambient.c b/firmware/ambient.c index 4f257ae..b839753 100644 --- a/firmware/ambient.c +++ b/firmware/ambient.c @@ -4,9 +4,9 @@ #include "lights.h" #define AMBIENT_VAL_SHIFT 2 -static uint16_t ambient_val; +static uint16_t ambient_val, ambient_val16; volatile unsigned char ambient_zone; -static unsigned char ambient_min, ambient_max; +static unsigned char ambient_min, ambient_max, ambient_16drop; /* logging */ #define AMBIENT_LOG_SIZE 128 @@ -34,9 +34,11 @@ static ambient_zone_t ambient_zones[] = { void init_ambient() { ambient_val = 0; + ambient_val16 = 0; ambient_max = 0; ambient_min = 0xFF; ambient_zone = 1; + ambient_16drop = 0; ambient_log_offset = eeprom_read_byte(&ambient_log_offset_stored); @@ -62,10 +64,12 @@ void ambient_log_min_max() return; eeprom_write_byte(&ambient_log[ambient_log_offset++], ambient_min); - eeprom_write_byte(&ambient_log[ambient_log_offset++], ambient_max); + // eeprom_write_byte(&ambient_log[ambient_log_offset++], ambient_max); + eeprom_write_byte(&ambient_log[ambient_log_offset++], ambient_16drop); ambient_min = 0xFF; ambient_max = 0; + ambient_16drop = 0; } void ambient_zone_changed() @@ -85,7 +89,7 @@ void ambient_zone_changed() void ambient_adc(uint16_t adcval) { unsigned char old_zone = ambient_zone; - unsigned char byte_val; + unsigned char byte_val, byte_val16; ambient_val += adcval - (ambient_val >> (AMBIENT_VAL_SHIFT - AMBIENT_ADC_SHIFT)); @@ -96,7 +100,16 @@ void ambient_adc(uint16_t adcval) while (ambient_zones[ambient_zone].hi < ambient_val) ambient_zone++; - byte_val = adcval >> 2; + byte_val = ambient_val >> (2 + AMBIENT_VAL_SHIFT - AMBIENT_ADC_SHIFT); + + ambient_val16 += byte_val - (ambient_val16 >> 4); + byte_val16 = ambient_val16 >> 4; + + if (byte_val16 > byte_val) { + byte_val16 -= byte_val; + if (byte_val16 > ambient_16drop) + ambient_16drop = byte_val16; + } if (ambient_min > byte_val) ambient_min = byte_val;