Adafruit CircuitPython API Reference — Adafruit CircuitPython 1 documentation (original) (raw)
CircuitPython
circuitpython.org | Get CircuitPython |Documentation | Contributing |Branding | Differences from Micropython |Project Structure
CircuitPython is a beginner friendly, open source version of Python for tiny, inexpensive computers called microcontrollers. Microcontrollers are the brains of many electronics including a wide variety of development boards used to build hobby projects and prototypes. CircuitPython in electronics is one of the best ways to learn to code because it connects code to reality. Simply install CircuitPython on a supported USB board usually via drag and drop and then edit a code.py
file on the CIRCUITPY drive. The code will automatically reload. No software installs are needed besides a text editor (we recommend Mu for beginners.)
Starting with CircuitPython 7.0.0, some boards may only be connectable over Bluetooth Low Energy (BLE). Those boards provide serial and file access over BLE instead of USB using open protocols. (Some boards may use both USB and BLE.) BLE access can be done from a variety of apps includingcode.circuitpython.org.
CircuitPython features unified Python core APIs and a growing list of 300+ device libraries and drivers that work with it. These libraries also work on single board computers with regular Python via the Adafruit Blinka Library.
CircuitPython is based on MicroPython. Seebelow for differences. Most, but not all, CircuitPython development is sponsored by Adafruit and is available on their educational development boards. Please support both MicroPython and Adafruit.
Get CircuitPython
Official binaries for all supported boards are available throughcircuitpython.org/downloads. The site includes stable, unstable and continuous builds. Full release notes are available throughGitHub releases as well.
Documentation
Guides and videos are available through the Adafruit Learning System under the CircuitPython category. An API reference is also available on Read the Docs. A collection of awesome resources can be found at Awesome CircuitPython.
Specifically useful documentation when starting out:
Contributing
SeeCONTRIBUTING.mdfor full guidelines but please be aware that by contributing to this project you are agreeing to the Code of Conduct. Contributors who follow the Code of Conductare welcome to submit pull requests and they will be promptly reviewed by project admins. Please join theDiscord too.
Branding
While we are happy to see CircuitPython forked and modified, we’d appreciate it if forked releases not use the name “CircuitPython” or the Blinka logo. “CircuitPython” means something special to us and those who learn about it. As a result, we’d like to make sure products referring to it meet a common set of requirements.
If you’d like to use the term “CircuitPython” and Blinka for your product here is what we ask:
- Your product is supported by the primary“adafruit/circuitpython” repo. This way we can update any custom code as we update the CircuitPython internals.
- Your product is listed on circuitpython.org (sourcehere). This is to ensure that a user of your product can always download the latest version of CircuitPython from the standard place.
- Your product supports at least one standard “Workflow” for serial and file access:
- With a user accessible USB plug which appears as a CIRCUITPY drive when plugged in.
- With file and serial access over Bluetooth Low Energy using the BLE Workflow.
- With file access over WiFi using the WiFi Workflow with serial access over USB and/or WebSocket.
- Boards that do not support the USB Workflow should be clearly marked.
If you choose not to meet these requirements, then we ask you call your version of CircuitPython something else (for example, SuperDuperPython) and not use the Blinka logo. You can say it is “CircuitPython-compatible” if most CircuitPython drivers will work with it.
Differences from MicroPython
CircuitPython:
- Supports native USB on most boards and BLE otherwise, allowing file editing without special tools.
- Floats (aka decimals) are enabled for all builds.
- Error messages are translated into 10+ languages.
- Concurrency within Python is not well supported. Interrupts and threading are disabled. async/await keywords are available on some boards for cooperative multitasking. Some concurrency is achieved with native modules for tasks that require it such as audio file playback.
Behavior
- The order that files are run and the state that is shared between them. CircuitPython’s goal is to clarify the role of each file and make each file independent from each other.
boot.py
runs only once on start up before workflows are initialized. This lays the ground work for configuring USB at startup rather than it being fixed. Since serial is not available, output is written toboot_out.txt
.code.py
(ormain.py
) is run after every reload until it finishes or is interrupted. After it is done running, the vm and hardware is reinitialized. This means you cannot read state fromcode.py
in the REPL anymore, as the REPL is a fresh vm. CircuitPython’s goal for this change includes reducing confusion about pins and memory being used.- After the main code is finished the REPL can be entered by pressing any key. - If the file
repl.py
exists, it is executed before the REPL Prompt is shown - In safe mode this functionality is disabled, to ensure the REPL Prompt can always be reached - Autoreload state will be maintained across reload.
- Adds a safe mode that does not run user code after a hard crash or brown out. This makes it possible to fix code that causes nasty crashes by making it available through mass storage after the crash. A reset (the button) is needed after it’s fixed to get back into normal mode.
- A 1 second delay is added to the boot process during which time the status LED will flash, and resetting the device or pressing the boot button will force the device into safe mode. This delay can be removed by a compile time option (
CIRCUITPY_SKIP_SAFE_MODE_WAIT
). - Safe mode may be handled programmatically by providing a
safemode.py
.safemode.py
is run if the board has reset due to entering safe mode, unless the safe mode initiated by the user by pressing button(s). USB is not available so nothing can be printed.safemode.py
can determine why the safe mode occurred usingsupervisor.runtime.safe_mode_reason
, and take appropriate action. For instance, if a hard crash occurred,safemode.py
may do amicrocontroller.reset()
to automatically restart despite the crash. If the battery is low, but is being charged,safemode.py
may put the board in deep sleep for a while. Or it may simply reset, and havecode.py
check the voltage and do the sleep. - RGB status LED indicating CircuitPython state. - One green flash - code completed without error. - Two red flashes - code ended due to an exception. - Three yellow flashes - safe mode. May be due to CircuitPython internal error.
- Re-runs
code.py
or other main file after file system writes by a workflow. (Disable withsupervisor.disable_autoreload()
) - Autoreload is disabled while the REPL is active.
code.py
may also be namedcode.txt
,main.py
, ormain.txt
.boot.py
may also be namedboot.txt
.safemode.py
may also be namedsafemode.txt
.
API
- Unified hardware APIs. Documented onReadTheDocs.
- API docs are Python stubs within the C files in
shared-bindings
. - No
machine
API.
Modules
- No module aliasing. (
uos
andutime
are not available asos
andtime
respectively.) Insteados
,time
, andrandom
are CPython compatible. - New
storage
module which manages file system mounts. (Functionality fromuos
in MicroPython.) - Modules with a CPython counterpart, such as
time
,os
andrandom
, are strictsubsetsof their CPython version. Therefore, code from CircuitPython is runnable on CPython but not necessarily the reverse. - tick count is available astime.monotonic()
Project Structure
Here is an overview of the top-level source code directories.
Core
The core code ofMicroPython is shared amongst ports including CircuitPython:
docs
High level user documentation in Sphinx reStructuredText format.drivers
External device drivers written in Python.examples
A few example Python scripts.extmod
Shared C code used in multiple ports’ modules.lib
Shared core C code including externally developed libraries such as FATFS.logo
The CircuitPython logo.mpy-cross
A cross compiler that converts Python files to byte code prior to being run in MicroPython. Useful for reducing library size.py
Core Python implementation, including compiler, runtime, and core library.shared-bindings
Shared definition of Python modules, their docs and backing C APIs. Ports must implement the C API to support the corresponding module.shared-module
Shared implementation of Python modules that may be based oncommon-hal
.tests
Test framework and test scripts.tools
Various tools, including the pyboard.py module.
Ports
Ports include the code unique to a microcontroller line.
The following ports are available: atmel-samd
, cxd56
, espressif
, litex
, mimxrt10xx
, nordic
, raspberrypi
, renode
, silabs
(efr32
), stm
, unix
.
However, not all ports are fully functional. Some have limited functionality and known serious bugs. For details, refer to the Port status section in the latest release notes.
Boards
- Each
port
has aboards
directory containing boards which belong to a specific microcontroller line. - A list of native modules supported by a particular board can be foundhere.
Full Table of Contents
API and Usage
- Core Modules
- Modules
* _bleio – Bluetooth Low Energy (BLE) communication
* _eve – Low-level BridgeTek EVE bindings
* _pew – LED matrix driver
* _pixelmap – A fast pixel mapping library
* _stage – C-level helpers for animation of sprites on a stage
* adafruit_bus_device – Hardware accelerated external bus access
* adafruit_pixelbuf – A fast RGB(W) pixel buffer library for like NeoPixel and DotStar
* aesio – AES encryption routines
* alarm – Alarms and sleep
* analogbufio – Analog Buffered IO Hardware Support
* analogio – Analog hardware support
* atexit – Atexit Module
* audiobusio – Support for audio input and output over digital buses
* audiocore – Support for audio samples
* audiodelays – Support for audio delay effects
* audiofilters – Support for audio filter effects
* audiofreeverb – Support for audio freeverb effect
* audioio – Support for audio output
* audiomixer – Support for audio mixing
* audiomp3 – Support for MP3-compressed audio files
* audiopwmio – Audio output via digital PWM
* aurora_epaper – A framebuffer for Pervasive Displays Aurora E-paper displays.
* bitbangio – Digital protocols implemented by the CPU
* bitmapfilter – Convolve an image with a kernel
* bitmaptools – Collection of bitmap manipulation tools
* bitops – Routines for low-level manipulation of binary data
* board – Board specific pin names
* busdisplay
* busio – Hardware accelerated external bus access
* camera – Support for camera input
* canio – CAN bus access
* codeop – Utilities to compile possibly incomplete Python source code.
* countio – Support for edge counting
* cyw43 – A class that represents a GPIO pin attached to the wifi chip.
* digitalio – Basic digital pin support
* displayio – High level, display object compositing system
* dotclockframebuffer – Native helpers for driving parallel displays
* dualbank – Dualbank Module
* epaperdisplay
* espcamera – Wrapper for the espcamera library
* espidf – Return the total size of the ESP-IDF, which includes the CircuitPython heap.
* espnow – ESP-NOW Module
* espulp – ESP Ultra Low Power Processor Module
* floppyio – Read flux transition information into the buffer.
* fontio – Core font related data structures
* fourwire – Connects to a BusDisplay over a four wire bus
* framebufferio – Native framebuffer display driving
* frequencyio – Support for frequency based protocols
* getpass – Getpass Module
* gifio – Access GIF-format images
* gnss – Global Navigation Satellite System
* hashlib – Hashing related functions
* i2cdisplaybus – Communicates to a display IC over I2C
* i2ctarget – Two wire serial protocol target
* imagecapture – Support for “Parallel capture” interfaces
* ipaddress
* is31fl3741 – Creates an in-memory framebuffer for a IS31FL3741 device.
* jpegio – Support for JPEG image decoding
* keypad – Support for scanning keys and key matrices
* keypad_demux – Support for scanning key matrices that use a demultiplexer
* locale – Locale support module
* lvfontio – Core font related data structures for LVGL
* math – mathematical functions
* max3421e – Provide USB host via a connected MAX3421E chip.
* mdns – Multicast Domain Name Service
* memorymap – Raw memory map access
* memorymonitor – Memory monitoring helpers
* microcontroller – Pin references and cpu functionality
* msgpack – Pack object in msgpack format
* neopixel_write – Low-level neopixel implementation
* nvm – Non-volatile memory
* onewireio – Low-level bit primitives for Maxim (formerly Dallas Semi) one-wire protocol.
* os – functions that an OS normally provides
* paralleldisplaybus – Native helpers for driving parallel displays
* picodvi – Low-level routines for interacting with PicoDVI Output
* ps2io – Support for PS/2 protocol
* pulseio – Support for individual pulse based protocols
* pwmio – Support for PWM based protocols
* qrio – Low-level QR code decoding
* rainbowio
* random – pseudo-random numbers and choices
* rclcpy – Robot Operating System (ROS2) connectivity through micro-ROS
* rgbmatrix – Low-level routines for bitbanged LED matrices
* rotaryio – Support for reading rotation sensors
* rp2pio – Hardware interface to RP2 series’ programmable IO (PIO) peripheral.
* rtc – Real Time Clock
* samd – SAMD implementation settings
* sdcardio – Interface to an SD card via the SPI bus
* sdioio – Interface to an SD card via the SDIO bus
* sharpdisplay – Support for Sharp Memory Display framebuffers
* socketpool
* spitarget – Serial Peripheral Interface protocol target
* ssl
* storage – Storage management
* struct – Manipulation of c-style data
* supervisor – Supervisor settings
* synthio – Support for multi-channel audio synthesis
* terminalio – Displays text in a TileGrid
* tilepalettemapper – Remaps color indices from the source bitmap to alternate indices on a per-tile basis. This allows for altering coloring of tiles based on their tilegrid location. It also allows for using a limited color bitmap with a wider array of colors.
* time – time and timing related functions
* touchio – Touch related IO
* traceback – Traceback Module
* uheap – Heap size analysis
* ulab – Manipulate numeric data similar to numpy
* usb – PyUSB-compatible USB host API
* usb_cdc – USB CDC Serial streams
* usb_hid – USB Human Interface Device
* usb_host – USB Host
* usb_midi – MIDI over USB
* usb_video – Allows streaming bitmaps to a host computer via USB
* ustack – Stack information and analysis
* vectorio – Lightweight 2D shapes for displays
* videocore – Low-level routines for interacting with the Broadcom VideoCore GPU
* warnings – Warn about potential code issues.
* watchdog – Watchdog Timer
* wifi
* zephyr_serial – Zephyr UART driver for fixed busses.
* zlib – zlib decompression functionality
* help() – Built-in method to provide helpful information
- Modules
- Standard Libraries
- Python standard libraries
* builtins – builtin functions and exceptions
* heapq – heap queue algorithm
* array – arrays of numeric data
* binascii – binary/ASCII conversions
* collections – collection and container types
* errno – system error codes
* gc – control the garbage collector
* io – input/output streams
* json – JSON encoding and decoding
* platform – access to underlying platform’s identifying data
* re – simple regular expressions
* sys – system specific functions
* select – wait for events on a set of streams - Omitted string functions
- CircuitPython/MicroPython-specific libraries
* micropython – access and control MicroPython internals
- Python standard libraries
- Supported Ports
- Analog Devices “MAX32” MCUs
* Structure of this port
* Building for MAX32 devices
* Flashing the board
* Using the REPL
* Editing code.py - SAMD21 and SAMD51
* Building
* Debugging
* Port Specific modules - Broadcom
- CXD56 (Spresense)
* Prerequisites
* Build instructions
* USB connection
* Flash the bootloader
* Flash the circuitpython image
* Accessing the board - Espressif
* Support Status:
* How this port is organized:
* Connecting to the ESP32
* Connecting to the ESP32-C3
* Connecting to the ESP32-S2
* Connecting to the ESP32-S3
* Building and flashing
* Debugging - LiteX (FPGA)
* Installation - NXP i.MX RT10xx Series
- Nordic Semiconductor nRF52 Series
* Flash
* Segger Targets
* DFU Targets - RP2040
* Building
* Port Specific modules - Renode
* Running
* Other stuff - Silicon Labs EFR32
* How this port is organized
* Prerequisites
* Supported boards
* Build instructions
* Flashing CircuitPython
* Running CircuitPython - ST Microelectronics STM32
* How this port is organized:
* Build instructions
* USB connection
* Flash the bootloader
* Flashing the circuitpython image with DFU-Util
* Accessing the board - MicroPython Unix port
* Building - Zephyr
* Getting Started
* Testing other boards
- Analog Devices “MAX32” MCUs
- Troubleshooting
- Adafruit CircuitPython Libraries
- CircuitPython Library Bundles
- Workflows
- Environment Variables