Calibration example script (phyduino.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.
import time
import phyduino as mcu
CALIBRATION_MS = 5000
sensor_min = 4095
sensor_max = 0
mcu.led.on()
start = time.ticks_ms()
while time.ticks_diff(time.ticks_ms(), start) < CALIBRATION_MS:
value = mcu.analog_read("A0")
sensor_min = min(sensor_min, value)
sensor_max = max(sensor_max, value)
time.sleep_ms(10)
mcu.led.off()
print("range:", sensor_min, "-", sensor_max)
led = mcu.pwm("LED")
span = max(sensor_max - sensor_min, 1)
while True:
value = mcu.analog_read("A0")
value = min(max(value, sensor_min), sensor_max)
led.duty_u16((value - sensor_min) * 65535 // span)
time.sleep_ms(10)