Conghao97's picture tcftrees's picture
ProgramGen release
d086025
|
Raw History Blame Contribute Delete
34.6 kB

adafruit/adafruit_circuitpython_bitbangio

Project Overview

adafruit_bitbangio is a pure-Python CircuitPython library that adds software (bit-banged) I2C and SPI bus support to boards that do not provide the built-in bitbangio module. Its purpose is to let CircuitPython code talk to I2C and SPI peripherals over ordinary GPIO pins, following the same application programming interface as the core bitbangio module so that existing driver code works as a drop-in replacement (imported as adafruit_bitbangio as bitbangio). Because the interface mirrors the core API, it intentionally omits bit-order and chip-select options, and Adafruit recommends the native bitbangio module where available, since its timing is more reliable. The scope is deliberately narrow: it implements the two bus protocols and nothing more, leaving device-specific logic to other drivers that consume these bus objects. The architecture is contained in a single module, adafruit_bitbangio.py. A _BitBangIO base class supplies shared behavior, including lock management (try_lock/unlock with a lock-check guard), context-manager support, and deinit. The I2C class implements the I2C protocol over configurable SCL and SDA pins with a configurable frequency and timeout, emulating open-drain signaling by switching pins between input and output states; the SPI class implements SPI over SCLK, MOSI, and MISO pins. Protocol timing is driven by busy-wait delays computed from time.monotonic. Supporting components include runnable examples (examples/), a test suite that exercises the buses against simulated I2C and SPI devices (tests/simulator.py, simulated_i2c.py, simulated_spi.py), Sphinx documentation under docs/, and standard Adafruit CircuitPython library tooling such as ruff linting, pre-commit hooks, and Read the Docs configuration.

Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance.

Submission Constraints (read carefully — the evaluation depends on these)

This is a closed-book task. The graded test suite is hidden and will be injected into the workspace at evaluation time. To be scored correctly you MUST follow these rules:

  1. Do NOT create or modify any files under the test directories (e.g. tests/, test/, testing/, or files named test_*.py / conftest.py). The grader injects its own test files at those paths; any file you place there will collide with the injected suite and cause the whole evaluation to score 0. Implement only the library/source code — never the tests.

  2. Your package MUST be importable by the name the tests use. The hidden tests import your package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a valid pyproject.toml / setup.py / setup.cfg and lay out your modules so that pip install -e . succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0.

  3. Match the documented module paths and public API exactly (names, signatures, and any literal error/exception strings). Internal helpers not listed in the API guide may be implemented however you like.

Install / Reconstruction Contract

