CircuitPython Analog In

This quick-start example shows how you can read the analog voltage of a potentiometer connected to the Circuit Playground Express.

First, connect your potentiometer to the Circuit Playground Express using three alligator clip leads, as shown. The connections are:

  • Left pot connection to 3.3V
  • Center pot (wiper) to A1
  • Right pot connection to GND
When you turn the knob of the potentiometer, the wiper rotates left and right, increasing or decreasing the resistance. This, in turn, changes the analog voltage level that will be read by the Circuit Playground Express on A1.

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

# CircuitPlaygroundExpress_AnalogIn
# reads the analog voltage level from a 10k potentiometer
# connected to GND, 3.3V, and pin A1
# and prints the results to the REPL

from analogio import AnalogIn
import board
import time

analogin = AnalogIn(board.A1)

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

while True:
    print("Analog Voltage: %f" % getVoltage(analogin))

Creating an Analog Input

analogin = AnalogIn(board.A1)Creates an object named 'analogin' which is connected to the A1 pad on the Circuit Playground Express. 

You can use many of different kinds of external analog sensors connected to the Analog IO pads, such as distance sensors, flex sensors, and more!!

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 voltage as a floating point value (the %f indicates to print as floating point) by calling getVoltage on each of our analog object, in this case the potentiometer.

If you connect to the serial port REPL, you'll see the voltage printed out. Try turning the knob of the potentiometer to see the voltage change!

Last updated on 2018-02-19 at 11.48.00 PM Published on 2017-10-12 at 10.43.39 PM