busio – Hardware accelerated external bus access

The busio module contains classes to support a variety of serial protocols.

When the microcontroller does not support the behavior in a hardware accelerated fashion it may internally use a bitbang routine. However, if hardware support is available on a subset of pins but not those provided, then a RuntimeError will be raised. Use the bitbangio module to explicitly bitbang a serial protocol on any general purpose pins.

All classes change hardware state and should be deinitialized when they are no longer needed if the program continues after use. To do so, either call deinit() or use a context manager. See Lifetime and ContextManagers for more info.

For example:

import busio
from board import *

i2c = busio.I2C(SCL, SDA)
print(i2c.scan())
i2c.deinit()

This example will initialize the the device, run scan() and then deinit() the hardware. The last step is optional because CircuitPython automatically resets hardware after a program finishes.

Available on these boards
  • 8086 Commander
  • @sarfata shIRtty
  • ARAMCON Badge 2019
  • ARAMCON2 Badge
  • ATMegaZero ESP32-S2
  • Adafruit BLM Badge
  • Adafruit CLUE nRF52840 Express
  • Adafruit Circuit Playground Bluefruit
  • Adafruit Circuit Playground Express 4-H
  • Adafruit CircuitPlayground Express
  • Adafruit CircuitPlayground Express with Crickit libraries
  • Adafruit CircuitPlayground Express with displayio
  • Adafruit EdgeBadge
  • Adafruit Feather Bluefruit Sense
  • Adafruit Feather M0 Adalogger
  • Adafruit Feather M0 Basic
  • Adafruit Feather M0 Express
  • Adafruit Feather M0 Express with Crickit libraries
  • Adafruit Feather M0 RFM69
  • Adafruit Feather M0 RFM9x
  • Adafruit Feather M4 CAN
  • Adafruit Feather M4 Express
  • Adafruit Feather MIMXRT1011
  • Adafruit Feather RP2040
  • Adafruit Feather STM32F405 Express
  • Adafruit Feather nRF52840 Express
  • Adafruit FunHouse
  • Adafruit Gemma M0
  • Adafruit Gemma M0 PyCon 2018
  • Adafruit Grand Central M4 Express
  • Adafruit Hallowing M4 Express
  • Adafruit ItsyBitsy M0 Express
  • Adafruit ItsyBitsy M4 Express
  • Adafruit ItsyBitsy RP2040
  • Adafruit ItsyBitsy nRF52840 Express
  • Adafruit LED Glasses Driver nRF52840
  • Adafruit Macropad RP2040
  • Adafruit MagTag
  • Adafruit Matrix Portal M4
  • Adafruit Metro ESP32S2
  • Adafruit Metro M0 Express
  • Adafruit Metro M4 Airlift Lite
  • Adafruit Metro M4 Express
  • Adafruit Metro nRF52840 Express
  • Adafruit Monster M4SK
  • Adafruit ProxLight Trinkey M0
  • Adafruit PyGamer
  • Adafruit PyPortal
  • Adafruit PyPortal Pynt
  • Adafruit PyPortal Titano
  • Adafruit PyRuler
  • Adafruit Pybadge
  • Adafruit QT Py M0
  • Adafruit QT Py M0 Haxpress
  • Adafruit QT Py RP2040
  • Adafruit QT2040 Trinkey
  • Adafruit Trellis M4 Express
  • Adafruit Trinket M0
  • AloriumTech Evo M51
  • Arduino MKR Zero
  • Arduino MKR1300
  • Arduino Nano 33 BLE
  • Arduino Nano 33 IoT
  • Arduino Nano RP2040 Connect
  • Arduino Zero
  • Artisense Reference Design RD00
  • AtelierDuMaker nRF52840 Breakout
  • BDMICRO VINA-D21
  • BDMICRO VINA-D51
  • BLE-SS dev board Multi Sensor
  • BastBLE
  • BastWiFi
  • BlueMicro840
  • CP Sapling M0
  • CP Sapling M0 w/ SPI Flash
  • CP32-M4
  • Capable Robot Programmable USB Hub
  • Cedar Grove StringCar M0 Express
  • Challenger RP2040 WiFi
  • Circuit Playground Express Digi-Key PyCon 2019
  • CircuitBrains Basic
  • CircuitBrains Deluxe
  • CrumpS2
  • Cytron Maker Pi RP2040
  • DynOSSAT-EDU-EPS
  • DynOSSAT-EDU-OBC
  • DynaLoRa_USB
  • ESP 12k NodeMCU
  • Electronic Cats Bast Pro Mini M0
  • Electronic Cats CatWAN USBStick
  • Electronic Cats Hunter Cat NFC
  • Electronic Cats NFC Copy Cat
  • Electronut Labs Blip
  • Electronut Labs Papyr
  • EncoderPad RP2040
  • Escornabot Makech
  • Espruino Pico
  • Espruino Wifi
  • Feather ESP32S2 without PSRAM
  • Feather MIMXRT1011
  • Feather MIMXRT1062
  • FeatherS2
  • FeatherS2 Neo
  • FeatherS2 PreRelease
  • Fluff M0
  • Franzininho WIFI w/Wroom
  • Franzininho WIFI w/Wrover
  • Gravitech Cucumber M
  • Gravitech Cucumber MS
  • Gravitech Cucumber R
  • Gravitech Cucumber RS
  • HMI-DevKit-1.1
  • Hacked Feather M0 Express with 8Mbyte SPI flash
  • HalloWing M0 Express
  • HiiBot BlueFi
  • IMXRT1010-EVK
  • IkigaiSense Vita nRF52840
  • J&J Studios datum-Distance
  • J&J Studios datum-IMU
  • J&J Studios datum-Light
  • J&J Studios datum-Weather
  • Kaluga 1
  • LILYGO TTGO T8 ESP32-S2 w/Display
  • LoC BeR M4 base board
  • MDBT50Q-DB-40
  • MDBT50Q-RX Dongle
  • MEOWBIT
  • MORPHEANS MorphESP-240
  • MakerDiary nRF52840 MDK
  • MakerDiary nRF52840 MDK USB Dongle
  • Makerdiary M60 Keyboard
  • Makerdiary Pitaya Go
  • Makerdiary nRF52840 M.2 Developer Kit
  • Meow Meow
  • Metro MIMXRT1011
  • Mini SAM M4
  • NUCLEO STM32F746
  • NUCLEO STM32F767
  • NUCLEO STM32H743
  • OPENMV-H7 R1
  • Oak Dev Tech PixelWing ESP32S2
  • Open Hardware Summit 2020 Badge
  • PCA10056 nRF52840-DK
  • PCA10059 nRF52840 Dongle
  • PCA10100 nRF52833 Dongle
  • PYB LR Nano V2
  • Particle Argon
  • Particle Boron
  • Particle Xenon
  • PewPew 10.2
  • PewPew 13
  • PewPew M4
  • PicoPlanet
  • Pimoroni Interstate 75
  • Pimoroni Keybow 2040
  • Pimoroni PGA2040
  • Pimoroni Pico LiPo (16MB)
  • Pimoroni Pico LiPo (4MB)
  • Pimoroni PicoSystem
  • Pimoroni Plasma 2040
  • Pimoroni Tiny 2040
  • PyCubedv04
  • PyCubedv04-MRAM
  • PyboardV1_1
  • Raspberry Pi Pico
  • Robo HAT MM1 M4
  • S2Mini
  • SAM E54 Xplained Pro
  • SAM32v26
  • SPRESENSE
  • ST STM32F746G Discovery
  • STM32F411E_DISCO
  • STM32F412G_DISCO
  • STM32F4_DISCO
  • Saola 1 w/Wroom
  • Saola 1 w/Wrover
  • Seeeduino Wio Terminal
  • Seeeduino XIAO
  • Serpente
  • Silicognition LLC M4-Shim
  • Simmel
  • SparkFun LUMIDrive
  • SparkFun MicroMod RP2040 Processor
  • SparkFun MicroMod SAMD51 Processor
  • SparkFun MicroMod nRF52840 Processor
  • SparkFun Pro Micro RP2040
  • SparkFun Pro nRF52840 Mini
  • SparkFun Qwiic Micro
  • SparkFun RedBoard Turbo
  • SparkFun SAMD21 Dev Breakout
  • SparkFun SAMD21 Mini Breakout
  • SparkFun STM32 MicroMod Processor
  • SparkFun Thing Plus - RP2040
  • SparkFun Thing Plus - SAMD51
  • Sprite_v2b
  • StackRduino M0 PRO
  • TG-Boards' Datalore IP M4
  • TG-Watch
  • THUNDERPACK_v11
  • THUNDERPACK_v12
  • Targett Module Clip w/Wroom
  • Targett Module Clip w/Wrover
  • Teensy 4.0
  • Teensy 4.1
  • Teknikio Bluebird
  • The Open Book Feather
  • TinkeringTech ScoutMakes Azul
  • TinyS2
  • Trinket M0 Haxpress
  • UARTLogger II
  • WarmBit BluePixel nRF52840
  • Winterbloom Big Honking Button
  • Winterbloom Sol
  • XinaBox CC03
  • XinaBox CS11
  • iMX RT 1020 EVK
  • iMX RT 1060 EVK
  • keithp.com snekboard
  • micro:bit v2
  • microS2
  • nanoESP32-S2 w/Wrover
  • nanoESP32-S2 w/Wroom
  • ndGarage[n°] Bit6: FeatherSnow-v2
  • ndGarage[n°]Bit6:FeatherSnow
  • nice!nano
  • senseBox MCU
  • stm32f411ce-blackpill
  • stm32f411ce-blackpill-with-flash
  • uChip
  • uGame10

