]> www.fi.muni.cz Git - bike-lights.git/blobdiff - firmware/ambient.c
ambient.c: adjust the day/dawn values
[bike-lights.git] / firmware / ambient.c
index cbbef9e02a78d902ef606dad286ffa8cb90358da..72e13323a9d6124ba863a70a71dc676af916a876 100644 (file)
@@ -2,47 +2,68 @@
 
 #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 uint16_t ambient_zones[] = {
-       0x10, 0x18, 0x20, 0x40, 0x100, 0x400, 0x1000, 0x4000, 0xffff
+/* 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                   , 0x0290<<AMBIENT_VAL_SHIFT }, // dark
+       { 0x0280<<AMBIENT_VAL_SHIFT, 0x0300<<AMBIENT_VAL_SHIFT }, // evening
+       { 0x02f8<<AMBIENT_VAL_SHIFT, 0x0310<<AMBIENT_VAL_SHIFT }, // dawn
+       { 0x0308<<AMBIENT_VAL_SHIFT, 0xffff                    }, // day
 };
 #define N_AMBIENT_ZONES (sizeof(ambient_zones)/sizeof(ambient_zones[0]))
 
-void ambient_init()
+void init_ambient()
 {
        ambient_val = 0;
-       ambient_zone = 0;
-       ambient_zone_set = 0;
+       ambient_zone = 1;
 }
 
 void ambient_zone_changed()
 {
-       log_byte(0xCC);
+#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;
+       unsigned char old_zone = ambient_zone;
 
-       if (!ambient_zone_set)
-               ambient_val = adcval << 4;
-       else // running sum
-               ambient_val += adcval - (ambient_val >> 4);
+       ambient_val += adcval - (ambient_val
+               >> (AMBIENT_VAL_SHIFT - AMBIENT_ADC_SHIFT));
 
-       newzone = 0;
-       while (newzone < N_AMBIENT_ZONES-1
-               && ambient_zones[newzone] < ambient_val)
-               newzone++;
+       while (ambient_zones[ambient_zone].lo > ambient_val)
+               ambient_zone--;
 
-       if (!ambient_zone_set || newzone != ambient_zone) {
-               ambient_zone = newzone;
-               ambient_zone_set = 1;
-               // ambient_zone_changed();
+       while (ambient_zones[ambient_zone].hi < ambient_val)
+               ambient_zone++;
+
+#if 0
+       if (old_zone != ambient_zone) {
+               log_byte(0xab);
+               log_byte(ambient_zone);
+               log_word(adcval);
+               log_flush();
        }
+               // ambient_zone_changed();
+#endif
 }