CircuitPython

If you are new to CircuitPython, see Welcome to CircuitPython!

The simple code below intended for the CPX board reads multiple samples from every pin and then averages them before printing them to serial console. It takes approximately 1 second to read 370 samples for all eight pins plus a little additional time to do the maths, format output and send it to the serial console. The values printed are: a timestamp at start of the sampling period, another timestamp at the end, and then the averaged values for pins A0 to A7. The timestamps are the number of seconds from when the CPX board was powered up.

The first line on the terminal screenshot below shows values read between 352.076888 and 353.057003 seconds with A1 4421.45 and A2 18889.9. The unconnected pins have values around 29000. These values are raw values and can be converted to a voltage by dividing by 65536 and multiplying by the reference voltage which is 3.3V in the library code. For this example, the values would be 223mV and 951mV, respectively,

The output is in Python tuple format and can be graphed directly by Mu editor. For this project the terminal output was captured to a file and then graphed using the R language.

Download: file
import time

import board
from analogio import AnalogIn

# All eight pins on CPX board
pins = [ AnalogIn(board.A0),
         AnalogIn(board.A1),
         AnalogIn(board.A2),
         AnalogIn(board.A3),
         AnalogIn(board.A4),
         AnalogIn(board.A5),
         AnalogIn(board.A6),
         AnalogIn(board.A7) ]     

numpins = len(pins)

# 370 is about 1 second for 8 pins on CPX
samples = 370

# Print two relative timestamps in seconds plus an
# unweighted average of many samples for each pin in
# python tuple style which can be read direclty and
# graphed by the Mu editor - values are raw (0-65535)
while True:
    total = [0] * numpins
    t1 = time.monotonic()
    for repeat in range(samples):
        values = [pin.value for pin in pins]
        total = [sum(x) for x in zip(total, values)]
    t2 = time.monotonic()
    avgs = list(map(lambda x: x / samples, total))
    print("({:f},{:f},".format(t1,t2) +
          ",".join(str(avg) for avg in avgs) + ")")

Adafruit recommends copying this file to the board using the target filename code.py on the Circuit Playground Express.

This guide was first published on Oct 28, 2018. It was last updated on Oct 28, 2018. This page (CircuitPython) was last updated on Apr 24, 2019.