Follow this contract before implementing the documented APIs:

  • Project root: /workspace/repo at runtime; the submitted repository root is ..
  • Package/distribution name: adafruit-circuitpython-bitbangio
  • Package roots: .
  • Install strategy: editable-install
  • Import/entry: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package.
  • Provision commands:
    python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQgaW5zdGFsbGVyIGNvbnRyb2xzIFBFUCA1MTcgYnVpbGQgZGVwZW5kZW5jaWVzIG9ubHkuIEl0IGRvZXMKICAgICMgbm90IHVwZ3JhZGUgcGlwL3NldHVwdG9vbHMgaW4gdGhlIG1lYXN1cmVkIHByb2plY3QncyBydW50aW1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BwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))'
    programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; }
    export -f programgen_pip_install
    programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel
    programgen_pip_install python3 -m pip install setuptools wheel setuptools-scm
    (
    programgen_install_report="$(mktemp)"
    trap 'rm -f "$programgen_install_report"' EXIT
    SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report"
    python3 -c 'exec("import json,subprocess,sys\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\nreport=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"'))\n\nrequested={canonicalize_name(name) for name in ()}\nrequirements=[]\nfor item in report.get('"'"'install'"'"', []):\n    metadata=item.get('"'"'metadata'"'"', {})\n    name=canonicalize_name(metadata.get('"'"'name'"'"', '"'"''"'"'))\n    provided={canonicalize_name(value) for value in metadata.get('"'"'provides_extra'"'"', [])}\n    selected={'"'"''"'"'} | (provided & requested)\n    parsed=[Requirement(value) for value in metadata.get('"'"'requires_dist'"'"', [])]\n    while True:\n        added=set()\n        for requirement in parsed:\n            if requirement.marker is not None and not any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n                continue\n            if canonicalize_name(requirement.name)==name:\n                if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('"'"'version'"'"', '"'"''"'"'), prereleases=True)):\n                    raise ValueError('"'"'local extra requires a different target distribution'"'"')\n                extras={canonicalize_name(value) for value in requirement.extras}\n                if not extras <= provided:\n                    raise ValueError('"'"'local extra refers to an undeclared extra'"'"')\n                added.update(extras - selected)\n        if not added:\n            break\n        selected.update(added)\n    for requirement in parsed:\n        if canonicalize_name(requirement.name)==name:\n            continue\n        if requirement.marker is None or any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n            requirement.marker=None\n            requirements.append(str(requirement))\nrequirements=list(dict.fromkeys(requirements))\nsubprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None\n")' "$programgen_install_report"
    )
    
  • Runtime setup:
    {
      [ -e "$PWD"/README.rst ] || { mkdir -p "$(dirname "$PWD"/README.rst)"; : > "$PWD"/README.rst; };
      SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps;
    }
    
  • Project root for installation: .
  • Build-version environment: SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0, PDM_BUILD_SCM_VERSION=0.0.0, POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0, UV_DYNAMIC_VERSIONING_BYPASS=0.0.0
  • Test directory: tests
  • Test command: bash -lc 'set -uo pipefail run=(python3 -m pytest -vv --continue-on-collection-errors -o addopts= tests/test_adafruit_bitbangio_i2c.py tests/test_adafruit_bitbangio_spi.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv --continue-on-collection-errors -o addopts= tests/test_adafruit_bitbangio_i2c.py tests/test_adafruit_bitbangio_spi.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_adafruit_bitbangio_i2c.py tests/test_adafruit_bitbangio_spi.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"') fi "${run[@]}"; exit $?'
  • Test startup: run the exact test command above from the project root after installation; hidden tests are injected separately.

Environment & Project Structure

  • Language: python
  • Build system: python
  • Test command: bash -lc set -uo pipefail run=(python3 -m pytest -vv --continue-on-collection-errors -o addopts= tests/test_adafruit_bitbangio_i2c.py tests/test_adafruit_bitbangio_spi.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv --continue-on-collection-errors -o addopts= tests/test_adafruit_bitbangio_i2c.py tests/test_adafruit_bitbangio_spi.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_adafruit_bitbangio_i2c.py tests/test_adafruit_bitbangio_spi.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}') fi "${run[@]}"; exit $?

Project Directory Structure

.gitattributes
.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md
.github/workflows/build.yml
.github/workflows/failure-help-text.yml
.github/workflows/release_gh.yml
.github/workflows/release_pypi.yml
.gitignore
.pre-commit-config.yaml
.readthedocs.yaml
CODE_OF_CONDUCT.md
LICENSE
LICENSES/CC-BY-4.0.txt
LICENSES/MIT.txt
LICENSES/Unlicense.txt
README.rst
README.rst.license
adafruit_bitbangio.py
docs/_static/custom.css
docs/_static/favicon.ico
docs/_static/favicon.ico.license
docs/api.rst
docs/api.rst.license
docs/conf.py
docs/examples.rst
docs/examples.rst.license
docs/index.rst
docs/index.rst.license
docs/requirements.txt
examples/bitbangio_simpletest.py
optional_requirements.txt
pyproject.toml
requirements.txt
ruff.toml

API Usage Guide

Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely.

Capability: Bitbangio-compatible software I/O module

Purpose

adafruit_bitbangio re-implements the core CircuitPython bitbangio interface in pure Python so existing driver code runs unchanged on boards that lack the native module (import adafruit_bitbangio as bitbangio). The public surface is deliberately minimal: the I2C and SPI software bus classes, the shared _BitBangIO base (subclassing only), and the bit-order constants MSBFIRST = 0 / LSBFIRST = 1, which exist purely for interface parity — no parameter in this library consumes them, and data is always clocked MSB-first. There are no bit-order or chip-select options anywhere. Every pin transition and every delay is performed with digitalio.DigitalInOut objects plus busy waits measured against time.monotonic, so the module works wherever digitalio works, including pins that cannot do hardware open-drain.

How the components relate

