CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-adafruit-blinka

CircuitPython APIs for non-CircuitPython versions of Python such as CPython on Linux and MicroPython.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

analog-io.mddocs/

Analog Input/Output

Analog-to-digital conversion and digital-to-analog output with platform-specific implementations. Provides CircuitPython-compatible analog I/O operations for reading sensor values and generating analog signals across supported hardware platforms.

Capabilities

Analog Input

The AnalogIn class provides analog-to-digital conversion for reading analog sensors and voltage levels. Automatically detects and uses appropriate platform-specific drivers.

class AnalogIn(ContextManaged):
    def __init__(self, pin):
        """
        Initialize analog input pin.
        
        Args:
            pin: Board analog pin object (from board module)
        
        Raises:
            RuntimeError: If no analog inputs are defined for the board
            ValueError: If the specified pin does not exist
        """
    
    @property
    def value(self) -> int:
        """
        Read raw ADC value.
        
        Returns:
            int: Raw ADC reading (typically 0-65535 range, platform-dependent)
        """
    
    @value.setter
    def value(self, value):
        """Raises AttributeError - AnalogIn is read-only"""
        raise AttributeError("'AnalogIn' object has no attribute 'value'")
    
    def deinit(self) -> None:
        """Release analog input resources"""

Analog Output

The AnalogOut class provides digital-to-analog conversion for generating analog voltages. Only available on platforms with DAC (Digital-to-Analog Converter) hardware.

class AnalogOut(ContextManaged):
    def __init__(self, pin):
        """
        Initialize analog output pin (DAC).
        
        Args:
            pin: Board analog output pin object (from board module)
        
        Raises:
            RuntimeError: If no analog outputs are defined for the board
            ValueError: If the specified pin does not exist
        """
    
    @property
    def value(self):
        """Raises AttributeError - AnalogOut value is write-only"""
        raise AttributeError("unreadable attribute")
    
    @value.setter
    def value(self, val: int) -> None:
        """
        Set DAC output value.
        
        Args:
            val: DAC output value (typically 0-65535 range, platform-dependent)
        """
    
    def deinit(self) -> None:
        """Release analog output resources"""

Usage Examples

Reading Analog Sensor

import board
import analogio
import time

# Setup analog input (e.g., potentiometer or sensor)
sensor = analogio.AnalogIn(board.A0)

# Read sensor values
for i in range(10):
    raw_value = sensor.value
    print(f"Raw ADC reading: {raw_value}")
    time.sleep(0.5)

# Cleanup
sensor.deinit()

Using Context Manager

import board
import analogio

# Automatic cleanup with context manager
with analogio.AnalogIn(board.A1) as sensor:
    reading = sensor.value
    print(f"Sensor reading: {reading}")

Analog Output (DAC)

import board
import analogio
import time

# Only available on boards with DAC support
try:
    dac = analogio.AnalogOut(board.A0)
    
    # Generate triangle wave
    for i in range(256):
        dac.value = i * 256  # Scale to full range
        time.sleep(0.01)
    
    for i in range(255, -1, -1):
        dac.value = i * 256
        time.sleep(0.01)
    
    # Cleanup
    dac.deinit()
    
except RuntimeError as e:
    print(f"DAC not available: {e}")

Converting to Voltage

import board
import analogio

# Many platforms require manual voltage calculation
with analogio.AnalogIn(board.A0) as sensor:
    raw_value = sensor.value
    
    # Example conversion for 3.3V reference, 16-bit ADC
    # (actual conversion depends on platform specifications)
    voltage = (raw_value / 65535.0) * 3.3
    print(f"Estimated voltage: {voltage:.2f}V")

Multi-Channel Reading

import board
import analogio
import time

# Setup multiple analog inputs
sensors = []
pins = [board.A0, board.A1, board.A2]

for pin in pins:
    try:
        sensor = analogio.AnalogIn(pin)
        sensors.append(sensor)
    except (RuntimeError, ValueError) as e:
        print(f"Pin {pin} not available: {e}")

# Read all sensors
for i in range(5):
    readings = []
    for j, sensor in enumerate(sensors):
        readings.append(sensor.value)
    
    print(f"Reading {i}: {readings}")
    time.sleep(1.0)

# Cleanup
for sensor in sensors:
    sensor.deinit()

Platform Considerations

Supported Platforms

  • MCP2221: USB-to-GPIO adapter with built-in ADC/DAC
  • Linux/SysFS: Generic Linux systems using IIO (Industrial I/O) subsystem
  • GreatFET One: USB analysis tool with analog capabilities
  • Various SBCs: Odroid, Siemens IoT2000, RK3xxx series, i.MX6ULL, STM32MP157
  • Allwinner SoCs: A10, A20 with analog input support
  • RP2040 via U2IF: Raspberry Pi Pico and related boards with USB interface

Limitations

  • Not all boards support analog I/O - check board documentation
  • Analog output (DAC) is less commonly available than analog input (ADC)
  • Value ranges and voltage references are platform-specific
  • Some platforms only support analog input, not output
  • Resolution and accuracy vary by hardware implementation

Error Handling

import board
import analogio

try:
    sensor = analogio.AnalogIn(board.A0)
    print(f"Sensor value: {sensor.value}")
    sensor.deinit()
except RuntimeError as e:
    print(f"Analog input not supported: {e}")
except ValueError as e:
    print(f"Invalid pin specification: {e}")

Install with Tessl CLI

npx tessl i tessl/pypi-adafruit-blinka

docs

analog-io.md

bitbangio.md

board-pins.md

communication.md

core-framework.md

digital-io.md

index.md

peripherals.md

pwm-pulse.md

utilities.md

tile.json