CircuitPython Analog In

This quick-start example shows how you can read the analog voltages on all five Trinket M0 pins.

Copy and paste the code block into using your favorite text editor, and save the file, to run the demo

# Trinket IO demo - analog inputs

from analogio import AnalogIn
import board
import time

analog0in = AnalogIn(board.D0)
analog1in = AnalogIn(board.D1)
analog2in = AnalogIn(board.D2)
analog3in = AnalogIn(board.D3)
analog4in = AnalogIn(board.D4)

def getVoltage(pin):
    return (pin.value * 3.3) / 65536

while True:
    print("D0: %0.2f \t D1: %0.2f \t D2: %0.2f \t D3: %0.2f \t D4: %0.2f" %
           getVoltage(analog4in) ))

Creating analog inputs

analog0in = AnalogIn(D0)
analog1in = AnalogIn(D1)
analog2in = AnalogIn(D2)
analog3in = AnalogIn(D3)
analog4in = AnalogIn(D4)

Creates five objects, one for each pad, and connects the objects to D0 through D4 inclusive, as analog inputs.

GetVoltage Helper

getVoltage(pin) is our little helper program. By default, analog readings will range from 0 (minimum) to 65535 (maximum). This helper will convert the 0-65535 reading from pin.value and convert it a 0-3.3V voltage reading.

Main Loop

The main loop is simple, it will just print out the three voltages as floating point values (the %f indicates to print as floating point) by calling getVoltage on each of our analog objects.

If you connect to the serial port REPL, you'll see the voltages printed out. By default the pins are floating so the voltages will vary. Try touching a wire from D0 to the GND or 3Vo pad to see the voltage change!

Last updated on 2017-12-01 at 04.45.54 PM Published on 2017-08-23 at 05.57.02 PM