0
0
Iot-protocolsHow-ToBeginner · 3 min read

How to Use ADC on Raspberry Pi Pico: Simple Guide

To use ADC on Raspberry Pi Pico, import the machine module, create an ADC object for the desired pin (e.g., ADC(26) for GPIO26), and call read_u16() to get the analog value. This reads a 16-bit integer representing the voltage level from 0 to 3.3V.
📐

Syntax

The basic syntax to use ADC on Raspberry Pi Pico is:

  • adc = machine.ADC(pin_number): Create an ADC object for the pin you want to read.
  • value = adc.read_u16(): Read the analog value as a 16-bit integer (0 to 65535).

Pin numbers correspond to GPIO pins that support ADC, usually GPIO26, GPIO27, or GPIO28.

python
import machine

adc = machine.ADC(26)  # Create ADC object on GPIO26
value = adc.read_u16()  # Read analog value (0-65535)
print(value)
Output
32768
💻

Example

This example reads the analog voltage from GPIO26 every second and prints the raw 16-bit ADC value. It shows how to set up ADC and get continuous readings.

python
import machine
import time

adc = machine.ADC(26)  # ADC on GPIO26

while True:
    value = adc.read_u16()  # Read ADC value
    print(f"ADC reading: {value}")
    time.sleep(1)
Output
ADC reading: 32768 ADC reading: 32770 ADC reading: 32765 (continues every second)
⚠️

Common Pitfalls

  • Wrong pin number: Only GPIO26, GPIO27, and GPIO28 support ADC on Pico. Using other pins will cause errors.
  • Not using read_u16(): Older methods like read() are not available; always use read_u16() for 16-bit resolution.
  • Ignoring voltage reference: ADC reads voltage from 0 to 3.3V; values must be scaled accordingly.
python
import machine

# Wrong way: Using a pin without ADC
# adc = machine.ADC(15)  # GPIO15 does not support ADC, will error

# Correct way:
adc = machine.ADC(26)  # GPIO26 supports ADC
value = adc.read_u16()
print(value)
Output
32768
📊

Quick Reference

FunctionDescription
machine.ADC(pin)Create ADC object for given GPIO pin (26, 27, or 28)
adc.read_u16()Read 16-bit analog value (0-65535) from ADC
time.sleep(seconds)Pause program for given seconds (used for delay between reads)

Key Takeaways

Use GPIO26, GPIO27, or GPIO28 pins for ADC on Raspberry Pi Pico.
Create an ADC object with machine.ADC(pin) and read values with read_u16().
ADC values range from 0 to 65535 representing 0 to 3.3 volts.
Avoid using pins without ADC support to prevent errors.
Use delays like time.sleep() to space out ADC readings in loops.