_BitBangIO is the shared skeleton: it owns the lock flag, the lock protocol (try_lock / unlock / the internal _check_lock guard), the context-manager pair, and a no-op deinit. I2C and SPI inherit all of that and add their pins, timing constants, and protocol state machines. Realistic driver workflows always have the same shape:

  1. Construct the bus over pin objects (microcontroller.Pin or board.*).
  2. Acquire the lock (spin on try_lock()).
  3. Issue transactions; each one re-checks the lock and raises immediately when the bus is not locked.
  4. unlock(), then eventually deinit().

Lock state machine (shared)

  • New objects start unlocked. try_lock() returns True once, then False until the next unlock(); it is not reentrant. unlock() on an unlocked bus raises ValueError (message: Not locked).
  • Every I2C transaction and scan(), plus SPI.configure(), funnels through _check_lock, which raises RuntimeError (First call try_lock()) when the flag is clear. The check runs after argument defaulting/slicing — and, for SPI data methods, after the MOSI/MISO/slice-length prechecks (ordering below).
  • __enter__ returns self without taking the lock; __exit__ calls deinit() unconditionally, even on exception. A with block therefore releases the pins when it exits; use it only for one-shot buses, otherwise lock/unlock manually.

Construction and lifecycle

  • I2C.init wraps SCL and SDA in DigitalInOut and immediately switches both to input: the bus starts released (high through external pull-ups) and the constructor does not take the lock. The half-period delay (1 / frequency) / 2 and the clock-stretch timeout are captured here.
  • SPI.init runs an internal acquire loop (while self.try_lock(): pass — the first call succeeds, the second returns False and ends the loop), sets SCLK as output, MOSI (if given) as output, MISO (if given) as input, calls configure() with its defaults, then unlocks. Net state after construction: bus unlocked, frequency reports 100000, SCLK parked at the idle level (polarity 0 → low). A fresh SPI bus is ready for transactions as soon as it is locked; a fresh I2C bus raises on any transaction until locked.
  • deinit: I2C deinits SDA then SCL; SPI deinits SCLK, then MISO, then MOSI, skipping absent optional pins. Because __exit__ deinit's, never reuse a bus object after a with block.

Defaults

  • I2C: frequency=400000 (half period 1.25 µs), timeout=1 second (used only for clock stretching on SCL release).
  • SPI: baudrate=100000, polarity=0, phase=0, bits=8. The half period (1 / baudrate) / 2 is recomputed on each configure() call.
  • SPI.frequency is a read-only property returning the configured baudrate, not the achieved toggle rate; real throughput is lower because each half cycle carries Python-level overhead.

I2C in detail

  • Open-drain emulation. The code never drives a line high: high means switched to input (the pull-up lifts it), low means switch_to_output(value=False). Both lines start as inputs.
  • Addressing. 7-bit only. The wire byte is address << 1 for writes and address << 1 | 1 for reads. scan() probes every address from 0x00 through 0x7F inclusive, ascending, using START + address-write + STOP, and returns the ACKing addresses — including reserved 0x00/0x7F if a device ACKs them. scan() requires the lock.
  • Byte order. All bytes shift out and in MSB-first (0x80 >> bit).
  • Wait timing — independent, not chained. Every half-period wait recomputes end = monotonic() + (1 / frequency) / 2 at the moment that particular wait begins, then busy-spins until the deadline. Each I2C half period is therefore a full (1 / frequency) / 2 window measured from its own start: waits are independent (not chained), and pin-switching or Python overhead spent between waits is never credited against the next window — the opposite of SPI's chained model. Since the guide asserts behavior is fully deterministic given monotonic time, this I2C/SPI asymmetry matters under a mocked clock: equivalent-sized I2C and SPI transfers do not consume the same elapsed time.
  • Clock stretching. Releasing SCL waits up to timeout seconds for the line to read high, then raises the bus-timed-out RuntimeError (message: Bus timed out.). SDA release has no timeout and trusts the pull-up.
  • NACK handling. A NAKed address byte or data byte aborts the transfer by raising RuntimeError with the device address embedded as zero-padded two-digit uppercase hex (0x07, never 0x7). Because the raise bypasses the STOP logic, the aborted frame ends with SCL driven low and SDA released — no STOP was emitted. A later transaction's START sequence releases SCL again first, so the same object can recover the bus, but the peripheral never saw a STOP for the aborted frame.
  • writeto(address, buffer, start, end). Streams buffer[start:end] (end defaults to len(buffer)) after the address byte. An empty slice still emits START + address + STOP, so an empty write still ACK-checks the device and can raise on NACK.
  • readfrom_into(address, buffer, start, end). Reads exactly end - start bytes and stores them at buffer[i + start] — the offset is honored for placement. Every byte except the last is ACKed; the final byte is NAKed per the I2C spec. A zero-length read (end == start) still sends START + read-address + STOP, so NACK still raises.
  • writeto_then_readfrom(address, buffer_out, buffer_in, out_*, in_*). The write phase runs without a STOP; the method then delegates to readfrom_into, producing the repeated-START read phase followed by STOP. The delegation re-enters the lock check (harmless while locked) and applies in_start/in_end offset semantics there. A NACK during the write phase raises before any read byte is clocked.

