0
# Adafruit Blinka
1
2
A comprehensive CircuitPython API emulation library that enables CircuitPython code to run on devices running CPython or MicroPython. Blinka provides hardware abstraction for GPIO operations, communication protocols, and peripheral interfaces across 100+ supported development boards and single-board computers.
3
4
## Package Information
5
6
- **Package Name**: adafruit-blinka
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install adafruit-blinka`
10
11
## Core Imports
12
13
```python
14
import board
15
import digitalio
16
import analogio
17
import busio
18
```
19
20
For specific modules:
21
22
```python
23
from adafruit_blinka import ContextManaged, Lockable
24
import microcontroller
25
```
26
27
## Basic Usage
28
29
```python
30
import board
31
import digitalio
32
import time
33
34
# Configure a digital output pin
35
led = digitalio.DigitalInOut(board.D18)
36
led.direction = digitalio.Direction.OUTPUT
37
38
# Blink the LED
39
for i in range(10):
40
led.value = True
41
time.sleep(0.5)
42
led.value = False
43
time.sleep(0.5)
44
45
# Cleanup
46
led.deinit()
47
```
48
49
## Architecture
50
51
Adafruit-Blinka uses a layered architecture to provide CircuitPython compatibility:
52
53
- **Platform Detection**: Automatic hardware detection and driver loading via `adafruit_blinka.agnostic`
54
- **Hardware Abstraction**: Board-specific pin mappings and microcontroller implementations
55
- **Resource Management**: Context managers and locking mechanisms for safe hardware access
56
- **Protocol Implementation**: Software and hardware implementations of I2C, SPI, UART, PWM
57
- **CircuitPython API Compatibility**: Identical interfaces and behavior to CircuitPython
58
59
This design enables seamless migration of CircuitPython code to CPython environments while maintaining hardware portability across diverse platforms from Raspberry Pi to FTDI USB adapters.
60
61
## Capabilities
62
63
### Digital Input/Output
64
65
GPIO pin control with direction, pull resistors, and drive modes. Provides CircuitPython-compatible digital I/O operations with automatic resource management.
66
67
```python { .api }
68
class DigitalInOut(ContextManaged):
69
def __init__(self, pin):
70
"""Initialize digital I/O pin"""
71
72
@property
73
def direction(self) -> Direction:
74
"""Pin direction (INPUT or OUTPUT)"""
75
76
@direction.setter
77
def direction(self, value: Direction) -> None:
78
"""Set pin direction"""
79
80
@property
81
def value(self) -> bool:
82
"""Pin logic level (True=HIGH, False=LOW)"""
83
84
@value.setter
85
def value(self, val: bool) -> None:
86
"""Set pin logic level"""
87
88
@property
89
def pull(self) -> Pull:
90
"""Pull resistor configuration"""
91
92
@pull.setter
93
def pull(self, val: Pull) -> None:
94
"""Configure pull resistor"""
95
96
def switch_to_output(self, value: bool = False, drive_mode: DriveMode = DriveMode.PUSH_PULL) -> None:
97
"""Switch pin to output mode"""
98
99
def switch_to_input(self, pull: Pull = None) -> None:
100
"""Switch pin to input mode"""
101
102
class Direction:
103
INPUT: Direction
104
OUTPUT: Direction
105
106
class Pull:
107
UP: Pull
108
DOWN: Pull
109
110
class DriveMode:
111
PUSH_PULL: DriveMode
112
OPEN_DRAIN: DriveMode
113
```
114
115
[Digital I/O](./digital-io.md)
116
117
### Analog Input/Output
118
119
Analog-to-digital conversion and digital-to-analog output with platform-specific implementations. Supports reading sensor values and generating analog signals.
120
121
```python { .api }
122
class AnalogIn:
123
def __init__(self, pin):
124
"""Initialize analog input pin"""
125
126
@property
127
def value(self) -> int:
128
"""Raw ADC value (0-65535)"""
129
130
@property
131
def voltage(self) -> float:
132
"""Voltage reading in volts"""
133
134
class AnalogOut:
135
def __init__(self, pin):
136
"""Initialize analog output pin (DAC)"""
137
138
@property
139
def value(self) -> int:
140
"""DAC output value (0-65535)"""
141
142
@value.setter
143
def value(self, val: int) -> None:
144
"""Set DAC output value"""
145
```
146
147
[Analog I/O](./analog-io.md)
148
149
### Communication Protocols
150
151
Hardware and software implementations of I2C, SPI, and UART communication protocols with automatic resource locking and CircuitPython compatibility.
152
153
```python { .api }
154
class I2C(Lockable):
155
def __init__(self, scl, sda, frequency: int = 100000):
156
"""Initialize I2C bus"""
157
158
def scan(self) -> list[int]:
159
"""Scan for I2C devices, return list of addresses"""
160
161
def readfrom_into(self, address: int, buffer: bytearray, start: int = 0, end: int = None) -> None:
162
"""Read from device into buffer"""
163
164
def writeto(self, address: int, buffer: bytes, start: int = 0, end: int = None) -> None:
165
"""Write buffer to device"""
166
167
class SPI(Lockable):
168
def __init__(self, clock, MOSI=None, MISO=None):
169
"""Initialize SPI bus"""
170
171
def configure(self, baudrate: int = 100000, polarity: int = 0, phase: int = 0, bits: int = 8) -> None:
172
"""Configure SPI parameters"""
173
174
def write(self, buf: bytes) -> None:
175
"""Write data to SPI bus"""
176
177
def readinto(self, buf: bytearray) -> None:
178
"""Read data from SPI bus into buffer"""
179
180
class UART:
181
def __init__(self, tx, rx, baudrate: int = 9600, bits: int = 8, parity=None, stop: int = 1, timeout: float = 1.0):
182
"""Initialize UART interface"""
183
184
def read(self, nbytes: int = None) -> bytes:
185
"""Read data from UART"""
186
187
def write(self, buf: bytes) -> int:
188
"""Write data to UART, return bytes written"""
189
```
190
191
[Communication Protocols](./communication.md)
192
193
### PWM and Pulse Control
194
195
Pulse Width Modulation output and pulse measurement capabilities for motor control, servo positioning, and signal generation.
196
197
```python { .api }
198
class PWMOut:
199
def __init__(self, pin, duty_cycle: int = 0, frequency: int = 500, variable_frequency: bool = False):
200
"""Initialize PWM output pin"""
201
202
@property
203
def duty_cycle(self) -> int:
204
"""PWM duty cycle (0-65535)"""
205
206
@duty_cycle.setter
207
def duty_cycle(self, val: int) -> None:
208
"""Set PWM duty cycle"""
209
210
@property
211
def frequency(self) -> int:
212
"""PWM frequency in Hz"""
213
214
@frequency.setter
215
def frequency(self, val: int) -> None:
216
"""Set PWM frequency"""
217
218
class PulseIn:
219
def __init__(self, pin, maxlen: int = 100, idle_state: bool = False):
220
"""Initialize pulse input measurement"""
221
222
def __len__(self) -> int:
223
"""Number of pulses captured"""
224
225
def __getitem__(self, index: int) -> int:
226
"""Get pulse duration in microseconds"""
227
```
228
229
[PWM and Pulse Control](./pwm-pulse.md)
230
231
### Board Pin Definitions
232
233
Platform-specific pin mappings and hardware interfaces with automatic detection and configuration for 100+ supported development boards.
234
235
```python { .api }
236
# Board-specific pin constants (examples)
237
D0: Pin # Digital pin 0
238
D1: Pin # Digital pin 1
239
SDA: Pin # I2C data pin
240
SCL: Pin # I2C clock pin
241
MOSI: Pin # SPI data out
242
MISO: Pin # SPI data in
243
SCLK: Pin # SPI clock
244
245
def I2C() -> busio.I2C:
246
"""Return default I2C interface if available"""
247
248
def SPI() -> busio.SPI:
249
"""Return default SPI interface if available"""
250
251
# Version information
252
__version__: str # Blinka version
253
__repo__: str # Repository URL
254
__blinka__: bool # Always True for identification
255
```
256
257
[Board Definitions](./board-pins.md)
258
259
### Specialized Peripherals
260
261
Support for advanced peripherals including NeoPixel LED strips, rotary encoders, keypads, and USB HID devices.
262
263
```python { .api }
264
def neopixel_write(gpio, buf: bytes) -> None:
265
"""Write color buffer to NeoPixel LED strip"""
266
267
class IncrementalEncoder:
268
def __init__(self, pin_a, pin_b):
269
"""Initialize rotary encoder"""
270
271
@property
272
def position(self) -> int:
273
"""Current encoder position"""
274
275
class Keys:
276
def __init__(self, pins, value_when_pressed: bool = False, pull_up: bool = True):
277
"""Initialize key scanner"""
278
279
@property
280
def events(self) -> EventQueue:
281
"""Key event queue"""
282
283
class Device:
284
def __init__(self, descriptor: bytes, usage_page: int, usage: int, report_ids: tuple, in_report_lengths: tuple, out_report_lengths: tuple):
285
"""Initialize USB HID device"""
286
287
def send_report(self, report: bytes, report_id: int = None) -> None:
288
"""Send HID report"""
289
```
290
291
[Specialized Peripherals](./peripherals.md)
292
293
### Core Framework
294
295
Base classes and utilities that provide resource management, platform detection, and CircuitPython compatibility features.
296
297
```python { .api }
298
class ContextManaged:
299
def deinit(self) -> None:
300
"""Release hardware resources"""
301
302
def __enter__(self):
303
"""Context manager entry"""
304
305
def __exit__(self, exc_type, exc_val, exc_tb):
306
"""Context manager exit with automatic cleanup"""
307
308
class Lockable(ContextManaged):
309
def try_lock(self) -> bool:
310
"""Attempt to acquire exclusive lock"""
311
312
def unlock(self) -> None:
313
"""Release exclusive lock"""
314
315
def load_settings_toml() -> None:
316
"""Load settings from settings.toml into environment"""
317
318
def patch_system() -> None:
319
"""Apply platform-specific system patches"""
320
321
def delay_us(delay: int) -> None:
322
"""Microsecond precision delay"""
323
324
# Platform detection
325
detector: object # Platform detection instance
326
chip_id: str # Detected chip identifier
327
board_id: str # Detected board identifier
328
implementation: str # Python implementation name
329
```
330
331
[Core Framework](./core-framework.md)
332
333
### Software Bit-banged Protocols
334
335
Software implementations of I2C and SPI communication protocols for platforms without dedicated hardware peripherals or when hardware resources are already in use.
336
337
```python { .api }
338
class I2C(Lockable):
339
def __init__(self, scl, sda, frequency: int = 400000):
340
"""Initialize software I2C interface"""
341
342
def scan(self) -> list[int]:
343
"""Scan I2C bus for connected devices"""
344
345
def readfrom_into(self, address: int, buffer: bytearray, start: int = 0, end: int = None) -> None:
346
"""Read data from I2C device into buffer"""
347
348
def writeto(self, address: int, buffer: bytes, start: int = 0, end: int = None, stop: bool = True) -> int:
349
"""Write data to I2C device from buffer"""
350
351
class SPI(Lockable):
352
def __init__(self, clock, MOSI=None, MISO=None):
353
"""Initialize software SPI interface"""
354
355
def configure(self, baudrate: int = 100000, polarity: int = 0, phase: int = 0, bits: int = 8) -> None:
356
"""Configure SPI communication parameters"""
357
358
def write(self, buf: bytes) -> None:
359
"""Write data to SPI device"""
360
361
def readinto(self, buf: bytearray) -> None:
362
"""Read data from SPI device into buffer"""
363
```
364
365
[Software Protocols](./bitbangio.md)
366
367
## Utility Functions
368
369
Color generation and MicroPython compatibility utilities that enhance the CircuitPython API emulation.
370
371
```python { .api }
372
# Color utilities (rainbowio module)
373
def colorwheel(color_value: int) -> int:
374
"""Generate rainbow colors from 0-255 input value"""
375
376
# MicroPython compatibility decorators (micropython module)
377
def const(x):
378
"""Emulate making a constant (MicroPython compatibility)"""
379
380
def native(f):
381
"""Emulate native decorator (MicroPython compatibility)"""
382
383
def viper(f):
384
"""MicroPython viper decorator - not supported (raises SyntaxError)"""
385
386
def asm_thumb(f):
387
"""MicroPython inline assembler decorator - not supported (raises SyntaxError)"""
388
```
389
390
[Utility Functions](./utilities.md)
391
392
## Types
393
394
```python { .api }
395
class Pin:
396
"""Hardware pin reference"""
397
id: int
398
399
class Enum:
400
"""CircuitPython-style enum base class"""
401
def iteritems(self):
402
"""Iterate over enum items"""
403
```
404
405
## Version Information
406
407
```python { .api }
408
__version__: str # Package version string
409
VERSION: str # Alias for __version__
410
```