Analog Input

Quick Reference

Configuring an Analog Input Pin

Arduino

Nothing required

CircuitPython

import board
import analogio
adc = analogio.AnalogIn(board.A0)

Using an Analog Input Pin

Arduino

int val = analogRead(3);

CircuitPython

adc.value

Discussion

Configuring an Analog Input Pin

Arduino

Nothing special is needed to configure an analog input pin. An analog output pin needs to be configured as output in the same way as a digital output pin. Note that only certain pins are able to be used as analog. Check the documentation for your specific board to find which ones.

CircuitPython

Using an analog pin in CircuitPython is similar to using a digital one.

As before, use the board module to give access to the correct pins by name. Additionally, the analogio modules gives you the analog I/O classes.

To read analog inputs you need to create an instance of AnalogIn:

Download: file
>>> import board
>>> import analogio
>>> adc = analogio.AnalogIn(board.A0)

To set up an analog output, you create an AnalogOut instance.

Download: file
>>> import board
>>> import analogio
>>> led = analogio.AnalogOut(board.A0)

Using an Analog Input Pin

Arduino

Analog I/O is done similarly to digital. Different boards can have different numbers and locations of analog pins. Check your documentation for specifics on what your board has.

Download: file
int val = analogRead(3);

The returned value is an int between 0 and 1023, inclusive. This range assumes a 10-bit analog to digital converter. In general the number of bits in the analog to digital converter determines the range, which will be 0 to 2bits-1. E.g. a 12-bit converter will result in values between 0 and 4095. Refer to your board's documentation to find the size of the converter.

CircuitPython

Once you have an AnalogIn object as shown above, you just need to get its value property:

Download: file
adc.value

In CircuitPython, analog input values that you read as shown above will always be in the range 0 to 65535. This does not mean that there is always a 16-bit converter. Instead, the values read from the converter are mapped to the 16-bit range. This frees you from having to be concerned with the details of the converter on your board.

The AnalogIn object gives you a handy method for querying the converter's reference voltage, so if you need to know the actual voltage being measured you can do it simply by using the following code. Keep in mind that he result will vary based on the voltage at the pin as well as the reference voltage.

Download: file
>>> adc.value / 65535 * adc.reference_voltage
3.2998
This guide was first published on Oct 22, 2018. It was last updated on Oct 22, 2018. This page (Analog Input) was last updated on May 22, 2019.