SPI in detail

  • Modes. polarity sets the idle SCLK level; phase picks edges. The helpers reduce to: phase 0 writes each bit while the clock is at idle and samples on the idle→active edge; phase 1 writes while active and samples on the active→idle edge. All four (polarity, phase) combinations behave like hardware SPI modes 0–3. configure() parks the clock at the new idle level each time it runs, guaranteeing a known idle state before any transfer.
  • Validation order in configure() (all after the lock check): baudrate integer check → bits integer check → bits range 1–8 → polarity in {0, 1} → phase in {0, 1}. All five failures raise ValueError (and are only reachable while locked, since validation sits inside the lock-checked branch — an unlocked call hits the lock-guard RuntimeError first). Python bools pass these checks (bool is an int; True == 1 is in the set).
  • write(buffer, start=0, end=None). start/end are plain positional-or-keyword parameters (unlike the keyword-only out_*/in_* of write_readinto). It clocks bits bit-pairs per byte from buffer[start:end], MSB-first from the top of the byte downward — with bits < 8 the low-order bits of each byte never reach MOSI. An empty slice produces no clock edges, but the unconditional trailing settle wait still elapses one half period of elapsed time; the bus stays idle and nothing raises.
  • readinto(buffer, start=0, end=None, write_value=0). Consumes len(buffer[start:end]) bytes but stores results at buffer[byte_position] — index 0 upward — ignoring the start offset for placement. This is the sharpest asymmetry in the module: I2C readfrom_into honors its offset; SPI readinto does not. Received bits merge via |= / &= ~mask, so with bits = 8 each byte is fully overwritten, and with bits < 8 the untouched low bits keep their prior values. MOSI is optional here: if present, write_value (default 0) is clocked out MSB-first; if absent, only MISO sampling runs.
  • *write_readinto(buffer_out, buffer_in, , out_start, out_end, in_start, in_end). Requires both pins. Prechecks run in this fixed order before the lock check: MOSI presence (RuntimeError) → MISO presence (RuntimeError) → equal slice lengths (RuntimeError: Buffer slices must be equal length) → lock. Both slices empty → no clock edges, but the trailing settle wait still elapses one half period of elapsed time. Placement is correct here: output comes from buffer_out[out_start + i] and input lands at buffer_in[in_start + i]; the out-slice length drives the byte count.
  • Edge timing. Each half period busy-waits until monotonic() reaches start + half_period, and the post-wait time becomes the next half period's start — chained half cycles, each measured from the end of the previous one, so inter-edge overhead is absorbed into the following window rather than extending the transaction.
  • Trailing settle wait. write, readinto, and write_readinto each perform one extra half-period busy wait after the final active→idle transition (inside the locked branch). The settle wait is unconditional: it runs even when the slice is empty and no clock edges occurred. A valid call therefore occupies 2 * bits * bytes + 1 half periods, and a zero-length transfer still consumes one half period of elapsed time under mocked monotonic.