class busio.I2C(scl: microcontroller.Pin, sda: microcontroller.Pin, *, frequency: int = 100000, timeout: int = 255)

Two wire serial protocol

I2C is a two-wire protocol for communicating between devices. At the physical level it consists of 2 wires: SCL and SDA, the clock and data lines respectively.

See also

Using this class directly requires careful lock management. Instead, use I2CDevice to manage locks.

See also

Using this class to directly read registers requires manual bit unpacking. Instead, use an existing driver or make one with Register data descriptors.

Parameters
  • scl (Pin) – The clock pin

  • sda (Pin) – The data pin

  • frequency (int) – The clock frequency in Hertz

  • timeout (int) – The maximum clock stretching timeut - (used only for bitbangio.I2C; ignored for busio.I2C)

Note

On the nRF52840, only one I2C object may be created, except on the Circuit Playground Bluefruit, which allows two, one for the onboard accelerometer, and one for offboard use.

deinit(self)None

Releases control of the underlying hardware so other classes can use it.

__enter__(self)I2C

No-op used in Context Managers.

__exit__(self)None

Automatically deinitializes the hardware on context exit. See Lifetime and ContextManagers for more info.

scan(self)List[int]

Scan all I2C addresses between 0x08 and 0x77 inclusive and return a list of those that respond.

