0
# Analog Input/Output
1
2
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.
3
4
## Capabilities
5
6
### Analog Input
7
8
The AnalogIn class provides analog-to-digital conversion for reading analog sensors and voltage levels. Automatically detects and uses appropriate platform-specific drivers.
9
10
```python { .api }
11
class AnalogIn(ContextManaged):
12
def __init__(self, pin):
13
"""
14
Initialize analog input pin.
15
16
Args:
17
pin: Board analog pin object (from board module)
18
19
Raises:
20
RuntimeError: If no analog inputs are defined for the board
21
ValueError: If the specified pin does not exist
22
"""
23
24
@property
25
def value(self) -> int:
26
"""
27
Read raw ADC value.
28
29
Returns:
30
int: Raw ADC reading (typically 0-65535 range, platform-dependent)
31
"""
32
33
@value.setter
34
def value(self, value):
35
"""Raises AttributeError - AnalogIn is read-only"""
36
raise AttributeError("'AnalogIn' object has no attribute 'value'")
37
38
def deinit(self) -> None:
39
"""Release analog input resources"""
40
```
41
42
### Analog Output
43
44
The AnalogOut class provides digital-to-analog conversion for generating analog voltages. Only available on platforms with DAC (Digital-to-Analog Converter) hardware.
45
46
```python { .api }
47
class AnalogOut(ContextManaged):
48
def __init__(self, pin):
49
"""
50
Initialize analog output pin (DAC).
51
52
Args:
53
pin: Board analog output pin object (from board module)
54
55
Raises:
56
RuntimeError: If no analog outputs are defined for the board
57
ValueError: If the specified pin does not exist
58
"""
59
60
@property
61
def value(self):
62
"""Raises AttributeError - AnalogOut value is write-only"""
63
raise AttributeError("unreadable attribute")
64
65
@value.setter
66
def value(self, val: int) -> None:
67
"""
68
Set DAC output value.
69
70
Args:
71
val: DAC output value (typically 0-65535 range, platform-dependent)
72
"""
73
74
def deinit(self) -> None:
75
"""Release analog output resources"""
76
```
77
78
## Usage Examples
79
80
### Reading Analog Sensor
81
82
```python
83
import board
84
import analogio
85
import time
86
87
# Setup analog input (e.g., potentiometer or sensor)
88
sensor = analogio.AnalogIn(board.A0)
89
90
# Read sensor values
91
for i in range(10):
92
raw_value = sensor.value
93
print(f"Raw ADC reading: {raw_value}")
94
time.sleep(0.5)
95
96
# Cleanup
97
sensor.deinit()
98
```
99
100
### Using Context Manager
101
102
```python
103
import board
104
import analogio
105
106
# Automatic cleanup with context manager
107
with analogio.AnalogIn(board.A1) as sensor:
108
reading = sensor.value
109
print(f"Sensor reading: {reading}")
110
```
111
112
### Analog Output (DAC)
113
114
```python
115
import board
116
import analogio
117
import time
118
119
# Only available on boards with DAC support
120
try:
121
dac = analogio.AnalogOut(board.A0)
122
123
# Generate triangle wave
124
for i in range(256):
125
dac.value = i * 256 # Scale to full range
126
time.sleep(0.01)
127
128
for i in range(255, -1, -1):
129
dac.value = i * 256
130
time.sleep(0.01)
131
132
# Cleanup
133
dac.deinit()
134
135
except RuntimeError as e:
136
print(f"DAC not available: {e}")
137
```
138
139
### Converting to Voltage
140
141
```python
142
import board
143
import analogio
144
145
# Many platforms require manual voltage calculation
146
with analogio.AnalogIn(board.A0) as sensor:
147
raw_value = sensor.value
148
149
# Example conversion for 3.3V reference, 16-bit ADC
150
# (actual conversion depends on platform specifications)
151
voltage = (raw_value / 65535.0) * 3.3
152
print(f"Estimated voltage: {voltage:.2f}V")
153
```
154
155
### Multi-Channel Reading
156
157
```python
158
import board
159
import analogio
160
import time
161
162
# Setup multiple analog inputs
163
sensors = []
164
pins = [board.A0, board.A1, board.A2]
165
166
for pin in pins:
167
try:
168
sensor = analogio.AnalogIn(pin)
169
sensors.append(sensor)
170
except (RuntimeError, ValueError) as e:
171
print(f"Pin {pin} not available: {e}")
172
173
# Read all sensors
174
for i in range(5):
175
readings = []
176
for j, sensor in enumerate(sensors):
177
readings.append(sensor.value)
178
179
print(f"Reading {i}: {readings}")
180
time.sleep(1.0)
181
182
# Cleanup
183
for sensor in sensors:
184
sensor.deinit()
185
```
186
187
## Platform Considerations
188
189
### Supported Platforms
190
191
- **MCP2221**: USB-to-GPIO adapter with built-in ADC/DAC
192
- **Linux/SysFS**: Generic Linux systems using IIO (Industrial I/O) subsystem
193
- **GreatFET One**: USB analysis tool with analog capabilities
194
- **Various SBCs**: Odroid, Siemens IoT2000, RK3xxx series, i.MX6ULL, STM32MP157
195
- **Allwinner SoCs**: A10, A20 with analog input support
196
- **RP2040 via U2IF**: Raspberry Pi Pico and related boards with USB interface
197
198
### Limitations
199
200
- Not all boards support analog I/O - check board documentation
201
- Analog output (DAC) is less commonly available than analog input (ADC)
202
- Value ranges and voltage references are platform-specific
203
- Some platforms only support analog input, not output
204
- Resolution and accuracy vary by hardware implementation
205
206
### Error Handling
207
208
```python
209
import board
210
import analogio
211
212
try:
213
sensor = analogio.AnalogIn(board.A0)
214
print(f"Sensor value: {sensor.value}")
215
sensor.deinit()
216
except RuntimeError as e:
217
print(f"Analog input not supported: {e}")
218
except ValueError as e:
219
print(f"Invalid pin specification: {e}")
220
```