Cross-cutting, test-sensitive notes

  • SPI data methods validate pins/slices before the lock check; I2C methods only default end values before it. An unlocked SPI therefore raises the pin-presence or slice-length error first, while an unlocked I2C raises the lock error even for an empty buffer.
  • Error types: configure()'s five validation failures (baudrate integer, bits integer, bits range 1–8, polarity, phase) raise ValueError, while the MOSI/MISO pin-presence prechecks raise RuntimeError ('Write attempted with no MOSI pin specified.' / 'Read attempted with no MISO pin specified.'), as do the lock guard and the slice-length mismatch. Because lock-guard errors are RuntimeError and configure()'s ValueErrors sit inside the locked branch, an unlocked bus never surfaces configure()'s validation errors — the ValueError-vs-RuntimeError split between these failure families is easy to get wrong in tests.
  • The MOSI/MISO presence errors and the not-locked error fire even for empty buffers — nothing is a silent no-op except zero-length slices of an otherwise valid call, and even those still consume one trailing half period of elapsed time.
  • Buffers are indexed element-wise (buffer[i] = byte, byte & (0x80 >> bit)), so bytearrays, lists of ints, and memoryviews all work; reads mutate the buffer in place.
  • MSBFIRST / LSBFIRST are exported for drop-in compatibility only; nothing reads them.
  • There are no interrupts, background tasks, or hardware peripherals: behavior is fully deterministic given monotonic time, which is what the bundled simulator tests rely on.

Exact API Reference

adafruit_bitbangio.I2C

  • Import Path: from adafruit_bitbangio import I2C
  • Required Test Import Paths:
    • adafruit_bitbangio.I2C
  • Exact Test Import Statements:
    • import adafruit_bitbangio
  • Kind: class
  • Signature:
class I2C(_BitBangIO):
    def __init__(self, scl: Pin, sda: Pin, *, frequency: int=400000, timeout: float=1) -> None
    def deinit(self) -> None
    def scan(self) -> List[int]
    def writeto(self, address: int, buffer: ReadableBuffer, *, start: int=0, end: Optional[int]=None) -> None
    def readfrom_into(self, address: int, buffer: WriteableBuffer, *, start: int=0, end: Optional[int]=None) -> None
    def writeto_then_readfrom(self, address: int, buffer_out: ReadableBuffer, buffer_in: WriteableBuffer, *, out_start: int=0, out_end: Optional[int]=None, in_start: int=0, in_end: Optional[int]=None) -> None
    _scl: Any
    _sda: Any
    def try_lock(self) -> bool
    def unlock(self) -> None
    def __enter__(self) -> '_BitBangIO'
    def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]) -> None
  • Raises (implementation must reproduce these exact messages):
    • Bus timed out.
  • Behavior: Software-based implementation of the I2C protocol over GPIO pins.

adafruit_bitbangio.SPI

  • Import Path: from adafruit_bitbangio import SPI
  • Required Test Import Paths:
    • adafruit_bitbangio.SPI
  • Exact Test Import Statements:
    • import adafruit_bitbangio
  • Kind: class
  • Signature:
class SPI(_BitBangIO):
    def __init__(self, clock: Pin, MOSI: Optional[Pin]=None, MISO: Optional[Pin]=None) -> None
    def deinit(self) -> None
    def configure(self, *, baudrate: int=100000, polarity: Literal[0, 1]=0, phase: Literal[0, 1]=0, bits: int=8) -> None
    def write(self, buffer: ReadableBuffer, start: int=0, end: Optional[int]=None) -> None
    def readinto(self, buffer: WriteableBuffer, start: int=0, end: Optional[int]=None, write_value: int=0) -> None
    def write_readinto(self, buffer_out: ReadableBuffer, buffer_in: WriteableBuffer, *, out_start: int=0, out_end: Optional[int]=None, in_start: int=0, in_end: Optional[int]=None) -> None
    @property
    def frequency(self) -> int
    _polarity: Any
    _phase: Any
    def try_lock(self) -> bool
    def unlock(self) -> None
    def __enter__(self) -> '_BitBangIO'
    def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType]) -> None
  • Raises (implementation must reproduce these exact messages):
    • Write attempted with no MOSI pin specified.
    • Read attempted with no MISO pin specified.
    • Buffer slices must be equal length
    • baudrate must be an integer
    • bits must be an integer
    • bits must be in the range of 1-8
    • polarity must be either 0 or 1
    • phase must be either 0 or 1
  • Behavior: Software-based implementation of the SPI protocol over GPIO pins.

adafruit_bitbangio

  • Import Path: adafruit_bitbangio
  • Required Test Import Paths:
    • adafruit_bitbangio
  • Exact Test Import Statements:
    • import adafruit_bitbangio
  • Kind: module
  • Behavior: Module required during hidden-test collection.