Returns

List of device ids on the I2C bus

Return type

list

try_lock(self)bool

Attempts to grab the I2C lock. Returns True on success.

Returns

True when lock has been grabbed

Return type

bool

unlock(self)None

Releases the I2C lock.

readfrom_into(self, address: int, buffer: _typing.WriteableBuffer, *, start: int = 0, end: Optional[int] = None)None

Read into buffer from the device selected by address. The number of bytes read will be the length of buffer. At least one byte must be read.

If start or end is provided, then the buffer will be sliced as if buffer[start:end]. This will not cause an allocation like buf[start:end] will so it saves memory.

Parameters
  • address (int) – 7-bit device address

  • buffer (WriteableBuffer) – buffer to write into

  • start (int) – Index to start writing at

  • end (int) – Index to write up to but not include. Defaults to len(buffer)

writeto(self, address: int, buffer: _typing.ReadableBuffer, *, start: int = 0, end: Optional[int] = None, stop: bool = True)None

Write the bytes from buffer to the device selected by address and then transmit a stop bit.

If start or end is provided, then the buffer will be sliced as if buffer[start:end]. This will not cause an allocation like buffer[start:end] will so it saves memory.

Writing a buffer or slice of length zero is permitted, as it can be used to poll for the existence of a device.

Parameters
  • address (int) – 7-bit device address

  • buffer (ReadableBuffer) – buffer containing the bytes to write

  • start (int) – Index to start writing from

  • end (int) – Index to read up to but not include. Defaults to len(buffer)

writeto_then_readfrom(self, address: int, out_buffer: _typing.ReadableBuffer, in_buffer: _typing.WriteableBuffer, *, out_start: int = 0, out_end: Optional[int] = None, in_start: int = 0, in_end: Optional[int] = None)None

Write the bytes from out_buffer to the device selected by address, generate no stop bit, generate a repeated start and read into in_buffer. out_buffer and in_buffer can be the same buffer because they are used sequentially.

If start or end is provided, then the corresponding buffer will be sliced as if buffer[start:end]. This will not cause an allocation like buf[start:end] will so it saves memory.

