Analog Averaging example script (arduino.py) Shows how averaging steadies a reading. For each setting, takes 100 readings of A0 and A3 and prints the lowest, the highest and the spread between them (in ADC steps), then waits 5 seconds and starts again.
Arduino has no averaging setting, so this uses mcu.analog_averaging() from phyduino.py, which applies to every analogue pin: A3-A5 average in the external ADC itself, A0-A2 take the samples one after another. analogReadResolution(12) makes analogRead() give the ADCs' own 0-4095 steps.
- Wiring
- Connect a steady voltage, e.g. a potentiometer wiper, to A0 (0-3.3 V) and A3 (0-2.048 V), or leave them as they are.
- Output
averaging 1 A0 lowest 2040 highest 2056 spread 16
averaging 1 A3 lowest 2046 highest 2050 spread 4
...
averaging 32 A0 lowest 2047 highest 2049 spread 2
from arduino import *
import phyduino as mcu
READINGS = 100
def spread(pin):
"""Takes READINGS readings of one pin; returns the lowest, the highest and the gap."""
values = [analogRead(pin) for _ in range(READINGS)]
return min(values), max(values), max(values) - min(values)
def setup():
analogReadResolution(12)
def loop():
for samples in (1, 4, 8, 16, 32):
mcu.analog_averaging(samples)
for pin in (A0, A3):
low, high, width = spread(pin)
print("averaging %2d %s lowest %4d highest %4d spread %3d" % (samples, pin, low, high, width))
mcu.analog_averaging(1)
print()
delay(5000)
def main():
setup()
while True:
loop()
if __name__ == "__main__":
main()