Detailed Implementation Nodes

Node: Bitbangio-compatible software I/O module

Functional constraints

Locking

  • One boolean lock per bus object, shared by I2C and SPI via the base class. try_lock() returns True once then False; unlock() on an unlocked bus raises ValueError; every transaction (and SPI.configure) raises RuntimeError when called unlocked.
  • with bus: runs deinit() on exit — pins are released; do not reuse the object afterwards. For reusable buses, lock/unlock manually.

I2C

  • Constructor leaves both lines as inputs (open-drain emulation: input = released high through pull-up, output-low = driven low) and does not lock. Defaults: frequency 400000, timeout 1 s.
  • 7-bit addressing; wire byte is address << 1 (write) or address << 1 | 1 (read); all bytes MSB-first.
  • Wait timing: each _wait computes end = monotonic() + (1/frequency)/2 from the moment that wait starts, so every I2C half period is a full window measured from its own start; waits are independent (not chained) and overhead between waits is not absorbed — the opposite of SPI's chained half-cycle model.
  • scan() needs the lock, probes 0x00–0x7F ascending, returns ACKing addresses (START + address + STOP per probe).
  • Any NACK (address or data) raises RuntimeError carrying the address as zero-padded two-digit uppercase hex (0x07) and leaves the frame without a STOP (SCL low, SDA released); the next START sequence re-releases SCL and recovers.
  • writeto streams buffer[start:end]; an empty slice still sends START + address + STOP.
  • readfrom_into reads end - start bytes and stores at buffer[i + start] (offset honored); final byte NAKed; zero-length read still addresses the device.
  • writeto_then_readfrom writes without STOP, then repeated-START read via readfrom_into, then STOP; write-phase NACK raises before any read byte.
  • SCL release waits up to timeout for clock stretching, then raises the bus-timed-out RuntimeError.

SPI

  • Constructor self-locks briefly, applies configure() defaults (baudrate 100000, polarity 0, phase 0, bits 8), parks SCLK at the idle level, then unlocks — ready to use after try_lock().
  • configure() requires the lock and validates in fixed order: baudrate int → bits int → bits 1–8 → polarity {0,1} → phase {0,1}, each failure raising ValueError (reachable only while locked, since validation sits inside the lock-checked branch); bools pass (bool subclasses int). It recomputes the half period and re-parks the clock. frequency returns the configured baudrate, not the achieved rate.
  • Phase 0: write at idle level, sample on idle→active. Phase 1: write at active level, sample on active→idle. All four modes valid.
  • bits counts down from the MSB: with bits < 8 low bits are dropped on write and preserved on read.
  • write(buffer, start, end): start/end are positional-or-keyword; empty slice = no clock edges but the trailing settle wait still elapses one half period; no error.
  • readinto: consumes len(buffer[start:end]) bytes but stores at buffer[0] upward — the start offset does not shift placement (contrast with I2C readfrom_into); bits merge with |= / &= ~mask so bits < 8 keeps prior low bits; MOSI optional (clocks out write_value); MISO required.
  • write_readinto precheck order before the lock check: MOSI presence → MISO presence (each RuntimeError) → equal slice lengths (RuntimeError) → lock; both slices empty = no clock edges but the trailing settle wait still elapses one half period; placement honors in_start/out_start; the out-slice length drives the byte count.
  • Timing: chained half-period busy waits on time.monotonic, each measured from the end of the previous one; write, readinto, and write_readinto each end with one unconditional trailing half-period settle wait after the final active→idle transition, which fires even for empty slices — a valid call occupies 2 * bits * bytes + 1 half periods, and a zero-length transfer still consumes one half period of elapsed time.

Usage example

import board
import adafruit_bitbangio as bitbangio

i2c = bitbangio.I2C(board.SCL, board.SDA, frequency=100000)
while not i2c.try_lock():
    pass
try:
    print('devices:', [hex(a) for a in i2c.scan()])
    i2c.writeto(0x3C, bytes([0x00, 0xAF]))
    rx = bytearray(2)
    i2c.writeto_then_readfrom(0x3C, bytes([0x00]), rx)
finally:
    i2c.unlock()
i2c.deinit()