Parameters
  • address (int) – 7-bit device address

  • out_buffer (ReadableBuffer) – buffer containing the bytes to write

  • in_buffer (WriteableBuffer) – buffer to write into

  • out_start (int) – Index to start writing from

  • out_end (int) – Index to read up to but not include. Defaults to len(buffer)

  • in_start (int) – Index to start writing at

  • in_end (int) – Index to write up to but not include. Defaults to len(buffer)

class busio.SPI(clock: microcontroller.Pin, MOSI: Optional[microcontroller.Pin] = None, MISO: Optional[microcontroller.Pin] = None)

A 3-4 wire serial protocol

SPI is a serial protocol that has exclusive pins for data in and out of the main device. It is typically faster than I2C because a separate pin is used to select a device rather than a transmitted address. This class only manages three of the four SPI lines: clock, MOSI, MISO. Its up to the client to manage the appropriate select line, often abbreviated CS or SS. (This is common because multiple secondaries can share the clock, MOSI and MISO lines and therefore the hardware.)

Construct an SPI object on the given pins.

Note

The SPI peripherals allocated in order of desirability, if possible, such as highest speed and not shared use first. For instance, on the nRF52840, there is a single 32MHz SPI peripheral, and multiple 8MHz peripherals, some of which may also be used for I2C. The 32MHz SPI peripheral is returned first, then the exclusive 8MHz SPI peripheral, and finally the shared 8MHz peripherals.

See also

Using this class directly requires careful lock management. Instead, use SPIDevice to manage locks.

See also

Using this class to directly read registers requires manual bit unpacking. Instead, use an existing driver or make one with Register data descriptors.

Parameters
  • clock (Pin) – the pin to use for the clock.

  • MOSI (Pin) – the Main Out Selected In pin.

  • MISO (Pin) – the Main In Selected Out pin.

frequency :int

The actual SPI bus frequency. This may not match the frequency requested due to internal limitations.

deinit(self)None

Turn off the SPI bus.

__enter__(self)SPI

No-op used by Context Managers. Provided by context manager helper.

__exit__(self)None

Automatically deinitializes the hardware when exiting a context. See Lifetime and ContextManagers for more info.

configure(self, *, baudrate: int = 100000, polarity: int = 0, phase: int = 0, bits: int = 8)None

Configures the SPI bus. The SPI object must be locked.

Parameters
  • baudrate (int) – the desired clock rate in Hertz. The actual clock rate may be higher or lower due to the granularity of available clock settings. Check the frequency attribute for the actual clock rate.

  • polarity (int) – the base state of the clock line (0 or 1)

  • phase (int) – the edge of the clock that data is captured. First (0) or second (1). Rising or falling depends on clock polarity.

  • bits (int) – the number of bits per word

Note

On the SAMD21, it is possible to set the baudrate to 24 MHz, but that speed is not guaranteed to work. 12 MHz is the next available lower speed, and is within spec for the SAMD21.

Note

On the nRF52840, these baudrates are available: 125kHz, 250kHz, 1MHz, 2MHz, 4MHz, and 8MHz. If you pick a a baudrate other than one of these, the nearest lower baudrate will be chosen, with a minimum of 125kHz. Two SPI objects may be created, except on the Circuit Playground Bluefruit, which allows only one (to allow for an additional I2C object).

try_lock(self)bool

Attempts to grab the SPI lock. Returns True on success.

Returns

True when lock has been grabbed

Return type

bool

unlock(self)None

Releases the SPI lock.

write(self, buffer: _typing.ReadableBuffer, *, start: int = 0, end: Optional[int] = None)None

Write the data contained in buffer. The SPI object must be locked. If the buffer is empty, nothing happens.

Parameters
  • buffer (ReadableBuffer) – Write out the data in this buffer

  • start (int) – Start of the slice of buffer to write out: buffer[start:end]

  • end (int) – End of the slice; this index is not included. Defaults to len(buffer)

readinto(self, buffer: _typing.WriteableBuffer, *, start: int = 0, end: Optional[int] = None, write_value: int = 0)None

Read into buffer while writing write_value for each byte read. The SPI object must be locked. If the number of bytes to read is 0, nothing happens.

