CircuitPython Analog In

Though the following example uses the Circuit Playground Express to demonstrate, the code works exactly the same way with the Circuit Playground Bluefruit. Simply copy the code and follow along with your Circuit Playground Bluefruit!

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 code.py using your favorite code editor, and save the file, to run the demo.

# Circuit Playground AnalogIn
# Reads the analog voltage level from a 10k potentiometer connected to GND, 3.3V, and pin A1
# and prints the results to the serial console.

import time
import board
import analogio

analogin = analogio.AnalogIn(board.A1)


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


while True:
    print("Analog Voltage: %f" % getVoltage(analogin))
    time.sleep(0.1)

Creating an Analog Input

analogin = analogio.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 console, you'll see the voltage printed out. Try turning the knob of the potentiometer to see the voltage change!

This guide was first published on Oct 12, 2017. It was last updated on Oct 12, 2017. This page (CircuitPython Analog In) was last updated on Nov 11, 2019.