Calibration example script (arduino.py) Learns the range of a sensor on A0 during the first five seconds, then sets the on-board LED's brightness from where each reading falls in that range.
- Wiring
- A sensor, e.g. a light-dependent resistor divider, on A0. While the LED is on at the start, give the sensor its lowest and highest values, e.g. cover it and then shine a light on it.
from arduino import *
SENSOR_PIN = A0
CALIBRATION_MS = 5000
sensor_min = 1023
sensor_max = 0
def setup():
global sensor_min, sensor_max
pinMode(LED_BUILTIN, OUTPUT)
digitalWrite(LED_BUILTIN, HIGH)
start = millis()
while millis() - start < CALIBRATION_MS:
value = analogRead(SENSOR_PIN)
sensor_min = min(sensor_min, value)
sensor_max = max(sensor_max, value)
delay(10)
digitalWrite(LED_BUILTIN, LOW)
print("range:", sensor_min, "-", sensor_max)
sensor_max = max(sensor_max, sensor_min + 1)
def loop():
value = analogRead(SENSOR_PIN)
value = constrain(value, sensor_min, sensor_max)
value = map(value, sensor_min, sensor_max, 0, 255)
analogWrite(LED_BUILTIN, value)
delay(10)
def main():
setup()
while True:
loop()
if __name__ == "__main__":
main()