Parameters
  • buffer (WriteableBuffer) – Read data into this buffer

  • start (int) – Start of the slice of buffer to read into: buffer[start:end]

  • end (int) – End of the slice; this index is not included. Defaults to len(buffer)

  • write_value (int) – Value to write while reading. (Usually ignored.)

write_readinto(self, buffer_out: _typing.ReadableBuffer, buffer_in: _typing.WriteableBuffer, *, out_start: int = 0, out_end: Optional[int] = None, in_start: int = 0, in_end: Optional[int] = None)None

Write out the data in buffer_out while simultaneously reading data into buffer_in. The SPI object must be locked. The lengths of the slices defined by buffer_out[out_start:out_end] and buffer_in[in_start:in_end] must be equal. If buffer slice lengths are both 0, nothing happens.

Parameters
  • buffer_out (ReadableBuffer) – Write out the data in this buffer

  • buffer_in (WriteableBuffer) – Read data into this buffer

  • out_start (int) – Start of the slice of buffer_out to write out: buffer_out[out_start:out_end]

  • out_end (int) – End of the slice; this index is not included. Defaults to len(buffer_out)

  • in_start (int) – Start of the slice of buffer_in to read into: buffer_in[in_start:in_end]

  • in_end (int) – End of the slice; this index is not included. Defaults to len(buffer_in)

class busio.UART(tx: microcontroller.Pin, rx: microcontroller.Pin, *, baudrate: int = 9600, bits: int = 8, parity: Optional[Parity] = None, stop: int = 1, timeout: float = 1, receiver_buffer_size: int = 64)

A bidirectional serial protocol

A common bidirectional serial protocol that uses an an agreed upon speed rather than a shared clock line.

Parameters
  • tx (Pin) – the pin to transmit with, or None if this UART is receive-only.

  • rx (Pin) – the pin to receive on, or None if this UART is transmit-only.

  • rts (Pin) – the pin for rts, or None if rts not in use.

  • cts (Pin) – the pin for cts, or None if cts not in use.

  • rs485_dir (Pin) – the output pin for rs485 direction setting, or None if rs485 not in use.

  • rs485_invert (bool) – rs485_dir pin active high when set. Active low otherwise.

  • baudrate (int) – the transmit and receive speed.

  • bits (int) – the number of bits per byte, 5 to 9.

  • parity (Parity) – the parity used for error checking.

  • stop (int) – the number of stop bits, 1 or 2.

  • timeout (float) – the timeout in seconds to wait for the first character and between subsequent characters when reading. Raises ValueError if timeout >100 seconds.

  • receiver_buffer_size (int) – the character length of the read buffer (0 to disable). (When a character is 9 bits the buffer will be 2 * receiver_buffer_size bytes.)

New in CircuitPython 4.0: timeout has incompatibly changed units from milliseconds to seconds. The new upper limit on timeout is meant to catch mistaken use of milliseconds.

baudrate :int

The current baudrate.

in_waiting :int

The number of bytes in the input buffer, available to be read

timeout :float

The current timeout, in seconds (float).

deinit(self)None

Deinitialises the UART and releases any hardware resources for reuse.

__enter__(self)UART

No-op used by Context Managers.

__exit__(self)None

Automatically deinitializes the hardware when exiting a context. See Lifetime and ContextManagers for more info.

read(self, nbytes: Optional[int] = None)Optional[bytes]

Read characters. If nbytes is specified then read at most that many bytes. Otherwise, read everything that arrives until the connection times out. Providing the number of bytes expected is highly recommended because it will be faster.

Returns

Data read

Return type

bytes or None

readinto(self, buf: _typing.WriteableBuffer)Optional[int]

Read bytes into the buf. Read at most len(buf) bytes.

Returns

number of bytes read and stored into buf

Return type

int or None (on a non-blocking error)

New in CircuitPython 4.0: No length parameter is permitted.

readline(self)bytes
Read a line, ending in a newline character, or

return None if a timeout occurs sooner, or return everything readable if no newline is found and timeout=0

Returns

the line read

Return type

bytes or None

write(self, buf: _typing.WriteableBuffer)Optional[int]

Write the buffer of bytes to the bus.

New in CircuitPython 4.0: buf must be bytes, not a string.

return

the number of bytes written

rtype

int or None

reset_input_buffer(self)None

Discard any unread characters in the input buffer.

class busio.Parity

Enum-like class to define the parity used to verify correct data transfer.

ODD :int

Total number of ones should be odd.

EVEN :int

Total number of ones should be even.