I'm trying to implement AutoDim functionality into my Xronos clock using phtoresistor.
I'm measuring this photores values and map them to values from 1 to 5 (1 being dimmest, and 5 being brightest).
It works for the most part, but when room is totally dark, clock brightness goes up! This confused a hell out of me until I printed lightLevel values and noticed that they can be negative (since it's a byte it turns into 255) when photoCell reading is below 300. Is this a bug in map() function? Since I defined strict parameters from 1 to 5 how does it go to -1 and -2?
Sure I understand it happens when reading goes below 300, but still should result be always 1 if reading is 300 or less?
You need to constrain your readings to the same range as your map input range.
It isn't a bug.
Have a look at the constrain function (macro?) in the reference.
Sure I understand it happens when reading goes below 300, but still should result be always 1 if reading is 300 or less?
No. The map() function defines two ranges - a from range and a to range. If the input value is no in the from range, the output value will not be in the to range.
would be a lot easier to debug. You can print lightLevel at each step to make sure that it is read, constrained, and mapped correctly.
Thanks! Yeah it's much easier to read, but now my lightLevel var will have to be int, so I'm wasting a byte
It works now tho! If anyone interested here's the code. I had to do a little trick to prevent clock from flickering. Basically it only changes brightness if it it's different from previous reading, plus it takes readings only every 10 seconds (aprox)...
void autoBrightness () {
if (brightness) return; // Brightness is not set to 0 (auto)
if (second()%10) return; // Take readings every 10th second only
if (prevBrightness==0) { // Initialized previous Brightness setting only if Brightness was reset
prevBrightness=map( constrain (analogRead(photoCellPin), PHOTOCELL_MIN, PHOTOCELL_MAX), PHOTOCELL_MIN, PHOTOCELL_MAX, 1, 5); // Get Ambient Light Reading
setBrightness(prevBrightness); // Set LED brightness
}
lightLevel = map( constrain (analogRead(photoCellPin), PHOTOCELL_MIN, PHOTOCELL_MAX), PHOTOCELL_MIN, PHOTOCELL_MAX, 1, 5); // Get Ambient Light Reading
if (lightLevel != prevBrightness) { // Set LED brightness only if light changed
setBrightness(lightLevel);
prevBrightness=lightLevel;
//Serial.println (lightLevel);
}
}