├── .gitignore ├── LICENSE ├── README.md ├── docs ├── Makefile ├── README.md ├── conf.py ├── cyberbrick_core │ ├── general.rst │ ├── img │ │ └── Controller_core.png │ ├── lib │ │ ├── BuzzerController.rst │ │ ├── LEDController.rst │ │ ├── MotorController.rst │ │ ├── ServosController.rst │ │ ├── index.rst │ │ └── rc_module.rst │ ├── quickref.rst │ ├── start │ │ └── index.rst │ └── tutorial │ │ ├── img │ │ └── mem32_gpio_output.jpg │ │ ├── index.rst │ │ ├── peripheral_access.rst │ │ └── pwm.rst ├── index.rst ├── library │ ├── _thread.rst │ ├── array.rst │ ├── asyncio.rst │ ├── binascii.rst │ ├── btree.rst │ ├── builtins.rst │ ├── cmath.rst │ ├── collections.rst │ ├── cryptolib.rst │ ├── deflate.rst │ ├── errno.rst │ ├── esp.rst │ ├── esp32.rst │ ├── espnow.rst │ ├── framebuf.rst │ ├── gc.rst │ ├── gzip.rst │ ├── hashlib.rst │ ├── heapq.rst │ ├── index.rst │ ├── io.rst │ ├── json.rst │ ├── machine.ADC.rst │ ├── machine.ADCBlock.rst │ ├── machine.I2C.rst │ ├── machine.PWM.rst │ ├── machine.Pin.rst │ ├── machine.RTC.rst │ ├── machine.SPI.rst │ ├── machine.Signal.rst │ ├── machine.Timer.rst │ ├── machine.UART.rst │ ├── machine.WDT.rst │ ├── machine.rst │ ├── math.rst │ ├── micropython.rst │ ├── neopixel.rst │ ├── network.WLAN.rst │ ├── network.rst │ ├── os.rst │ ├── platform.rst │ ├── random.rst │ ├── re.rst │ ├── select.rst │ ├── socket.rst │ ├── ssl.rst │ ├── struct.rst │ ├── sys.rst │ ├── time.rst │ ├── uctypes.rst │ ├── vfs.rst │ └── zlib.rst ├── license.rst ├── make.bat ├── readthedocs │ └── settings │ │ └── local_settings.py ├── reference │ ├── constrained.rst │ ├── glossary.rst │ ├── index.rst │ ├── isr_rules.rst │ ├── mpremote.rst │ ├── mpyfiles.rst │ ├── packages.rst │ ├── pyboard.py.rst │ ├── repl.rst │ └── speed_python.rst ├── requirements.txt ├── static │ ├── custom.css │ ├── customstyle.css │ └── favicon.ico └── templates │ ├── layout.html │ ├── replace.inc │ ├── topindex.html │ └── versions.html ├── src ├── app_rc │ ├── app │ │ ├── control.py │ │ ├── devices.py │ │ ├── parser.py │ │ └── rc_main.py │ ├── bbl │ │ ├── __init__.py │ │ ├── buzzer.py │ │ ├── executor.py │ │ ├── leds.py │ │ ├── motors.py │ │ └── servos.py │ └── boot.py └── app_timelapse │ └── boot.py └── tools ├── HapticOpti_speed_curve.py ├── HapticOpti_time2speed_curve.py ├── README.md └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | **/__pycache__/ 3 | */build/ 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | CyberBrick Codebase License: 2 | 3 | Copyright (C) 2025 MakerWorld 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to use, copy, modify, reproduce and distribute (the "Use") the Software, subject to the following conditions: 6 | 1. Only Use in MakerWorld 7 | The Software may only be used through services, programs, or products provided by MakerWorld, or those expressly authorized by a written license from MakerWorld. When using the Software, strict compliance with MakerWorld's Terms of Use and Community Guidelines is mandatory. 8 | 2. Derivative Works 9 | You may reproduce and distribute copies of your derivative works based on the Software (the "Derivative Works") under the license of Article 1. 10 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions of Your modifications, or for any such Derivative Works as a whole. 11 | 3. License Notice 12 | This License including but not limited to the copyright of MakerWorld shall be included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CyberBrick Controller Core 2 | ---------------------------- 3 | 4 | This is a project repository for RC controller applications and Timelapse controllers based on the [MicroPython](https://github.com/micropython/micropython) project, which works well on CyberBrick Controller Core with Receiver/Transmitter Shield or Timelapse Kit. 5 | 6 | This is fun, enjoy it! 7 | 8 | ## About this repositoty 9 | ------------------------ 10 | 11 | This repository contains the following content: 12 | - [docs/](docs/) -- user documentation in Sphinx reStructuredText format. This is used to generate the online documentation. 13 | - [src/](src/) -- project engineering code, including application code projects for RC and Timelapse. 14 | - [tools/](tools/) -- various tools, currently including visualization tools for advanced control of throttle speed curves in RC applications. 15 | 16 | 17 | ## How to use 18 | ------------- 19 | 20 | ### RC controller application 21 | 22 | Installation environment dependency: 23 | 24 | $ pip install -r requirements.txt 25 | 26 | Enter the RC code directory: 27 | 28 | $ cd src/app_rc/ 29 | 30 | In the app_rc folder, you can see the startup and control code used to implement RC applications. To achieve RC application functionality, you can upload the directory contents to the onboard file system directory of Controller Core. 31 | 32 | It is recommended to use the mpy_cross tool to convert [control.py](src/app_rc/app/control.py) and [parser.py](src/app_rc/app/parser.py) into bytecode in (.mpy) format, with the same name as the (.py) program. When encountering the problem of insufficient RAM space during program execution. 33 | 34 | $ mpy-cross .\app\control.py 35 | $ mpy-cross .\app\parse.py 36 | 37 | ### Timelapse Kit application 38 | 39 | $ cd src/app_timelapse/ 40 | 41 | Enter the timelapse code directory, upload the directory contents to the onboard file system directory of Controller Core. 42 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | MicroPython Documentation 2 | ========================= 3 | 4 | The MicroPython documentation can be found at: 5 | http://docs.micropython.org/en/latest/ 6 | 7 | The documentation you see there is generated from the files in the docs tree: 8 | https://github.com/micropython/micropython/tree/master/docs 9 | 10 | Building the documentation locally 11 | ---------------------------------- 12 | 13 | If you're making changes to the documentation, you may want to build the 14 | documentation locally so that you can preview your changes. 15 | 16 | Install Sphinx, and optionally (for the RTD-styling), sphinx_rtd_theme, 17 | preferably in a virtualenv: 18 | 19 | pip install sphinx 20 | pip install sphinx_rtd_theme 21 | 22 | In `micropython/docs`, build the docs: 23 | 24 | make html 25 | 26 | You'll find the index page at `micropython/docs/build/html/index.html`. 27 | 28 | Having readthedocs.org build the documentation 29 | ---------------------------------------------- 30 | 31 | If you would like to have docs for forks/branches hosted on GitHub, GitLab or 32 | BitBucket an alternative to building the docs locally is to sign up for a free 33 | https://readthedocs.org account. The rough steps to follow are: 34 | 1. sign-up for an account, unless you already have one 35 | 2. in your account settings: add GitHub as a connected service (assuming 36 | you have forked this repo on github) 37 | 3. in your account projects: import your forked/cloned micropython repository 38 | into readthedocs 39 | 4. in the project's versions: add the branches you are developing on or 40 | for which you'd like readthedocs to auto-generate docs whenever you 41 | push a change 42 | 43 | PDF manual generation 44 | --------------------- 45 | 46 | This can be achieved with: 47 | 48 | make latexpdf 49 | 50 | but requires a rather complete install of LaTeX with various extensions. On 51 | Debian/Ubuntu, try (1GB+ download): 52 | 53 | apt install texlive-latex-recommended texlive-latex-extra texlive-xetex texlive-fonts-extra cm-super xindy 54 | -------------------------------------------------------------------------------- /docs/cyberbrick_core/general.rst: -------------------------------------------------------------------------------- 1 | .. _esp32_general: 2 | 3 | General information about the ESP32 port 4 | ======================================== 5 | 6 | The ESP32-C3 is a popular WiFi and Bluetooth enabled System-on-Chip (SoC) by 7 | Espressif Systems. 8 | 9 | Multitude of boards 10 | ------------------- 11 | 12 | There is a multitude of modules and boards from different sources which carry 13 | the ESP32-C3 chip. MicroPython tries to provide a generic port which would run on 14 | as many boards/modules as possible, but there may be limitations. Espressif 15 | development boards are taken as reference for the port (for example, testing is 16 | performed on them). For any board you are using please make sure you have a 17 | datasheet, schematics and other reference materials so you can look up any 18 | board-specific functions. 19 | 20 | To make a generic ESP32-C3 port and support as many boards as possible the 21 | following design and implementation decision were made: 22 | 23 | * GPIO pin numbering is based on ESP32-C3 chip numbering. Please have the manual/pin 24 | diagram of your board at hand to find correspondence between your board pins and 25 | actual ESP32-C3 pins. 26 | * All pins are supported by MicroPython but not all are usable on any given board. 27 | For example pins that are connected to external SPI flash should not be used, 28 | and a board may only expose a certain selection of pins. 29 | 30 | 31 | Technical specifications and SoC datasheets 32 | ------------------------------------------- 33 | 34 | The datasheets and other reference material for ESP32 chip are available 35 | from the vendor site: https://www.espressif.com/en/support/download/documents?keys=esp32-c3 . 36 | They are the primary reference for the chip technical specifications, capabilities, 37 | operating modes, internal functioning, etc. 38 | 39 | For your convenience, some of technical specifications are provided below: 40 | 41 | * Architecture: RISC-V 32-bit 42 | * CPU frequency: up to 160MHz 43 | * Total RAM available: 400KB (part of it reserved for system) 44 | * BootROM: 384KB 45 | * Internal FlashROM: none 46 | * External FlashROM: code and data, via SPI Flash; usual size 4MB 47 | * GPIO: 22 (GPIOs are multiplexed with other functions, including 48 | external FlashROM, UART, etc.) 49 | * UART: 2 RX/TX UART 50 | * SPI: 3 SPI interfaces (one used for FlashROM) 51 | * I2C: 1 I2C (bitbang implementation available on any pins) 52 | * ADC: 12-bit SAR ADC up to 6 channels 53 | * RMT: 6 channels allowing accurate pulse transmit/receive 54 | 55 | For more information see the ESP32 datasheet: https://www.espressif.com/sites/default/files/documentation/esp32-c3_datasheet_en.pdf 56 | 57 | MicroPython is implemented on top of the ESP-IDF, Espressif's development 58 | framework for the ESP32. This is a FreeRTOS based system. See the 59 | `ESP-IDF Programming Guide `_ 60 | for details. 61 | -------------------------------------------------------------------------------- /docs/cyberbrick_core/img/Controller_core.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CyberBrick-Official/CyberBrick_Controller_Core/b5fc07d44d65143cfef1164ae6234099fcb11d62/docs/cyberbrick_core/img/Controller_core.png -------------------------------------------------------------------------------- /docs/cyberbrick_core/lib/BuzzerController.rst: -------------------------------------------------------------------------------- 1 | BuzzerController 2 | ================ 3 | 4 | .. automodule:: bbl.buzzer 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | :special-members: __init__ -------------------------------------------------------------------------------- /docs/cyberbrick_core/lib/LEDController.rst: -------------------------------------------------------------------------------- 1 | LEDController 2 | ============= 3 | 4 | .. automodule:: bbl.leds 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | :special-members: __init__ -------------------------------------------------------------------------------- /docs/cyberbrick_core/lib/MotorController.rst: -------------------------------------------------------------------------------- 1 | MotorsController 2 | ================ 3 | 4 | .. automodule:: bbl.motors 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | :special-members: __init__ -------------------------------------------------------------------------------- /docs/cyberbrick_core/lib/ServosController.rst: -------------------------------------------------------------------------------- 1 | ServosController 2 | ================ 3 | 4 | .. automodule:: bbl.servos 5 | :members: 6 | :undoc-members: 7 | :show-inheritance: 8 | :special-members: __init__ -------------------------------------------------------------------------------- /docs/cyberbrick_core/lib/index.rst: -------------------------------------------------------------------------------- 1 | CyberBrick Custom Libraries 2 | =========================== 3 | 4 | These are some driver libraries provided to CyberBrick Controller Core, 5 | which are paired with Transmitter Shield and Receiver Shield to 6 | achieve functionality for supported devices. You can use it to easily and quickly implement control functions. 7 | 8 | At present, this includes LEDs, motors, servos, and so on. 9 | We will continue to expand the components. 10 | 11 | .. toctree:: 12 | :maxdepth: 1 13 | 14 | rc_module 15 | LEDController 16 | ServosController 17 | MotorController 18 | BuzzerController 19 | -------------------------------------------------------------------------------- /docs/cyberbrick_core/lib/rc_module.rst: -------------------------------------------------------------------------------- 1 | rc_module 2 | ========= 3 | 4 | This module provides functionality for radio control (RC) slave operations. 5 | 6 | .. function:: rc_master_init() 7 | 8 | Initializes the RC master module. 9 | 10 | **Description** 11 | 12 | This function sets up the necessary configurations and resources for the RC master to operate. It is essential to call this function before starting any RC tasks. 13 | 14 | **Example** 15 | 16 | .. code-block:: python 17 | 18 | import rc_module 19 | 20 | rc_module.rc_master_init() 21 | 22 | .. function:: rc_slave_init() 23 | 24 | Initializes the RC slave module. 25 | 26 | **Description** 27 | 28 | The bbl_rc_slave module is part of the RC car suite, serving as the receiver component. 29 | It provides functionalities to manage and operate the RC receiver, enabling communication with the RC transmitter. 30 | This module is essential for loading and configuring the resources necessary for the receiver's operation, 31 | ensuring effective control over the RC car's movements and actions. 32 | 33 | **Example** 34 | 35 | .. code-block:: python 36 | 37 | import rc_module 38 | 39 | rc_module.rc_slave_init() 40 | 41 | .. function:: rc_slave_data() 42 | 43 | Retrieves the current RC data. 44 | 45 | **Description** 46 | 47 | This function returns the current RC data from the RC suite's remote control transmitter. 48 | When the transmitter and receiver are paired and the transmitter is operational, `rc_slave_data()` 49 | returns a tuple corresponding to the transmitter's interface numbers: [L1, L2, L3, R1, R2, R3, K1, K2, K3, K4]. 50 | The first six elements are ADC values [0, 4095] from the transmitter's six joystick channels, 51 | and the last four elements are high/low states [0, 1] from the transmitter's four button IOs. 52 | For example, [1885, 1960, 1992, 2106, 1945, 2009, 1, 1, 1, 1]. If the transmitter is not paired or operational, 53 | `rc_slave_data()` returns None. 54 | 55 | **Parameters** 56 | 57 | None 58 | 59 | **Returns** 60 | 61 | A tuple containing the current RC data, or None if no data is available. 62 | 63 | **Example** 64 | 65 | .. code-block:: python 66 | 67 | import rc_module 68 | 69 | rc_module.init() 70 | rc_data = rc_module.rc_data() 71 | if rc_data: 72 | print("Joystick ADC values:", rc_data[:6]) 73 | print("Button states:", rc_data[6:]) 74 | else: 75 | print("No data received. Please check if the transmitter is paired and operational.") 76 | 77 | .. function:: rc_index() 78 | 79 | Retrieves the current RC index. 80 | 81 | **Description** 82 | 83 | This function returns the current index of the receiver board, 84 | which is determined during pairing with the transmitter. 85 | The return values may be 0, 1, 2, where 0 represents unpaired, 86 | 1 represents configured to receive as slave 1, and 2 represents slave 2 87 | 88 | **Parameters** 89 | 90 | None 91 | 92 | **Returns** 93 | 94 | The current RC index. 95 | 96 | **Example** 97 | 98 | .. code-block:: python 99 | 100 | import rc_module 101 | 102 | rc_index = rc_module.rc_index() 103 | print("RC Index:", rc_index) 104 | 105 | .. function:: rc_simulation() 106 | 107 | Retrieves the current RC testing and control instructions. 108 | 109 | **Description** 110 | 111 | This function will receive RC related testing and control instructions, which are usually from PC or APP. 112 | 113 | **Parameters** 114 | 115 | None 116 | 117 | **Returns** 118 | 119 | Instruction of string type. 120 | 121 | **Example** 122 | 123 | .. code-block:: python 124 | 125 | import time 126 | import rc_module 127 | 128 | while True: 129 | simulation = rc_module.rc_simulation() 130 | if simulation: 131 | print("RC simulation:", simulation) 132 | time.sleep(0.1) 133 | -------------------------------------------------------------------------------- /docs/cyberbrick_core/start/index.rst: -------------------------------------------------------------------------------- 1 | Getting Started with CyberBrick Core 2 | ==================================== 3 | 4 | Welcome to the MicroPython beginner's tutorial for the Controller Core. This guide will walk you through setting up the development environment, basic programming, and common applications. 5 | 6 | This tutorial is intended to get you started using MicroPython on the ESP32-C3 7 | system-on-a-chip. If it is your first time it is recommended to follow the 8 | tutorial through in the order below. Otherwise the sections are mostly self 9 | contained, so feel free to skip to those that interest you. 10 | 11 | The tutorial does not assume that you know Python, but it also does not attempt 12 | to explain any of the details of the Python language. Instead it provides you 13 | with commands that are ready to run, and hopes that you will gain a bit of 14 | Python knowledge along the way. To learn more about Python itself please refer 15 | to ``__. 16 | 17 | 1. Setting Up the Development Environment 18 | ----------------------------------------- 19 | 20 | The Controller Core supports MicroPython programming directly without needing to re-flash the firmware. To set up your development environment using Visual Studio Code (VSCode), follow the steps below:​ 21 | 22 | - A Controller Core 23 | - A USB-C cable 24 | - A computer (Windows, macOS, or Linux) 25 | - Visual Studio Code (https://code.visualstudio.com/) 26 | - Node.js (https://nodejs.org/) 27 | - Pymakr extension for VSCode (https://marketplace.visualstudio.com/items?itemName=pycom.Pymakr) 28 | 29 | 1. Install Visual Studio Code 30 | 2. Install Node.js Pymakr requires Node.js as a dependency. After installation, verify it by running the following command in your terminal or command prompt: node -v 31 | 3. Install the Pymakr Extension in VSCode. Open VSCode. Click on the Extensions icon in the Activity Bar on the side of the window. Find the Pymakr extension in the search results and click "Install". 32 | 33 | For more detailed instructions and troubleshooting, 34 | refer to the documentation on using VSCode for 35 | MicroPython programming: https://github.com/pycom/pymakr-vsc/blob/HEAD/GET_STARTED.md 36 | 37 | If you don't want to make such complex configurations, 38 | you can search for "Python IDE for beginners" in the browser 39 | to choose a more suitable development environment. 40 | 41 | 2. Connecting to REPL 42 | ---------------------- 43 | 44 | REPL (Read Evaluate Print Loop) is an interactive terminal for MicroPython, allowing you to quickly test code and run commands. 45 | 46 | You can refer to this website (https://docs.micropython.org/en/latest/zephyr/tutorial/repl.html) to connect to connect to the REPL of the Controller Core. 47 | 48 | Once connected to REPL, you can enter Python code and execute it immediately. 49 | 50 | Example: 51 | 52 | .. code-block:: python 53 | 54 | print("Hello, CyberBrick!") 55 | 56 | 3. Basic Usage 57 | -------------- 58 | 59 | On the Controller Core, you can use MicroPython to control peripherals such as GPIO, 60 | I2C, and PWM. For example, to light up the onboard RGB, 61 | to light up the onboard RGB, Make it light up the red light: 62 | 63 | .. code-block:: python 64 | 65 | import machine 66 | import neopixel 67 | import time 68 | 69 | pin = machine.Pin(8, machine.Pin.OUT) 70 | np = neopixel.NeoPixel(pin, 1) 71 | 72 | np[0] = (255, 0, 0) #(R, G, B) 73 | np.write() 74 | 75 | Additionally, you can control GPIO pins, such as setting IO2 to high: 76 | 77 | .. code-block:: python 78 | 79 | import machine 80 | 81 | io2 = machine.Pin(2, machine.Pin.OUT) 82 | io2.value(1) # Set IO2 to high 83 | 84 | 4. File System 85 | -------------- 86 | 87 | The Controller Core includes a file system formatted in FAT, stored in the flash memory behind the MicroPython firmware. 88 | 89 | You can use the `os` module to interact with the file system. For example, to list files: 90 | 91 | .. code-block:: python 92 | 93 | import os 94 | print(os.listdir()) 95 | -------------------------------------------------------------------------------- /docs/cyberbrick_core/tutorial/img/mem32_gpio_output.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CyberBrick-Official/CyberBrick_Controller_Core/b5fc07d44d65143cfef1164ae6234099fcb11d62/docs/cyberbrick_core/tutorial/img/mem32_gpio_output.jpg -------------------------------------------------------------------------------- /docs/cyberbrick_core/tutorial/index.rst: -------------------------------------------------------------------------------- 1 | .. _esp32_tutorial: 2 | 3 | MicroPython tutorial for ESP32 4 | ============================== 5 | 6 | This tutorial is intended to get you started using MicroPython on the ESP32 7 | system-on-a-chip. If it is your first time it is recommended to follow the 8 | tutorial through in the order below. Otherwise the sections are mostly self 9 | contained, so feel free to skip to those that interest you. 10 | 11 | The tutorial does not assume that you know Python, but it also does not attempt 12 | to explain any of the details of the Python language. Instead it provides you 13 | with commands that are ready to run, and hopes that you will gain a bit of 14 | Python knowledge along the way. To learn more about Python itself please refer 15 | to ``__. 16 | 17 | .. toctree:: 18 | :maxdepth: 1 19 | :numbered: 20 | 21 | pwm.rst 22 | peripheral_access.rst 23 | -------------------------------------------------------------------------------- /docs/cyberbrick_core/tutorial/peripheral_access.rst: -------------------------------------------------------------------------------- 1 | Accessing peripherals directly via registers 2 | ============================================ 3 | 4 | The ESP32's peripherals can be controlled via direct register reads and writes. 5 | This requires reading the datasheet to know what registers to use and what 6 | values to write to them. The following example shows how to turn on and change 7 | the prescaler of the MCPWM0 peripheral. 8 | 9 | .. code-block:: python3 10 | 11 | from micropython import const 12 | from machine import mem32 13 | 14 | # Define the register addresses that will be used. 15 | DR_REG_DPORT_BASE = const(0x3FF00000) 16 | DPORT_PERIP_CLK_EN_REG = const(DR_REG_DPORT_BASE + 0x0C0) 17 | DPORT_PERIP_RST_EN_REG = const(DR_REG_DPORT_BASE + 0x0C4) 18 | DPORT_PWM0_CLK_EN = const(1 << 17) 19 | MCPWM0 = const(0x3FF5E000) 20 | MCPWM1 = const(0x3FF6C000) 21 | 22 | # Enable CLK and disable RST. 23 | print(hex(mem32[DPORT_PERIP_CLK_EN_REG] & 0xffffffff)) 24 | print(hex(mem32[DPORT_PERIP_RST_EN_REG] & 0xffffffff)) 25 | mem32[DPORT_PERIP_CLK_EN_REG] |= DPORT_PWM0_CLK_EN 26 | mem32[DPORT_PERIP_RST_EN_REG] &= ~DPORT_PWM0_CLK_EN 27 | print(hex(mem32[DPORT_PERIP_CLK_EN_REG] & 0xffffffff)) 28 | print(hex(mem32[DPORT_PERIP_RST_EN_REG] & 0xffffffff)) 29 | 30 | # Change the MCPWM0 prescaler. 31 | print(hex(mem32[MCPWM0])) # read PWM_CLK_CFG_REG (reset value = 0) 32 | mem32[MCPWM0] = 0x55 # change PWM_CLK_PRESCALE 33 | print(hex(mem32[MCPWM0])) # read PWM_CLK_CFG_REG 34 | 35 | Note that before a peripheral can be used its clock must be enabled and it must 36 | be taken out of reset. In the above example the following registers are used 37 | for this: 38 | 39 | - ``DPORT_PERI_CLK_EN_REG``: used to enable a peripheral clock 40 | 41 | - ``DPORT_PERI_RST_EN_REG``: used to reset (or take out of reset) a peripheral 42 | 43 | The MCPWM0 peripheral is in bit position 17 of the above two registers, hence 44 | the value of ``DPORT_PWM0_CLK_EN``. 45 | 46 | Synchronous access to pins directly via registers 47 | ------------------------------------------------- 48 | 49 | The following code shows how to access pins directly via registers. It has been 50 | tested on a generic ESP32 board. It configures pins 16, 17, 32 and 33 in output 51 | mode via registers, and switches pin output values via registers. Pins 16 and 52 | 17 are switched simultaneously. 53 | 54 | .. code-block:: python3 55 | 56 | from micropython import const 57 | from machine import mem32, Pin 58 | 59 | GPIO_OUT_REG = const(0x3FF44004) # GPIO 0-31 output register 60 | GPIO_OUT1_REG = const(0x3FF44010) # GPIO 32-39 output register 61 | 62 | GPIO_ENABLE_REG = const(0x3FF44020) # GPIO 0-31 output enable register 63 | GPIO_ENABLE1_REG = const(0x3FF4402C) # GPIO 32-39 output enable register 64 | 65 | M16 = 1 << 16 # Pin(16) bit mask 66 | M17 = 1 << 17 # Pin(17) bit mask 67 | 68 | M32 = 1 << (32-32) # Pin(32) bit mask 69 | M33 = 1 << (33-32) # Pin(33) bit mask 70 | 71 | # Enable pin output mode like 72 | # p16 = Pin(16, mode=Pin.OUT) 73 | # p17 = Pin(17, mode=Pin.OUT) 74 | # p32 = Pin(32, mode=Pin.OUT) 75 | # p33 = Pin(33, mode=Pin.OUT) 76 | mem32[GPIO_ENABLE_REG] = mem32[GPIO_ENABLE_REG] | M16 | M17 77 | mem32[GPIO_ENABLE1_REG] = mem32[GPIO_ENABLE1_REG] | M32 | M33 78 | 79 | print(hex(mem32[GPIO_OUT_REG]), hex(mem32[GPIO_OUT1_REG])) 80 | 81 | # Set outputs to 1 like 82 | # p16(1) 83 | # p17(1) 84 | # p32(1) 85 | # p33(1) 86 | mem32[GPIO_OUT_REG] = mem32[GPIO_OUT_REG] | M16 | M17 87 | mem32[GPIO_OUT1_REG] = mem32[GPIO_OUT1_REG] | M32 | M33 88 | 89 | print(hex(mem32[GPIO_OUT_REG]), hex(mem32[GPIO_OUT1_REG])) 90 | 91 | # Set outputs to 0 like 92 | # p16(0) 93 | # p17(0) 94 | # p32(0) 95 | # p33(0) 96 | mem32[GPIO_OUT_REG] = mem32[GPIO_OUT_REG] & ~(M16 | M17) 97 | mem32[GPIO_OUT1_REG] = mem32[GPIO_OUT1_REG] & ~(M32 | M33) 98 | 99 | print(hex(mem32[GPIO_OUT_REG]), hex(mem32[GPIO_OUT1_REG])) 100 | 101 | while True: 102 | # Set outputs to 1 103 | mem32[GPIO_OUT_REG] = mem32[GPIO_OUT_REG] | M16 | M17 104 | mem32[GPIO_OUT1_REG] = mem32[GPIO_OUT1_REG] | M32 | M33 105 | 106 | # Set outputs to 0 107 | mem32[GPIO_OUT_REG] = mem32[GPIO_OUT_REG] & ~(M16 | M17) 108 | mem32[GPIO_OUT1_REG] = mem32[GPIO_OUT1_REG] & ~(M32 | M33) 109 | 110 | 111 | Output is:: 112 | 113 | 0x0 0x0 114 | 0x30000 0x3 115 | 0x0 0x0 116 | 117 | Pins 16 and 17 are switched synchronously: 118 | 119 | .. image:: img/mem32_gpio_output.jpg 120 | 121 | Same image on pins 32 and 33. 122 | 123 | Note that pins 34-36 and 39 are inputs only. Also pins 1 and 3 are Tx, Rx of the REPL UART, 124 | pins 6-11 are connected to the built-in SPI flash. 125 | -------------------------------------------------------------------------------- /docs/cyberbrick_core/tutorial/pwm.rst: -------------------------------------------------------------------------------- 1 | .. _esp32_pwm: 2 | 3 | Pulse Width Modulation 4 | ====================== 5 | 6 | Pulse width modulation (PWM) is a way to get an artificial analog output on a 7 | digital pin. It achieves this by rapidly toggling the pin from low to high. 8 | There are two parameters associated with this: the frequency of the toggling, 9 | and the duty cycle. The duty cycle is defined to be how long the pin is high 10 | compared with the length of a single period (low plus high time). Maximum 11 | duty cycle is when the pin is high all of the time, and minimum is when it is 12 | low all of the time. 13 | 14 | * More comprehensive example with all 16 PWM channels and 8 timers:: 15 | 16 | from machine import Pin, PWM 17 | try: 18 | f = 100 # Hz 19 | d = 1024 // 16 # 6.25% 20 | pins = (15, 2, 4, 16, 18, 19, 22, 23, 25, 26, 27, 14 , 12, 13, 32, 33) 21 | pwms = [] 22 | for i, pin in enumerate(pins): 23 | pwms.append(PWM(Pin(pin), freq=f * (i // 2 + 1), duty= 1023 if i==15 else d * (i + 1))) 24 | print(pwms[i]) 25 | finally: 26 | for pwm in pwms: 27 | try: 28 | pwm.deinit() 29 | except: 30 | pass 31 | 32 | Output is:: 33 | 34 | PWM(Pin(15), freq=100, duty=64, resolution=10, mode=0, channel=0, timer=0) 35 | PWM(Pin(2), freq=100, duty=128, resolution=10, mode=0, channel=1, timer=0) 36 | PWM(Pin(4), freq=200, duty=192, resolution=10, mode=0, channel=2, timer=1) 37 | PWM(Pin(16), freq=200, duty=256, resolution=10, mode=0, channel=3, timer=1) 38 | PWM(Pin(18), freq=300, duty=320, resolution=10, mode=0, channel=4, timer=2) 39 | PWM(Pin(19), freq=300, duty=384, resolution=10, mode=0, channel=5, timer=2) 40 | PWM(Pin(22), freq=400, duty=448, resolution=10, mode=0, channel=6, timer=3) 41 | PWM(Pin(23), freq=400, duty=512, resolution=10, mode=0, channel=7, timer=3) 42 | PWM(Pin(25), freq=500, duty=576, resolution=10, mode=1, channel=0, timer=0) 43 | PWM(Pin(26), freq=500, duty=640, resolution=10, mode=1, channel=1, timer=0) 44 | PWM(Pin(27), freq=600, duty=704, resolution=10, mode=1, channel=2, timer=1) 45 | PWM(Pin(14), freq=600, duty=768, resolution=10, mode=1, channel=3, timer=1) 46 | PWM(Pin(12), freq=700, duty=832, resolution=10, mode=1, channel=4, timer=2) 47 | PWM(Pin(13), freq=700, duty=896, resolution=10, mode=1, channel=5, timer=2) 48 | PWM(Pin(32), freq=800, duty=960, resolution=10, mode=1, channel=6, timer=3) 49 | PWM(Pin(33), freq=800, duty=1023, resolution=10, mode=1, channel=7, timer=3) 50 | 51 | * Example of a smooth frequency change:: 52 | 53 | from time import sleep 54 | from machine import Pin, PWM 55 | 56 | F_MIN = 500 57 | F_MAX = 1000 58 | 59 | f = F_MIN 60 | delta_f = 1 61 | 62 | p = PWM(Pin(5), f) 63 | print(p) 64 | 65 | while True: 66 | p.freq(f) 67 | 68 | sleep(10 / F_MIN) 69 | 70 | f += delta_f 71 | if f >= F_MAX or f <= F_MIN: 72 | delta_f = -delta_f 73 | 74 | See PWM wave at Pin(5) with an oscilloscope. 75 | 76 | * Example of a smooth duty change:: 77 | 78 | from time import sleep 79 | from machine import Pin, PWM 80 | 81 | DUTY_MAX = 2**16 - 1 82 | 83 | duty_u16 = 0 84 | delta_d = 16 85 | 86 | p = PWM(Pin(5), 1000, duty_u16=duty_u16) 87 | print(p) 88 | 89 | while True: 90 | p.duty_u16(duty_u16) 91 | 92 | sleep(1 / 1000) 93 | 94 | duty_u16 += delta_d 95 | if duty_u16 >= DUTY_MAX: 96 | duty_u16 = DUTY_MAX 97 | delta_d = -delta_d 98 | elif duty_u16 <= 0: 99 | duty_u16 = 0 100 | delta_d = -delta_d 101 | 102 | See PWM wave at Pin(5) with an oscilloscope. 103 | 104 | Note: the Pin.OUT mode does not need to be specified. The channel is initialized 105 | to PWM mode internally once for each Pin that is passed to the PWM constructor. 106 | 107 | The following code is wrong:: 108 | 109 | pwm = PWM(Pin(5, Pin.OUT), freq=1000, duty=512) # Pin(5) in PWM mode here 110 | pwm = PWM(Pin(5, Pin.OUT), freq=500, duty=256) # Pin(5) in OUT mode here, PWM is off 111 | 112 | Use this code instead:: 113 | 114 | pwm = PWM(Pin(5), freq=1000, duty=512) 115 | pwm.init(freq=500, duty=256) 116 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | MicroPython documentation and references 2 | ======================================== 3 | 4 | .. toctree:: 5 | 6 | cyberbrick_core/start/index.rst 7 | cyberbrick_core/lib/index.rst 8 | library/index.rst 9 | reference/index.rst 10 | license.rst 11 | cyberbrick_core/quickref.rst 12 | -------------------------------------------------------------------------------- /docs/library/_thread.rst: -------------------------------------------------------------------------------- 1 | :mod:`_thread` -- multithreading support 2 | ======================================== 3 | 4 | .. module:: _thread 5 | :synopsis: multithreading support 6 | 7 | |see_cpython_module| :mod:`python:_thread`. 8 | 9 | This module implements multithreading support. 10 | 11 | This module is highly experimental and its API is not yet fully settled 12 | and not yet described in this documentation. 13 | -------------------------------------------------------------------------------- /docs/library/array.rst: -------------------------------------------------------------------------------- 1 | :mod:`array` -- arrays of numeric data 2 | ====================================== 3 | 4 | .. module:: array 5 | :synopsis: efficient arrays of numeric data 6 | 7 | |see_cpython_module| :mod:`python:array`. 8 | 9 | Supported format codes: ``b``, ``B``, ``h``, ``H``, ``i``, ``I``, ``l``, 10 | ``L``, ``q``, ``Q``, ``f``, ``d`` (the latter 2 depending on the 11 | floating-point support). 12 | 13 | Classes 14 | ------- 15 | 16 | .. class:: array(typecode, [iterable]) 17 | 18 | Create array with elements of given type. Initial contents of the 19 | array are given by *iterable*. If it is not provided, an empty 20 | array is created. 21 | 22 | .. method:: append(val) 23 | 24 | Append new element *val* to the end of array, growing it. 25 | 26 | .. method:: extend(iterable) 27 | 28 | Append new elements as contained in *iterable* to the end of 29 | array, growing it. 30 | 31 | .. method:: __getitem__(index) 32 | 33 | Indexed read of the array, called as ``a[index]`` (where ``a`` is an ``array``). 34 | Returns a value if *index* is an ``int`` and an ``array`` if *index* is a slice. 35 | Negative indices count from the end and ``IndexError`` is thrown if the index is 36 | out of range. 37 | 38 | **Note:** ``__getitem__`` cannot be called directly (``a.__getitem__(index)`` fails) and 39 | is not present in ``__dict__``, however ``a[index]`` does work. 40 | 41 | .. method:: __setitem__(index, value) 42 | 43 | Indexed write into the array, called as ``a[index] = value`` (where ``a`` is an ``array``). 44 | ``value`` is a single value if *index* is an ``int`` and an ``array`` if *index* is a slice. 45 | Negative indices count from the end and ``IndexError`` is thrown if the index is out of range. 46 | 47 | **Note:** ``__setitem__`` cannot be called directly (``a.__setitem__(index, value)`` fails) and 48 | is not present in ``__dict__``, however ``a[index] = value`` does work. 49 | 50 | .. method:: __len__() 51 | 52 | Returns the number of items in the array, called as ``len(a)`` (where ``a`` is an ``array``). 53 | 54 | **Note:** ``__len__`` cannot be called directly (``a.__len__()`` fails) and the 55 | method is not present in ``__dict__``, however ``len(a)`` does work. 56 | 57 | .. method:: __add__(other) 58 | 59 | Return a new ``array`` that is the concatenation of the array with *other*, called as 60 | ``a + other`` (where ``a`` and *other* are both ``arrays``). 61 | 62 | **Note:** ``__add__`` cannot be called directly (``a.__add__(other)`` fails) and 63 | is not present in ``__dict__``, however ``a + other`` does work. 64 | 65 | .. method:: __iadd__(other) 66 | 67 | Concatenates the array with *other* in-place, called as ``a += other`` (where ``a`` and *other* 68 | are both ``arrays``). Equivalent to ``extend(other)``. 69 | 70 | **Note:** ``__iadd__`` cannot be called directly (``a.__iadd__(other)`` fails) and 71 | is not present in ``__dict__``, however ``a += other`` does work. 72 | 73 | .. method:: __repr__() 74 | 75 | Returns the string representation of the array, called as ``str(a)`` or ``repr(a)``` 76 | (where ``a`` is an ``array``). Returns the string ``"array(, [])"``, 77 | where ```` is the type code letter for the array and ```` is a comma 78 | separated list of the elements of the array. 79 | 80 | **Note:** ``__repr__`` cannot be called directly (``a.__repr__()`` fails) and 81 | is not present in ``__dict__``, however ``str(a)`` and ``repr(a)`` both work. 82 | -------------------------------------------------------------------------------- /docs/library/binascii.rst: -------------------------------------------------------------------------------- 1 | :mod:`binascii` -- binary/ASCII conversions 2 | =========================================== 3 | 4 | .. module:: binascii 5 | :synopsis: binary/ASCII conversions 6 | 7 | |see_cpython_module| :mod:`python:binascii`. 8 | 9 | This module implements conversions between binary data and various 10 | encodings of it in ASCII form (in both directions). 11 | 12 | Functions 13 | --------- 14 | 15 | .. function:: hexlify(data, [sep]) 16 | 17 | Convert the bytes in the *data* object to a hexadecimal representation. 18 | Returns a bytes object. 19 | 20 | If the additional argument *sep* is supplied it is used as a separator 21 | between hexadecimal values. 22 | 23 | .. function:: unhexlify(data) 24 | 25 | Convert hexadecimal data to binary representation. Returns bytes string. 26 | (i.e. inverse of hexlify) 27 | 28 | .. function:: a2b_base64(data) 29 | 30 | Decode base64-encoded data, ignoring invalid characters in the input. 31 | Conforms to `RFC 2045 s.6.8 `_. 32 | Returns a bytes object. 33 | 34 | .. function:: b2a_base64(data, *, newline=True) 35 | 36 | Encode binary data in base64 format, as in `RFC 3548 37 | `_. Returns the encoded data 38 | followed by a newline character if newline is true, as a bytes object. 39 | -------------------------------------------------------------------------------- /docs/library/btree.rst: -------------------------------------------------------------------------------- 1 | :mod:`btree` -- simple BTree database 2 | ===================================== 3 | 4 | .. module:: btree 5 | :synopsis: simple BTree database 6 | 7 | The ``btree`` module implements a simple key-value database using external 8 | storage (disk files, or in general case, a random-access `stream`). Keys are 9 | stored sorted in the database, and besides efficient retrieval by a key 10 | value, a database also supports efficient ordered range scans (retrieval 11 | of values with the keys in a given range). On the application interface 12 | side, BTree database work as close a possible to a way standard `dict` 13 | type works, one notable difference is that both keys and values must 14 | be `bytes`-like objects (so, if you want to store objects of other types, you 15 | need to first serialize them to `str` or `bytes` or another type that supports 16 | the buffer protocol). 17 | 18 | The module is based on the well-known BerkelyDB library, version 1.xx. 19 | 20 | Example:: 21 | 22 | import btree 23 | 24 | # First, we need to open a stream which holds a database 25 | # This is usually a file, but can be in-memory database 26 | # using io.BytesIO, a raw flash partition, etc. 27 | # Oftentimes, you want to create a database file if it doesn't 28 | # exist and open if it exists. Idiom below takes care of this. 29 | # DO NOT open database with "a+b" access mode. 30 | try: 31 | f = open("mydb", "r+b") 32 | except OSError: 33 | f = open("mydb", "w+b") 34 | 35 | # Now open a database itself 36 | db = btree.open(f) 37 | 38 | # The keys you add will be sorted internally in the database 39 | db[b"3"] = b"three" 40 | db[b"1"] = b"one" 41 | db[b"2"] = b"two" 42 | 43 | # Assume that any changes are cached in memory unless 44 | # explicitly flushed (or database closed). Flush database 45 | # at the end of each "transaction". 46 | db.flush() 47 | 48 | # Prints b'two' 49 | print(db[b"2"]) 50 | 51 | # Iterate over sorted keys in the database, starting from b"2" 52 | # until the end of the database, returning only values. 53 | # Mind that arguments passed to values() method are *key* values. 54 | # Prints: 55 | # b'two' 56 | # b'three' 57 | for word in db.values(b"2"): 58 | print(word) 59 | 60 | del db[b"2"] 61 | 62 | # No longer true, prints False 63 | print(b"2" in db) 64 | 65 | # Prints: 66 | # b"1" 67 | # b"3" 68 | for key in db: 69 | print(key) 70 | 71 | db.close() 72 | 73 | # Don't forget to close the underlying stream! 74 | f.close() 75 | 76 | 77 | Functions 78 | --------- 79 | 80 | .. function:: open(stream, *, flags=0, pagesize=0, cachesize=0, minkeypage=0) 81 | 82 | Open a database from a random-access `stream` (like an open file). All 83 | other parameters are optional and keyword-only, and allow to tweak advanced 84 | parameters of the database operation (most users will not need them): 85 | 86 | * *flags* - Currently unused. 87 | * *pagesize* - Page size used for the nodes in BTree. Acceptable range 88 | is 512-65536. If 0, a port-specific default will be used, optimized for 89 | port's memory usage and/or performance. 90 | * *cachesize* - Suggested memory cache size in bytes. For a 91 | board with enough memory using larger values may improve performance. 92 | Cache policy is as follows: entire cache is not allocated at once; 93 | instead, accessing a new page in database will allocate a memory buffer 94 | for it, until value specified by *cachesize* is reached. Then, these 95 | buffers will be managed using LRU (least recently used) policy. More 96 | buffers may still be allocated if needed (e.g., if a database contains 97 | big keys and/or values). Allocated cache buffers aren't reclaimed. 98 | * *minkeypage* - Minimum number of keys to store per page. Default value 99 | of 0 equivalent to 2. 100 | 101 | Returns a BTree object, which implements a dictionary protocol (set 102 | of methods), and some additional methods described below. 103 | 104 | Methods 105 | ------- 106 | 107 | .. method:: btree.close() 108 | 109 | Close the database. It's mandatory to close the database at the end of 110 | processing, as some unwritten data may be still in the cache. Note that 111 | this does not close underlying stream with which the database was opened, 112 | it should be closed separately (which is also mandatory to make sure that 113 | data flushed from buffer to the underlying storage). 114 | 115 | .. method:: btree.flush() 116 | 117 | Flush any data in cache to the underlying stream. 118 | 119 | .. method:: btree.__getitem__(key) 120 | btree.get(key, default=None, /) 121 | btree.__setitem__(key, val) 122 | btree.__delitem__(key) 123 | btree.__contains__(key) 124 | 125 | Standard dictionary methods. 126 | 127 | .. method:: btree.__iter__() 128 | 129 | A BTree object can be iterated over directly (similar to a dictionary) 130 | to get access to all keys in order. 131 | 132 | .. method:: btree.keys([start_key, [end_key, [flags]]]) 133 | btree.values([start_key, [end_key, [flags]]]) 134 | btree.items([start_key, [end_key, [flags]]]) 135 | 136 | These methods are similar to standard dictionary methods, but also can 137 | take optional parameters to iterate over a key sub-range, instead of 138 | the entire database. Note that for all 3 methods, *start_key* and 139 | *end_key* arguments represent key values. For example, `values()` 140 | method will iterate over values corresponding to they key range 141 | given. None values for *start_key* means "from the first key", no 142 | *end_key* or its value of None means "until the end of database". 143 | By default, range is inclusive of *start_key* and exclusive of 144 | *end_key*, you can include *end_key* in iteration by passing *flags* 145 | of `btree.INCL`. You can iterate in descending key direction 146 | by passing *flags* of `btree.DESC`. The flags values can be ORed 147 | together. 148 | 149 | Constants 150 | --------- 151 | 152 | .. data:: INCL 153 | 154 | A flag for `keys()`, `values()`, `items()` methods to specify that 155 | scanning should be inclusive of the end key. 156 | 157 | .. data:: DESC 158 | 159 | A flag for `keys()`, `values()`, `items()` methods to specify that 160 | scanning should be in descending direction of keys. 161 | -------------------------------------------------------------------------------- /docs/library/builtins.rst: -------------------------------------------------------------------------------- 1 | :mod:`builtins` -- builtin functions and exceptions 2 | =================================================== 3 | 4 | All builtin functions and exceptions are described here. They are also 5 | available via ``builtins`` module. 6 | 7 | Functions and types 8 | ------------------- 9 | 10 | .. function:: abs() 11 | 12 | .. function:: all() 13 | 14 | .. function:: any() 15 | 16 | .. function:: bin() 17 | 18 | .. class:: bool() 19 | 20 | .. class:: bytearray() 21 | 22 | .. class:: bytes() 23 | 24 | |see_cpython| `python:bytes`. 25 | 26 | .. function:: callable() 27 | 28 | .. function:: chr() 29 | 30 | .. function:: classmethod() 31 | 32 | .. function:: compile() 33 | 34 | .. class:: complex() 35 | 36 | .. function:: delattr(obj, name) 37 | 38 | The argument *name* should be a string, and this function deletes the named 39 | attribute from the object given by *obj*. 40 | 41 | .. class:: dict() 42 | 43 | .. function:: dir() 44 | 45 | .. function:: divmod() 46 | 47 | .. function:: enumerate() 48 | 49 | .. function:: eval() 50 | 51 | .. function:: exec() 52 | 53 | .. function:: filter() 54 | 55 | .. class:: float() 56 | 57 | .. class:: frozenset() 58 | 59 | .. function:: getattr() 60 | 61 | .. function:: globals() 62 | 63 | .. function:: hasattr() 64 | 65 | .. function:: hash() 66 | 67 | .. function:: hex() 68 | 69 | .. function:: id() 70 | 71 | .. function:: input() 72 | 73 | .. class:: int() 74 | 75 | .. classmethod:: from_bytes(bytes, byteorder) 76 | 77 | In MicroPython, `byteorder` parameter must be positional (this is 78 | compatible with CPython). 79 | 80 | .. method:: to_bytes(size, byteorder) 81 | 82 | In MicroPython, `byteorder` parameter must be positional (this is 83 | compatible with CPython). 84 | 85 | .. function:: isinstance() 86 | 87 | .. function:: issubclass() 88 | 89 | .. function:: iter() 90 | 91 | .. function:: len() 92 | 93 | .. class:: list() 94 | 95 | .. function:: locals() 96 | 97 | .. function:: map() 98 | 99 | .. function:: max() 100 | 101 | .. class:: memoryview() 102 | 103 | .. function:: min() 104 | 105 | .. function:: next() 106 | 107 | .. class:: object() 108 | 109 | .. function:: oct() 110 | 111 | .. function:: open() 112 | 113 | .. function:: ord() 114 | 115 | .. function:: pow() 116 | 117 | .. function:: print() 118 | 119 | .. function:: property() 120 | 121 | .. function:: range() 122 | 123 | .. function:: repr() 124 | 125 | .. function:: reversed() 126 | 127 | .. function:: round() 128 | 129 | .. class:: set() 130 | 131 | .. function:: setattr() 132 | 133 | .. class:: slice() 134 | 135 | The *slice* builtin is the type that slice objects have. 136 | 137 | .. function:: sorted() 138 | 139 | .. function:: staticmethod() 140 | 141 | .. class:: str() 142 | 143 | .. function:: sum() 144 | 145 | .. function:: super() 146 | 147 | .. class:: tuple() 148 | 149 | .. function:: type() 150 | 151 | .. function:: zip() 152 | 153 | 154 | Exceptions 155 | ---------- 156 | 157 | .. exception:: AssertionError 158 | 159 | .. exception:: AttributeError 160 | 161 | .. exception:: Exception 162 | 163 | .. exception:: ImportError 164 | 165 | .. exception:: IndexError 166 | 167 | .. exception:: KeyboardInterrupt 168 | 169 | .. exception:: KeyError 170 | 171 | .. exception:: MemoryError 172 | 173 | .. exception:: NameError 174 | 175 | .. exception:: NotImplementedError 176 | 177 | .. exception:: OSError 178 | 179 | .. exception:: RuntimeError 180 | 181 | .. exception:: StopIteration 182 | 183 | .. exception:: SyntaxError 184 | 185 | .. exception:: SystemExit 186 | 187 | |see_cpython| `python:SystemExit`. 188 | 189 | .. exception:: TypeError 190 | 191 | |see_cpython| `python:TypeError`. 192 | 193 | .. exception:: ValueError 194 | 195 | .. exception:: ZeroDivisionError 196 | -------------------------------------------------------------------------------- /docs/library/cmath.rst: -------------------------------------------------------------------------------- 1 | :mod:`cmath` -- mathematical functions for complex numbers 2 | ========================================================== 3 | 4 | .. module:: cmath 5 | :synopsis: mathematical functions for complex numbers 6 | 7 | |see_cpython_module| :mod:`python:cmath`. 8 | 9 | The ``cmath`` module provides some basic mathematical functions for 10 | working with complex numbers. 11 | 12 | Availability: not available on WiPy and ESP8266. Floating point support 13 | required for this module. 14 | 15 | Functions 16 | --------- 17 | 18 | .. function:: cos(z) 19 | 20 | Return the cosine of ``z``. 21 | 22 | .. function:: exp(z) 23 | 24 | Return the exponential of ``z``. 25 | 26 | .. function:: log(z) 27 | 28 | Return the natural logarithm of ``z``. The branch cut is along the negative real axis. 29 | 30 | .. function:: log10(z) 31 | 32 | Return the base-10 logarithm of ``z``. The branch cut is along the negative real axis. 33 | 34 | .. function:: phase(z) 35 | 36 | Returns the phase of the number ``z``, in the range (-pi, +pi]. 37 | 38 | .. function:: polar(z) 39 | 40 | Returns, as a tuple, the polar form of ``z``. 41 | 42 | .. function:: rect(r, phi) 43 | 44 | Returns the complex number with modulus ``r`` and phase ``phi``. 45 | 46 | .. function:: sin(z) 47 | 48 | Return the sine of ``z``. 49 | 50 | .. function:: sqrt(z) 51 | 52 | Return the square-root of ``z``. 53 | 54 | Constants 55 | --------- 56 | 57 | .. data:: e 58 | 59 | base of the natural logarithm 60 | 61 | .. data:: pi 62 | 63 | the ratio of a circle's circumference to its diameter 64 | -------------------------------------------------------------------------------- /docs/library/collections.rst: -------------------------------------------------------------------------------- 1 | :mod:`collections` -- collection and container types 2 | ==================================================== 3 | 4 | .. module:: collections 5 | :synopsis: collection and container types 6 | 7 | |see_cpython_module| :mod:`python:collections`. 8 | 9 | This module implements advanced collection and container types to 10 | hold/accumulate various objects. 11 | 12 | Classes 13 | ------- 14 | 15 | .. class:: deque(iterable, maxlen[, flags]) 16 | 17 | Deques (double-ended queues) are a list-like container that support O(1) 18 | appends and pops from either side of the deque. New deques are created 19 | using the following arguments: 20 | 21 | - *iterable* is an iterable used to populate the deque when it is 22 | created. It can be an empty tuple or list to create a deque that 23 | is initially empty. 24 | 25 | - *maxlen* must be specified and the deque will be bounded to this 26 | maximum length. Once the deque is full, any new items added will 27 | discard items from the opposite end. 28 | 29 | - The optional *flags* can be 1 to check for overflow when adding items. 30 | 31 | Deque objects support `bool`, `len`, iteration and subscript load and store. 32 | They also have the following methods: 33 | 34 | .. method:: deque.append(x) 35 | 36 | Add *x* to the right side of the deque. 37 | Raises ``IndexError`` if overflow checking is enabled and there is 38 | no more room in the queue. 39 | 40 | .. method:: deque.appendleft(x) 41 | 42 | Add *x* to the left side of the deque. 43 | Raises ``IndexError`` if overflow checking is enabled and there is 44 | no more room in the queue. 45 | 46 | .. method:: deque.pop() 47 | 48 | Remove and return an item from the right side of the deque. 49 | Raises ``IndexError`` if no items are present. 50 | 51 | .. method:: deque.popleft() 52 | 53 | Remove and return an item from the left side of the deque. 54 | Raises ``IndexError`` if no items are present. 55 | 56 | .. method:: deque.extend(iterable) 57 | 58 | Extend the deque by appending all the items from *iterable* to 59 | the right of the deque. 60 | Raises ``IndexError`` if overflow checking is enabled and there is 61 | no more room in the deque. 62 | 63 | .. function:: namedtuple(name, fields) 64 | 65 | This is factory function to create a new namedtuple type with a specific 66 | name and set of fields. A namedtuple is a subclass of tuple which allows 67 | to access its fields not just by numeric index, but also with an attribute 68 | access syntax using symbolic field names. Fields is a sequence of strings 69 | specifying field names. For compatibility with CPython it can also be a 70 | a string with space-separated field named (but this is less efficient). 71 | Example of use:: 72 | 73 | from collections import namedtuple 74 | 75 | MyTuple = namedtuple("MyTuple", ("id", "name")) 76 | t1 = MyTuple(1, "foo") 77 | t2 = MyTuple(2, "bar") 78 | print(t1.name) 79 | assert t2.name == t2[1] 80 | 81 | .. class:: OrderedDict(...) 82 | 83 | ``dict`` type subclass which remembers and preserves the order of keys 84 | added. When ordered dict is iterated over, keys/items are returned in 85 | the order they were added:: 86 | 87 | from collections import OrderedDict 88 | 89 | # To make benefit of ordered keys, OrderedDict should be initialized 90 | # from sequence of (key, value) pairs. 91 | d = OrderedDict([("z", 1), ("a", 2)]) 92 | # More items can be added as usual 93 | d["w"] = 5 94 | d["b"] = 3 95 | for k, v in d.items(): 96 | print(k, v) 97 | 98 | Output:: 99 | 100 | z 1 101 | a 2 102 | w 5 103 | b 3 104 | -------------------------------------------------------------------------------- /docs/library/cryptolib.rst: -------------------------------------------------------------------------------- 1 | :mod:`cryptolib` -- cryptographic ciphers 2 | ========================================= 3 | 4 | .. module:: cryptolib 5 | :synopsis: cryptographic ciphers 6 | 7 | Classes 8 | ------- 9 | 10 | .. class:: aes 11 | 12 | .. classmethod:: __init__(key, mode, [IV]) 13 | 14 | Initialize cipher object, suitable for encryption/decryption. Note: 15 | after initialization, cipher object can be use only either for 16 | encryption or decryption. Running decrypt() operation after encrypt() 17 | or vice versa is not supported. 18 | 19 | Parameters are: 20 | 21 | * *key* is an encryption/decryption key (bytes-like). 22 | * *mode* is: 23 | 24 | * ``1`` (or ``cryptolib.MODE_ECB`` if it exists) for Electronic Code Book (ECB). 25 | * ``2`` (or ``cryptolib.MODE_CBC`` if it exists) for Cipher Block Chaining (CBC). 26 | * ``6`` (or ``cryptolib.MODE_CTR`` if it exists) for Counter mode (CTR). 27 | 28 | * *IV* is an initialization vector for CBC mode. 29 | * For Counter mode, *IV* is the initial value for the counter. 30 | 31 | .. method:: encrypt(in_buf, [out_buf]) 32 | 33 | Encrypt *in_buf*. If no *out_buf* is given result is returned as a 34 | newly allocated `bytes` object. Otherwise, result is written into 35 | mutable buffer *out_buf*. *in_buf* and *out_buf* can also refer 36 | to the same mutable buffer, in which case data is encrypted in-place. 37 | 38 | .. method:: decrypt(in_buf, [out_buf]) 39 | 40 | Like `encrypt()`, but for decryption. 41 | -------------------------------------------------------------------------------- /docs/library/deflate.rst: -------------------------------------------------------------------------------- 1 | :mod:`deflate` -- deflate compression & decompression 2 | ===================================================== 3 | 4 | .. module:: deflate 5 | :synopsis: deflate compression & decompression 6 | 7 | This module allows compression and decompression of binary data with the 8 | `DEFLATE algorithm `_ 9 | (commonly used in the zlib library and gzip archiver). 10 | 11 | **Availability:** 12 | 13 | * Added in MicroPython v1.21. 14 | 15 | * Decompression: Enabled via the ``MICROPY_PY_DEFLATE`` build option, on by default 16 | on ports with the "extra features" level or higher (which is most boards). 17 | 18 | * Compression: Enabled via the ``MICROPY_PY_DEFLATE_COMPRESS`` build option, on 19 | by default on ports with the "full features" level or higher (generally this means 20 | you need to build your own firmware to enable this). 21 | 22 | Classes 23 | ------- 24 | 25 | .. class:: DeflateIO(stream, format=AUTO, wbits=0, close=False, /) 26 | 27 | This class can be used to wrap a *stream* which is any 28 | :term:`stream-like ` object such as a file, socket, or stream 29 | (including :class:`io.BytesIO`). It is itself a stream and implements the 30 | standard read/readinto/write/close methods. 31 | 32 | The *stream* must be a blocking stream. Non-blocking streams are currently 33 | not supported. 34 | 35 | The *format* can be set to any of the constants defined below, and defaults 36 | to ``AUTO`` which for decompressing will auto-detect gzip or zlib streams, 37 | and for compressing it will generate a raw stream. 38 | 39 | The *wbits* parameter sets the base-2 logarithm of the DEFLATE dictionary 40 | window size. So for example, setting *wbits* to ``10`` sets the window size 41 | to 1024 bytes. Valid values are ``5`` to ``15`` inclusive (corresponding to 42 | window sizes of 32 to 32k bytes). 43 | 44 | If *wbits* is set to ``0`` (the default), then for compression a window size 45 | of 256 bytes will be used (as if *wbits* was set to 8). For decompression, it 46 | depends on the format: 47 | 48 | * ``RAW`` will use 256 bytes (corresponding to *wbits* set to 8). 49 | * ``ZLIB`` (or ``AUTO`` with zlib detected) will use the value from the zlib 50 | header. 51 | * ``GZIP`` (or ``AUTO`` with gzip detected) will use 32 kilobytes 52 | (corresponding to *wbits* set to 15). 53 | 54 | See the :ref:`window size ` notes below for more information 55 | about the window size, zlib, and gzip streams. 56 | 57 | If *close* is set to ``True`` then the underlying stream will be closed 58 | automatically when the :class:`deflate.DeflateIO` stream is closed. This is 59 | useful if you want to return a :class:`deflate.DeflateIO` stream that wraps 60 | another stream and not have the caller need to know about managing the 61 | underlying stream. 62 | 63 | If compression is enabled, a given :class:`deflate.DeflateIO` instance 64 | supports both reading and writing. For example, a bidirectional stream like 65 | a socket can be wrapped, which allows for compression/decompression in both 66 | directions. 67 | 68 | Constants 69 | --------- 70 | 71 | .. data:: deflate.AUTO 72 | deflate.RAW 73 | deflate.ZLIB 74 | deflate.GZIP 75 | 76 | Supported values for the *format* parameter. 77 | 78 | Examples 79 | -------- 80 | 81 | A typical use case for :class:`deflate.DeflateIO` is to read or write a compressed 82 | file from storage: 83 | 84 | .. code:: python 85 | 86 | import deflate 87 | 88 | # Writing a zlib-compressed stream (uses the default window size of 256 bytes). 89 | with open("data.gz", "wb") as f: 90 | with deflate.DeflateIO(f, deflate.ZLIB) as d: 91 | # Use d.write(...) etc 92 | 93 | # Reading a zlib-compressed stream (auto-detect window size). 94 | with open("data.z", "rb") as f: 95 | with deflate.DeflateIO(f, deflate.ZLIB) as d: 96 | # Use d.read(), d.readinto(), etc. 97 | 98 | Because :class:`deflate.DeflateIO` is a stream, it can be used for example 99 | with :meth:`json.dump` and :meth:`json.load` (and any other places streams can 100 | be used): 101 | 102 | .. code:: python 103 | 104 | import deflate, json 105 | 106 | # Write a dictionary as JSON in gzip format, with a 107 | # small (64 byte) window size. 108 | config = { ... } 109 | with open("config.gz", "wb") as f: 110 | with deflate.DeflateIO(f, deflate.GZIP, 6) as f: 111 | json.dump(config, f) 112 | 113 | # Read back that dictionary. 114 | with open("config.gz", "rb") as f: 115 | with deflate.DeflateIO(f, deflate.GZIP, 6) as f: 116 | config = json.load(f) 117 | 118 | If your source data is not in a stream format, you can use :class:`io.BytesIO` 119 | to turn it into a stream suitable for use with :class:`deflate.DeflateIO`: 120 | 121 | .. code:: python 122 | 123 | import deflate, io 124 | 125 | # Decompress a bytes/bytearray value. 126 | compressed_data = get_data_z() 127 | with deflate.DeflateIO(io.BytesIO(compressed_data), deflate.ZLIB) as d: 128 | decompressed_data = d.read() 129 | 130 | # Compress a bytes/bytearray value. 131 | uncompressed_data = get_data() 132 | stream = io.BytesIO() 133 | with deflate.DeflateIO(stream, deflate.ZLIB) as d: 134 | d.write(uncompressed_data) 135 | compressed_data = stream.getvalue() 136 | 137 | .. _deflate_wbits: 138 | 139 | Deflate window size 140 | ------------------- 141 | 142 | The window size limits how far back in the stream the (de)compressor can 143 | reference. Increasing the window size will improve compression, but will require 144 | more memory and make the compressor slower. 145 | 146 | If an input stream was compressed a given window size, then `DeflateIO` 147 | using a smaller window size will fail mid-way during decompression with 148 | :exc:`OSError`, but only if a back-reference actually refers back further 149 | than the decompressor's window size. This means it may be possible to decompress 150 | with a smaller window size. For example, this would trivially be the case if the 151 | original uncompressed data is shorter than the window size. 152 | 153 | Decompression 154 | ~~~~~~~~~~~~~ 155 | 156 | The zlib format includes a header which specifies the window size that was used 157 | to compress the data. This indicates the maximum window size required to 158 | decompress this stream. If this header value is less than the specified *wbits* 159 | value (or if *wbits* is unset), then the header value will be used. 160 | 161 | The gzip format does not include the window size in the header, and assumes that 162 | all gzip compressors (e.g. the ``gzip`` utility, or CPython's implementation of 163 | :class:`gzip.GzipFile`) use the maximum window size of 32kiB. For this reason, 164 | if the *wbits* parameter is not set, the decompressor will use a 32 kiB window 165 | size (corresponding to *wbits* set to 15). This means that to be able to 166 | decompress an arbitrary gzip stream, you must have at least this much RAM 167 | available. If you control the source data, consider instead using the zlib 168 | format with a smaller window size. 169 | 170 | The raw format has no header and therefore does not include any information 171 | about the window size. If *wbits* is not set, then it will default to a window 172 | size of 256 bytes, which may not be large enough for a given stream. Therefore 173 | it is recommended that you should always explicitly set *wbits* if using the raw 174 | format. 175 | 176 | Compression 177 | ~~~~~~~~~~~ 178 | 179 | For compression, MicroPython will default to a window size of 256 bytes for all 180 | formats. This provides a reasonable amount of compression with minimal memory 181 | usage and fast compression time, and will generate output that will work with 182 | any decompressor. 183 | -------------------------------------------------------------------------------- /docs/library/errno.rst: -------------------------------------------------------------------------------- 1 | :mod:`errno` -- system error codes 2 | ================================== 3 | 4 | .. module:: errno 5 | :synopsis: system error codes 6 | 7 | |see_cpython_module| :mod:`python:errno`. 8 | 9 | This module provides access to symbolic error codes for `OSError` exception. 10 | A particular inventory of codes depends on :term:`MicroPython port`. 11 | 12 | Constants 13 | --------- 14 | 15 | .. data:: EEXIST, EAGAIN, etc. 16 | 17 | Error codes, based on ANSI C/POSIX standard. All error codes start with 18 | "E". As mentioned above, inventory of the codes depends on 19 | :term:`MicroPython port`. Errors are usually accessible as ``exc.errno`` 20 | where ``exc`` is an instance of `OSError`. Usage example:: 21 | 22 | try: 23 | os.mkdir("my_dir") 24 | except OSError as exc: 25 | if exc.errno == errno.EEXIST: 26 | print("Directory already exists") 27 | 28 | .. data:: errorcode 29 | 30 | Dictionary mapping numeric error codes to strings with symbolic error 31 | code (see above):: 32 | 33 | >>> print(errno.errorcode[errno.EEXIST]) 34 | EEXIST 35 | -------------------------------------------------------------------------------- /docs/library/esp.rst: -------------------------------------------------------------------------------- 1 | :mod:`esp` --- functions related to the ESP8266 and ESP32 2 | ========================================================= 3 | 4 | .. module:: esp 5 | :synopsis: functions related to the ESP8266 and ESP32 6 | 7 | The ``esp`` module contains specific functions related to both the ESP8266 and 8 | ESP32 modules. Some functions are only available on one or the other of these 9 | ports. 10 | 11 | 12 | Functions 13 | --------- 14 | 15 | .. function:: sleep_type([sleep_type]) 16 | 17 | **Note**: ESP8266 only 18 | 19 | Get or set the sleep type. 20 | 21 | If the *sleep_type* parameter is provided, sets the sleep type to its 22 | value. If the function is called without parameters, returns the current 23 | sleep type. 24 | 25 | The possible sleep types are defined as constants: 26 | 27 | * ``SLEEP_NONE`` -- all functions enabled, 28 | * ``SLEEP_MODEM`` -- modem sleep, shuts down the WiFi Modem circuit. 29 | * ``SLEEP_LIGHT`` -- light sleep, shuts down the WiFi Modem circuit 30 | and suspends the processor periodically. 31 | 32 | The system enters the set sleep mode automatically when possible. 33 | 34 | .. function:: deepsleep(time_us=0, /) 35 | 36 | **Note**: ESP8266 only - use `machine.deepsleep()` on ESP32 37 | 38 | Enter deep sleep. 39 | 40 | The whole module powers down, except for the RTC clock circuit, which can 41 | be used to restart the module after the specified time if the pin 16 is 42 | connected to the reset pin. Otherwise the module will sleep until manually 43 | reset. 44 | 45 | .. function:: osdebug(uart_no) 46 | 47 | .. note:: This is the ESP8266 form of this function. 48 | 49 | Change the level of OS serial debug log messages. On boot, 50 | OS serial debug log messages are disabled. 51 | 52 | ``uart_no`` is the number of the UART peripheral which should receive 53 | OS-level output, or ``None`` to disable OS serial debug log messages. 54 | 55 | .. function:: osdebug(uart_no, [level]) 56 | :no-index: 57 | 58 | .. note:: This is the ESP32 form of this function. 59 | 60 | Change the level of OS serial debug log messages. On boot, OS 61 | serial debug log messages are limited to Error output only. 62 | 63 | The behaviour of this function depends on the arguments passed to it. The 64 | following combinations are supported: 65 | 66 | ``osdebug(None)`` restores the default OS debug log message level 67 | (``LOG_ERROR``). 68 | 69 | ``osdebug(0)`` enables all available OS debug log messages (in the 70 | default build configuration this is ``LOG_INFO``). 71 | 72 | ``osdebug(0, level)`` sets the OS debug log message level to the 73 | specified value. The log levels are defined as constants: 74 | 75 | * ``LOG_NONE`` -- No log output 76 | * ``LOG_ERROR`` -- Critical errors, software module can not recover on its own 77 | * ``LOG_WARN`` -- Error conditions from which recovery measures have been taken 78 | * ``LOG_INFO`` -- Information messages which describe normal flow of events 79 | * ``LOG_DEBUG`` -- Extra information which is not necessary for normal use (values, pointers, sizes, etc) 80 | * ``LOG_VERBOSE`` -- Bigger chunks of debugging information, or frequent messages 81 | which can potentially flood the output 82 | 83 | .. note:: ``LOG_DEBUG`` and ``LOG_VERBOSE`` are not compiled into the 84 | MicroPython binary by default, to save size. A custom build with a 85 | modified "``sdkconfig``" source file is needed to see any output 86 | at these log levels. 87 | 88 | .. note:: Log output on ESP32 is automatically suspended in "Raw REPL" mode, 89 | to prevent communications issues. This means OS level logging is never 90 | seen when using ``mpremote run`` and similar tools. 91 | 92 | .. function:: set_native_code_location(start, length) 93 | 94 | **Note**: ESP8266 only 95 | 96 | Set the location that native code will be placed for execution after it is 97 | compiled. Native code is emitted when the ``@micropython.native``, 98 | ``@micropython.viper`` and ``@micropython.asm_xtensa`` decorators are applied 99 | to a function. The ESP8266 must execute code from either iRAM or the lower 100 | 1MByte of flash (which is memory mapped), and this function controls the 101 | location. 102 | 103 | If *start* and *length* are both ``None`` then the native code location is 104 | set to the unused portion of memory at the end of the iRAM1 region. The 105 | size of this unused portion depends on the firmware and is typically quite 106 | small (around 500 bytes), and is enough to store a few very small 107 | functions. The advantage of using this iRAM1 region is that it does not 108 | get worn out by writing to it. 109 | 110 | If neither *start* nor *length* are ``None`` then they should be integers. 111 | *start* should specify the byte offset from the beginning of the flash at 112 | which native code should be stored. *length* specifies how many bytes of 113 | flash from *start* can be used to store native code. *start* and *length* 114 | should be multiples of the sector size (being 4096 bytes). The flash will 115 | be automatically erased before writing to it so be sure to use a region of 116 | flash that is not otherwise used, for example by the firmware or the 117 | filesystem. 118 | 119 | When using the flash to store native code *start+length* must be less 120 | than or equal to 1MByte. Note that the flash can be worn out if repeated 121 | erasures (and writes) are made so use this feature sparingly. 122 | In particular, native code needs to be recompiled and rewritten to flash 123 | on each boot (including wake from deepsleep). 124 | 125 | In both cases above, using iRAM1 or flash, if there is no more room left 126 | in the specified region then the use of a native decorator on a function 127 | will lead to `MemoryError` exception being raised during compilation of 128 | that function. 129 | -------------------------------------------------------------------------------- /docs/library/gc.rst: -------------------------------------------------------------------------------- 1 | :mod:`gc` -- control the garbage collector 2 | ========================================== 3 | 4 | .. module:: gc 5 | :synopsis: control the garbage collector 6 | 7 | |see_cpython_module| :mod:`python:gc`. 8 | 9 | Functions 10 | --------- 11 | 12 | .. function:: enable() 13 | 14 | Enable automatic garbage collection. 15 | 16 | .. function:: disable() 17 | 18 | Disable automatic garbage collection. Heap memory can still be allocated, 19 | and garbage collection can still be initiated manually using :meth:`gc.collect`. 20 | 21 | .. function:: collect() 22 | 23 | Run a garbage collection. 24 | 25 | .. function:: mem_alloc() 26 | 27 | Return the number of bytes of heap RAM that are allocated by Python code. 28 | 29 | .. admonition:: Difference to CPython 30 | :class: attention 31 | 32 | This function is MicroPython extension. 33 | 34 | .. function:: mem_free() 35 | 36 | Return the number of bytes of heap RAM that is available for Python 37 | code to allocate, or -1 if this amount is not known. 38 | 39 | .. admonition:: Difference to CPython 40 | :class: attention 41 | 42 | This function is MicroPython extension. 43 | 44 | .. function:: threshold([amount]) 45 | 46 | Set or query the additional GC allocation threshold. Normally, a collection 47 | is triggered only when a new allocation cannot be satisfied, i.e. on an 48 | out-of-memory (OOM) condition. If this function is called, in addition to 49 | OOM, a collection will be triggered each time after *amount* bytes have been 50 | allocated (in total, since the previous time such an amount of bytes 51 | have been allocated). *amount* is usually specified as less than the 52 | full heap size, with the intention to trigger a collection earlier than when the 53 | heap becomes exhausted, and in the hope that an early collection will prevent 54 | excessive memory fragmentation. This is a heuristic measure, the effect 55 | of which will vary from application to application, as well as 56 | the optimal value of the *amount* parameter. 57 | 58 | Calling the function without argument will return the current value of 59 | the threshold. A value of -1 means a disabled allocation threshold. 60 | 61 | .. admonition:: Difference to CPython 62 | :class: attention 63 | 64 | This function is a MicroPython extension. CPython has a similar 65 | function - ``set_threshold()``, but due to different GC 66 | implementations, its signature and semantics are different. 67 | -------------------------------------------------------------------------------- /docs/library/gzip.rst: -------------------------------------------------------------------------------- 1 | :mod:`gzip` -- gzip compression & decompression 2 | =============================================== 3 | 4 | .. module:: gzip 5 | :synopsis: gzip compression & decompression 6 | 7 | |see_cpython_module| :mod:`python:gzip`. 8 | 9 | This module allows compression and decompression of binary data with the 10 | `DEFLATE algorithm `_ used by the gzip 11 | file format. 12 | 13 | .. note:: Prefer to use :class:`deflate.DeflateIO` instead of the functions in this 14 | module as it provides a streaming interface to compression and decompression 15 | which is convenient and more memory efficient when working with reading or 16 | writing compressed data to a file, socket, or stream. 17 | 18 | **Availability:** 19 | 20 | * This module is **not present by default** in official MicroPython firmware 21 | releases as it duplicates functionality available in the :mod:`deflate 22 | ` module. 23 | 24 | * A copy of this module can be installed (or frozen) 25 | from :term:`micropython-lib` (`source `_). 26 | See :ref:`packages` for more information. This documentation describes that module. 27 | 28 | * Compression support will only be available if compression support is enabled 29 | in the built-in :mod:`deflate ` module. 30 | 31 | Functions 32 | --------- 33 | 34 | .. function:: open(filename, mode, /) 35 | 36 | Wrapper around built-in :func:`open` returning a GzipFile instance. 37 | 38 | .. function:: decompress(data, /) 39 | 40 | Decompresses *data* into a bytes object. 41 | 42 | .. function:: compress(data, /) 43 | 44 | Compresses *data* into a bytes object. 45 | 46 | Classes 47 | ------- 48 | 49 | .. class:: GzipFile(*, fileobj, mode) 50 | 51 | This class can be used to wrap a *fileobj* which is any 52 | :term:`stream-like ` object such as a file, socket, or stream 53 | (including :class:`io.BytesIO`). It is itself a stream and implements the 54 | standard read/readinto/write/close methods. 55 | 56 | When the *mode* argument is ``"rb"``, reads from the GzipFile instance will 57 | decompress the data in the underlying stream and return decompressed data. 58 | 59 | If compression support is enabled then the *mode* argument can be set to 60 | ``"wb"``, and writes to the GzipFile instance will be compressed and written 61 | to the underlying stream. 62 | 63 | By default the GzipFile class will read and write data using the gzip file 64 | format, including a header and footer with checksum and a window size of 512 65 | bytes. 66 | 67 | The **file**, **compresslevel**, and **mtime** arguments are not 68 | supported. **fileobj** and **mode** must always be specified as keyword 69 | arguments. 70 | 71 | Examples 72 | -------- 73 | 74 | A typical use case for :class:`gzip.GzipFile` is to read or write a compressed 75 | file from storage: 76 | 77 | .. code:: python 78 | 79 | import gzip 80 | 81 | # Reading: 82 | with open("data.gz", "rb") as f: 83 | with gzip.GzipFile(fileobj=f, mode="rb") as g: 84 | # Use g.read(), g.readinto(), etc. 85 | 86 | # Same, but using gzip.open: 87 | with gzip.open("data.gz", "rb") as f: 88 | # Use f.read(), f.readinto(), etc. 89 | 90 | # Writing: 91 | with open("data.gz", "wb") as f: 92 | with gzip.GzipFile(fileobj=f, mode="wb") as g: 93 | # Use g.write(...) etc 94 | 95 | # Same, but using gzip.open: 96 | with gzip.open("data.gz", "wb") as f: 97 | # Use f.write(...) etc 98 | 99 | # Write a dictionary as JSON in gzip format, with a 100 | # small (64 byte) window size. 101 | config = { ... } 102 | with gzip.open("config.gz", "wb") as f: 103 | json.dump(config, f) 104 | 105 | For guidance on working with gzip sources and choosing the window size see the 106 | note at the :ref:`end of the deflate documentation `. 107 | -------------------------------------------------------------------------------- /docs/library/hashlib.rst: -------------------------------------------------------------------------------- 1 | :mod:`hashlib` -- hashing algorithms 2 | ==================================== 3 | 4 | .. module:: hashlib 5 | :synopsis: hashing algorithms 6 | 7 | |see_cpython_module| :mod:`python:hashlib`. 8 | 9 | This module implements binary data hashing algorithms. The exact inventory 10 | of available algorithms depends on a board. Among the algorithms which may 11 | be implemented: 12 | 13 | * SHA256 - The current generation, modern hashing algorithm (of SHA2 series). 14 | It is suitable for cryptographically-secure purposes. Included in the 15 | MicroPython core and any board is recommended to provide this, unless 16 | it has particular code size constraints. 17 | 18 | * SHA1 - A previous generation algorithm. Not recommended for new usages, 19 | but SHA1 is a part of number of Internet standards and existing 20 | applications, so boards targeting network connectivity and 21 | interoperability will try to provide this. 22 | 23 | * MD5 - A legacy algorithm, not considered cryptographically secure. Only 24 | selected boards, targeting interoperability with legacy applications, 25 | will offer this. 26 | 27 | Constructors 28 | ------------ 29 | 30 | .. class:: hashlib.sha256([data]) 31 | 32 | Create an SHA256 hasher object and optionally feed ``data`` into it. 33 | 34 | .. class:: hashlib.sha1([data]) 35 | 36 | Create an SHA1 hasher object and optionally feed ``data`` into it. 37 | 38 | .. class:: hashlib.md5([data]) 39 | 40 | Create an MD5 hasher object and optionally feed ``data`` into it. 41 | 42 | Methods 43 | ------- 44 | 45 | .. method:: hash.update(data) 46 | 47 | Feed more binary data into hash. 48 | 49 | .. method:: hash.digest() 50 | 51 | Return hash for all data passed through hash, as a bytes object. After this 52 | method is called, more data cannot be fed into the hash any longer. 53 | 54 | .. method:: hash.hexdigest() 55 | 56 | This method is NOT implemented. Use ``binascii.hexlify(hash.digest())`` 57 | to achieve a similar effect. 58 | -------------------------------------------------------------------------------- /docs/library/heapq.rst: -------------------------------------------------------------------------------- 1 | :mod:`heapq` -- heap queue algorithm 2 | ==================================== 3 | 4 | .. module:: heapq 5 | :synopsis: heap queue algorithm 6 | 7 | |see_cpython_module| :mod:`python:heapq`. 8 | 9 | This module implements the 10 | `min heap queue algorithm `_. 11 | 12 | A heap queue is essentially a list that has its elements stored in such a way 13 | that the first item of the list is always the smallest. 14 | 15 | Functions 16 | --------- 17 | 18 | .. function:: heappush(heap, item) 19 | 20 | Push the ``item`` onto the ``heap``. 21 | 22 | .. function:: heappop(heap) 23 | 24 | Pop the first item from the ``heap``, and return it. Raise ``IndexError`` if 25 | ``heap`` is empty. 26 | 27 | The returned item will be the smallest item in the ``heap``. 28 | 29 | .. function:: heapify(x) 30 | 31 | Convert the list ``x`` into a heap. This is an in-place operation. 32 | -------------------------------------------------------------------------------- /docs/library/io.rst: -------------------------------------------------------------------------------- 1 | :mod:`io` -- input/output streams 2 | ================================= 3 | 4 | .. module:: io 5 | :synopsis: input/output streams 6 | 7 | |see_cpython_module| :mod:`python:io`. 8 | 9 | This module contains additional types of `stream` (file-like) objects 10 | and helper functions. 11 | 12 | Conceptual hierarchy 13 | -------------------- 14 | 15 | .. admonition:: Difference to CPython 16 | :class: attention 17 | 18 | Conceptual hierarchy of stream base classes is simplified in MicroPython, 19 | as described in this section. 20 | 21 | (Abstract) base stream classes, which serve as a foundation for behaviour 22 | of all the concrete classes, adhere to few dichotomies (pair-wise 23 | classifications) in CPython. In MicroPython, they are somewhat simplified 24 | and made implicit to achieve higher efficiencies and save resources. 25 | 26 | An important dichotomy in CPython is unbuffered vs buffered streams. In 27 | MicroPython, all streams are currently unbuffered. This is because all 28 | modern OSes, and even many RTOSes and filesystem drivers already perform 29 | buffering on their side. Adding another layer of buffering is counter- 30 | productive (an issue known as "bufferbloat") and takes precious memory. 31 | Note that there still cases where buffering may be useful, so we may 32 | introduce optional buffering support at a later time. 33 | 34 | But in CPython, another important dichotomy is tied with "bufferedness" - 35 | it's whether a stream may incur short read/writes or not. A short read 36 | is when a user asks e.g. 10 bytes from a stream, but gets less, similarly 37 | for writes. In CPython, unbuffered streams are automatically short 38 | operation susceptible, while buffered are guarantee against them. The 39 | no short read/writes is an important trait, as it allows to develop 40 | more concise and efficient programs - something which is highly desirable 41 | for MicroPython. So, while MicroPython doesn't support buffered streams, 42 | it still provides for no-short-operations streams. Whether there will 43 | be short operations or not depends on each particular class' needs, but 44 | developers are strongly advised to favour no-short-operations behaviour 45 | for the reasons stated above. For example, MicroPython sockets are 46 | guaranteed to avoid short read/writes. Actually, at this time, there is 47 | no example of a short-operations stream class in the core, and one would 48 | be a port-specific class, where such a need is governed by hardware 49 | peculiarities. 50 | 51 | The no-short-operations behaviour gets tricky in case of non-blocking 52 | streams, blocking vs non-blocking behaviour being another CPython dichotomy, 53 | fully supported by MicroPython. Non-blocking streams never wait for 54 | data either to arrive or be written - they read/write whatever possible, 55 | or signal lack of data (or ability to write data). Clearly, this conflicts 56 | with "no-short-operations" policy, and indeed, a case of non-blocking 57 | buffered (and this no-short-ops) streams is convoluted in CPython - in 58 | some places, such combination is prohibited, in some it's undefined or 59 | just not documented, in some cases it raises verbose exceptions. The 60 | matter is much simpler in MicroPython: non-blocking stream are important 61 | for efficient asynchronous operations, so this property prevails on 62 | the "no-short-ops" one. So, while blocking streams will avoid short 63 | reads/writes whenever possible (the only case to get a short read is 64 | if end of file is reached, or in case of error (but errors don't 65 | return short data, but raise exceptions)), non-blocking streams may 66 | produce short data to avoid blocking the operation. 67 | 68 | The final dichotomy is binary vs text streams. MicroPython of course 69 | supports these, but while in CPython text streams are inherently 70 | buffered, they aren't in MicroPython. (Indeed, that's one of the cases 71 | for which we may introduce buffering support.) 72 | 73 | Note that for efficiency, MicroPython doesn't provide abstract base 74 | classes corresponding to the hierarchy above, and it's not possible 75 | to implement, or subclass, a stream class in pure Python. 76 | 77 | Functions 78 | --------- 79 | 80 | .. function:: open(name, mode='r', **kwargs) 81 | 82 | Open a file. Builtin ``open()`` function is aliased to this function. 83 | All ports (which provide access to file system) are required to support 84 | *mode* parameter, but support for other arguments vary by port. 85 | 86 | Classes 87 | ------- 88 | 89 | .. class:: StringIO([string]) 90 | .. class:: BytesIO([string]) 91 | 92 | In-memory file-like objects for input/output. `StringIO` is used for 93 | text-mode I/O (similar to a normal file opened with "t" modifier). 94 | `BytesIO` is used for binary-mode I/O (similar to a normal file 95 | opened with "b" modifier). Initial contents of file-like objects 96 | can be specified with *string* parameter (should be normal string 97 | for `StringIO` or bytes object for `BytesIO`). All the usual file 98 | methods like ``read()``, ``write()``, ``seek()``, ``flush()``, 99 | ``close()`` are available on these objects, and additionally, a 100 | following method: 101 | 102 | .. method:: getvalue() 103 | 104 | Get the current contents of the underlying buffer which holds data. 105 | 106 | .. class:: StringIO(alloc_size) 107 | :noindex: 108 | .. class:: BytesIO(alloc_size) 109 | :noindex: 110 | 111 | Create an empty `StringIO`/`BytesIO` object, preallocated to hold up 112 | to *alloc_size* number of bytes. That means that writing that amount 113 | of bytes won't lead to reallocation of the buffer, and thus won't hit 114 | out-of-memory situation or lead to memory fragmentation. These constructors 115 | are a MicroPython extension and are recommended for usage only in special 116 | cases and in system-level libraries, not for end-user applications. 117 | 118 | .. admonition:: Difference to CPython 119 | :class: attention 120 | 121 | These constructors are a MicroPython extension. 122 | -------------------------------------------------------------------------------- /docs/library/json.rst: -------------------------------------------------------------------------------- 1 | :mod:`json` -- JSON encoding and decoding 2 | ========================================= 3 | 4 | .. module:: json 5 | :synopsis: JSON encoding and decoding 6 | 7 | |see_cpython_module| :mod:`python:json`. 8 | 9 | This modules allows to convert between Python objects and the JSON 10 | data format. 11 | 12 | Functions 13 | --------- 14 | 15 | .. function:: dump(obj, stream, separators=None) 16 | 17 | Serialise *obj* to a JSON string, writing it to the given *stream*. 18 | 19 | If specified, separators should be an ``(item_separator, key_separator)`` 20 | tuple. The default is ``(', ', ': ')``. To get the most compact JSON 21 | representation, you should specify ``(',', ':')`` to eliminate whitespace. 22 | 23 | .. function:: dumps(obj, separators=None) 24 | 25 | Return *obj* represented as a JSON string. 26 | 27 | The arguments have the same meaning as in `dump`. 28 | 29 | .. function:: load(stream) 30 | 31 | Parse the given *stream*, interpreting it as a JSON string and 32 | deserialising the data to a Python object. The resulting object is 33 | returned. 34 | 35 | Parsing continues until end-of-file is encountered. 36 | A :exc:`ValueError` is raised if the data in *stream* is not correctly formed. 37 | 38 | .. function:: loads(str) 39 | 40 | Parse the JSON *str* and return an object. Raises :exc:`ValueError` if the 41 | string is not correctly formed. 42 | -------------------------------------------------------------------------------- /docs/library/machine.ADC.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: machine 2 | .. _machine.ADC: 3 | 4 | class ADC -- analog to digital conversion 5 | ========================================= 6 | 7 | The ADC class provides an interface to analog-to-digital converters, and 8 | represents a single endpoint that can sample a continuous voltage and 9 | convert it to a discretised value. 10 | 11 | For extra control over ADC sampling see :ref:`machine.ADCBlock `. 12 | 13 | Example usage:: 14 | 15 | from machine import ADC 16 | 17 | adc = ADC(pin) # create an ADC object acting on a pin 18 | val = adc.read_u16() # read a raw analog value in the range 0-65535 19 | val = adc.read_uv() # read an analog value in microvolts 20 | 21 | Constructors 22 | ------------ 23 | 24 | .. class:: ADC(id, *, sample_ns, atten) 25 | 26 | Access the ADC associated with a source identified by *id*. This 27 | *id* may be an integer (usually specifying a channel number), a 28 | :ref:`Pin ` object, or other value supported by the 29 | underlying machine. 30 | 31 | If additional keyword-arguments are given then they will configure 32 | various aspects of the ADC. If not given, these settings will take 33 | previous or default values. The settings are: 34 | 35 | - *sample_ns* is the sampling time in nanoseconds. 36 | 37 | - *atten* specifies the input attenuation. 38 | 39 | Methods 40 | ------- 41 | 42 | .. method:: ADC.init(*, sample_ns, atten) 43 | 44 | Apply the given settings to the ADC. Only those arguments that are 45 | specified will be changed. See the ADC constructor above for what the 46 | arguments are. 47 | 48 | .. method:: ADC.block() 49 | 50 | Return the :ref:`ADCBlock ` instance associated with 51 | this ADC object. 52 | 53 | This method only exists if the port supports the 54 | :ref:`ADCBlock ` class. 55 | 56 | .. method:: ADC.read_u16() 57 | 58 | Take an analog reading and return an integer in the range 0-65535. 59 | The return value represents the raw reading taken by the ADC, scaled 60 | such that the minimum value is 0 and the maximum value is 65535. 61 | 62 | .. method:: ADC.read_uv() 63 | 64 | Take an analog reading and return an integer value with units of 65 | microvolts. It is up to the particular port whether or not this value 66 | is calibrated, and how calibration is done. 67 | -------------------------------------------------------------------------------- /docs/library/machine.ADCBlock.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: machine 2 | .. _machine.ADCBlock: 3 | 4 | class ADCBlock -- control ADC peripherals 5 | ========================================= 6 | 7 | The ADCBlock class provides access to an ADC peripheral which has a 8 | number of channels that can be used to sample analog values. It allows 9 | finer control over configuration of :ref:`machine.ADC ` 10 | objects, which do the actual sampling. 11 | 12 | This class is not always available. 13 | 14 | Example usage:: 15 | 16 | from machine import ADCBlock 17 | 18 | block = ADCBlock(id, bits=12) # create an ADCBlock with 12-bit resolution 19 | adc = block.connect(4, pin) # connect channel 4 to the given pin 20 | val = adc.read_uv() # read an analog value 21 | 22 | Constructors 23 | ------------ 24 | 25 | .. class:: ADCBlock(id, *, bits) 26 | 27 | Access the ADC peripheral identified by *id*, which may be an integer 28 | or string. 29 | 30 | The *bits* argument, if given, sets the resolution in bits of the 31 | conversion process. If not specified then the previous or default 32 | resolution is used. 33 | 34 | Methods 35 | ------- 36 | 37 | .. method:: ADCBlock.init(*, bits) 38 | 39 | Configure the ADC peripheral. *bits* will set the resolution of the 40 | conversion process. 41 | 42 | .. method:: ADCBlock.connect(channel, *, ...) 43 | ADCBlock.connect(source, *, ...) 44 | ADCBlock.connect(channel, source, *, ...) 45 | 46 | Connect up a channel on the ADC peripheral so it is ready for sampling, 47 | and return an :ref:`ADC ` object that represents that connection. 48 | 49 | The *channel* argument must be an integer, and *source* must be an object 50 | (for example a :ref:`Pin `) which can be connected up for sampling. 51 | 52 | If only *channel* is given then it is configured for sampling. 53 | 54 | If only *source* is given then that object is connected to a default 55 | channel ready for sampling. 56 | 57 | If both *channel* and *source* are given then they are connected together 58 | and made ready for sampling. 59 | 60 | Any additional keyword arguments are used to configure the returned ADC object, 61 | via its :meth:`init ` method. 62 | -------------------------------------------------------------------------------- /docs/library/machine.PWM.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: machine 2 | .. _machine.PWM: 3 | 4 | class PWM -- pulse width modulation 5 | =================================== 6 | 7 | This class provides pulse width modulation output. 8 | 9 | Example usage:: 10 | 11 | from machine import PWM 12 | 13 | pwm = PWM(pin, freq=50, duty_u16=8192) # create a PWM object on a pin 14 | # and set freq and duty 15 | pwm.duty_u16(32768) # set duty to 50% 16 | 17 | # reinitialise with a period of 200us, duty of 5us 18 | pwm.init(freq=5000, duty_ns=5000) 19 | 20 | pwm.duty_ns(3000) # set pulse width to 3us 21 | 22 | pwm.deinit() 23 | 24 | Constructors 25 | ------------ 26 | 27 | .. class:: PWM(dest, *, freq, duty_u16, duty_ns, invert) 28 | 29 | Construct and return a new PWM object using the following parameters: 30 | 31 | - *dest* is the entity on which the PWM is output, which is usually a 32 | :ref:`machine.Pin ` object, but a port may allow other values, 33 | like integers. 34 | - *freq* should be an integer which sets the frequency in Hz for the 35 | PWM cycle. 36 | - *duty_u16* sets the duty cycle as a ratio ``duty_u16 / 65535``. 37 | - *duty_ns* sets the pulse width in nanoseconds. 38 | - *invert* inverts the respective output if the value is True 39 | 40 | Setting *freq* may affect other PWM objects if the objects share the same 41 | underlying PWM generator (this is hardware specific). 42 | Only one of *duty_u16* and *duty_ns* should be specified at a time. 43 | *invert* is not available at all ports. 44 | 45 | Methods 46 | ------- 47 | 48 | .. method:: PWM.init(*, freq, duty_u16, duty_ns) 49 | 50 | Modify settings for the PWM object. See the above constructor for details 51 | about the parameters. 52 | 53 | .. method:: PWM.deinit() 54 | 55 | Disable the PWM output. 56 | 57 | .. method:: PWM.freq([value]) 58 | 59 | Get or set the current frequency of the PWM output. 60 | 61 | With no arguments the frequency in Hz is returned. 62 | 63 | With a single *value* argument the frequency is set to that value in Hz. The 64 | method may raise a ``ValueError`` if the frequency is outside the valid range. 65 | 66 | .. method:: PWM.duty_u16([value]) 67 | 68 | Get or set the current duty cycle of the PWM output, as an unsigned 16-bit 69 | value in the range 0 to 65535 inclusive. 70 | 71 | With no arguments the duty cycle is returned. 72 | 73 | With a single *value* argument the duty cycle is set to that value, measured 74 | as the ratio ``value / 65535``. 75 | 76 | .. method:: PWM.duty_ns([value]) 77 | 78 | Get or set the current pulse width of the PWM output, as a value in nanoseconds. 79 | 80 | With no arguments the pulse width in nanoseconds is returned. 81 | 82 | With a single *value* argument the pulse width is set to that value. 83 | 84 | Limitations of PWM 85 | ------------------ 86 | 87 | * Not all frequencies can be generated with absolute accuracy due to 88 | the discrete nature of the computing hardware. Typically the PWM frequency 89 | is obtained by dividing some integer base frequency by an integer divider. 90 | For example, if the base frequency is 80MHz and the required PWM frequency is 91 | 300kHz the divider must be a non-integer number 80000000 / 300000 = 266.67. 92 | After rounding the divider is set to 267 and the PWM frequency will be 93 | 80000000 / 267 = 299625.5 Hz, not 300kHz. If the divider is set to 266 then 94 | the PWM frequency will be 80000000 / 266 = 300751.9 Hz, but again not 300kHz. 95 | 96 | Some ports like the RP2040 one use a fractional divider, which allow a finer 97 | granularity of the frequency at higher frequencies by switching the PWM 98 | pulse duration between two adjacent values, such that the resulting average 99 | frequency is more close to the intended one, at the cost of spectral purity. 100 | 101 | * The duty cycle has the same discrete nature and its absolute accuracy is not 102 | achievable. On most hardware platforms the duty will be applied at the next 103 | frequency period. Therefore, you should wait more than "1/frequency" before 104 | measuring the duty. 105 | 106 | * The frequency and the duty cycle resolution are usually interdependent. 107 | The higher the PWM frequency the lower the duty resolution which is available, 108 | and vice versa. For example, a 300kHz PWM frequency can have a duty cycle 109 | resolution of 8 bit, not 16-bit as may be expected. In this case, the lowest 110 | 8 bits of *duty_u16* are insignificant. So:: 111 | 112 | pwm=PWM(Pin(13), freq=300_000, duty_u16=2**16//2) 113 | 114 | and:: 115 | 116 | pwm=PWM(Pin(13), freq=300_000, duty_u16=2**16//2 + 255) 117 | 118 | will generate PWM with the same 50% duty cycle. 119 | -------------------------------------------------------------------------------- /docs/library/machine.RTC.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: machine 2 | .. _machine.RTC: 3 | 4 | class RTC -- real time clock 5 | ============================ 6 | 7 | The RTC is an independent clock that keeps track of the date 8 | and time. 9 | 10 | Example usage:: 11 | 12 | rtc = machine.RTC() 13 | rtc.datetime((2020, 1, 21, 2, 10, 32, 36, 0)) 14 | print(rtc.datetime()) 15 | 16 | 17 | Constructors 18 | ------------ 19 | 20 | .. class:: RTC(id=0, ...) 21 | 22 | Create an RTC object. See init for parameters of initialization. 23 | 24 | Methods 25 | ------- 26 | 27 | .. method:: RTC.datetime([datetimetuple]) 28 | 29 | Get or set the date and time of the RTC. 30 | 31 | With no arguments, this method returns an 8-tuple with the current 32 | date and time. With 1 argument (being an 8-tuple) it sets the date 33 | and time. 34 | 35 | The 8-tuple has the following format: 36 | 37 | (year, month, day, weekday, hours, minutes, seconds, subseconds) 38 | 39 | The meaning of the ``subseconds`` field is hardware dependent. 40 | 41 | .. method:: RTC.init(datetime) 42 | 43 | Initialise the RTC. Datetime is a tuple of the form: 44 | 45 | ``(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])`` 46 | 47 | .. method:: RTC.now() 48 | 49 | Get get the current datetime tuple. 50 | 51 | .. method:: RTC.deinit() 52 | 53 | Resets the RTC to the time of January 1, 2015 and starts running it again. 54 | 55 | .. method:: RTC.alarm(id, time, *, repeat=False) 56 | 57 | Set the RTC alarm. Time might be either a millisecond value to program the alarm to 58 | current time + time_in_ms in the future, or a datetimetuple. If the time passed is in 59 | milliseconds, repeat can be set to ``True`` to make the alarm periodic. 60 | 61 | .. method:: RTC.alarm_left(alarm_id=0) 62 | 63 | Get the number of milliseconds left before the alarm expires. 64 | 65 | .. method:: RTC.cancel(alarm_id=0) 66 | 67 | Cancel a running alarm. 68 | 69 | .. method:: RTC.irq(*, trigger, handler=None, wake=machine.IDLE) 70 | 71 | Create an irq object triggered by a real time clock alarm. 72 | 73 | - ``trigger`` must be ``RTC.ALARM0`` 74 | - ``handler`` is the function to be called when the callback is triggered. 75 | - ``wake`` specifies the sleep mode from where this interrupt can wake 76 | up the system. 77 | 78 | .. method:: RTC.memory([data]) 79 | 80 | ``RTC.memory(data)`` will write *data* to the RTC memory, where *data* is any 81 | object which supports the buffer protocol (including `bytes`, `bytearray`, 82 | `memoryview` and `array.array`). ``RTC.memory()`` reads RTC memory and returns 83 | a `bytes` object. 84 | 85 | Data written to RTC user memory is persistent across restarts, including 86 | `machine.soft_reset()` and `machine.deepsleep()`. 87 | 88 | The maximum length of RTC user memory is 2048 bytes by default on esp32, 89 | and 492 bytes on esp8266. 90 | 91 | Availability: esp32, esp8266 ports. 92 | 93 | Constants 94 | --------- 95 | 96 | .. data:: RTC.ALARM0 97 | 98 | irq trigger source 99 | -------------------------------------------------------------------------------- /docs/library/machine.SPI.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: machine 2 | .. _machine.SPI: 3 | 4 | class SPI -- a Serial Peripheral Interface bus protocol (controller side) 5 | ========================================================================= 6 | 7 | SPI is a synchronous serial protocol that is driven by a controller. At the 8 | physical level, a bus consists of 3 lines: SCK, MOSI, MISO. Multiple devices 9 | can share the same bus. Each device should have a separate, 4th signal, 10 | CS (Chip Select), to select a particular device on a bus with which 11 | communication takes place. Management of a CS signal should happen in 12 | user code (via machine.Pin class). 13 | 14 | Both hardware and software SPI implementations exist via the 15 | :ref:`machine.SPI ` and `machine.SoftSPI` classes. Hardware SPI uses underlying 16 | hardware support of the system to perform the reads/writes and is usually 17 | efficient and fast but may have restrictions on which pins can be used. 18 | Software SPI is implemented by bit-banging and can be used on any pin but 19 | is not as efficient. These classes have the same methods available and 20 | differ primarily in the way they are constructed. 21 | 22 | Example usage:: 23 | 24 | from machine import SPI, Pin 25 | 26 | spi = SPI(0, baudrate=400000) # Create SPI peripheral 0 at frequency of 400kHz. 27 | # Depending on the use case, extra parameters may be required 28 | # to select the bus characteristics and/or pins to use. 29 | cs = Pin(4, mode=Pin.OUT, value=1) # Create chip-select on pin 4. 30 | 31 | try: 32 | cs(0) # Select peripheral. 33 | spi.write(b"12345678") # Write 8 bytes, and don't care about received data. 34 | finally: 35 | cs(1) # Deselect peripheral. 36 | 37 | try: 38 | cs(0) # Select peripheral. 39 | rxdata = spi.read(8, 0x42) # Read 8 bytes while writing 0x42 for each byte. 40 | finally: 41 | cs(1) # Deselect peripheral. 42 | 43 | rxdata = bytearray(8) 44 | try: 45 | cs(0) # Select peripheral. 46 | spi.readinto(rxdata, 0x42) # Read 8 bytes inplace while writing 0x42 for each byte. 47 | finally: 48 | cs(1) # Deselect peripheral. 49 | 50 | txdata = b"12345678" 51 | rxdata = bytearray(len(txdata)) 52 | try: 53 | cs(0) # Select peripheral. 54 | spi.write_readinto(txdata, rxdata) # Simultaneously write and read bytes. 55 | finally: 56 | cs(1) # Deselect peripheral. 57 | 58 | Constructors 59 | ------------ 60 | 61 | .. class:: SPI(id, ...) 62 | 63 | Construct an SPI object on the given bus, *id*. Values of *id* depend 64 | on a particular port and its hardware. Values 0, 1, etc. are commonly used 65 | to select hardware SPI block #0, #1, etc. 66 | 67 | With no additional parameters, the SPI object is created but not 68 | initialised (it has the settings from the last initialisation of 69 | the bus, if any). If extra arguments are given, the bus is initialised. 70 | See ``init`` for parameters of initialisation. 71 | 72 | .. _machine.SoftSPI: 73 | .. class:: SoftSPI(baudrate=500000, *, polarity=0, phase=0, bits=8, firstbit=MSB, sck=None, mosi=None, miso=None) 74 | 75 | Construct a new software SPI object. Additional parameters must be 76 | given, usually at least *sck*, *mosi* and *miso*, and these are used 77 | to initialise the bus. See `SPI.init` for a description of the parameters. 78 | 79 | Methods 80 | ------- 81 | 82 | .. method:: SPI.init(baudrate=1000000, *, polarity=0, phase=0, bits=8, firstbit=SPI.MSB, sck=None, mosi=None, miso=None, pins=(SCK, MOSI, MISO)) 83 | 84 | Initialise the SPI bus with the given parameters: 85 | 86 | - ``baudrate`` is the SCK clock rate. 87 | - ``polarity`` can be 0 or 1, and is the level the idle clock line sits at. 88 | - ``phase`` can be 0 or 1 to sample data on the first or second clock edge 89 | respectively. 90 | - ``bits`` is the width in bits of each transfer. Only 8 is guaranteed to be supported by all hardware. 91 | - ``firstbit`` can be ``SPI.MSB`` or ``SPI.LSB``. 92 | - ``sck``, ``mosi``, ``miso`` are pins (machine.Pin) objects to use for bus signals. For most 93 | hardware SPI blocks (as selected by ``id`` parameter to the constructor), pins are fixed 94 | and cannot be changed. In some cases, hardware blocks allow 2-3 alternative pin sets for 95 | a hardware SPI block. Arbitrary pin assignments are possible only for a bitbanging SPI driver 96 | (``id`` = -1). 97 | - ``pins`` - WiPy port doesn't ``sck``, ``mosi``, ``miso`` arguments, and instead allows to 98 | specify them as a tuple of ``pins`` parameter. 99 | 100 | In the case of hardware SPI the actual clock frequency may be lower than the 101 | requested baudrate. This is dependent on the platform hardware. The actual 102 | rate may be determined by printing the SPI object. 103 | 104 | .. method:: SPI.deinit() 105 | 106 | Turn off the SPI bus. 107 | 108 | .. method:: SPI.read(nbytes, write=0x00) 109 | 110 | Read a number of bytes specified by ``nbytes`` while continuously writing 111 | the single byte given by ``write``. 112 | Returns a ``bytes`` object with the data that was read. 113 | 114 | .. method:: SPI.readinto(buf, write=0x00) 115 | 116 | Read into the buffer specified by ``buf`` while continuously writing the 117 | single byte given by ``write``. 118 | Returns ``None``. 119 | 120 | Note: on WiPy this function returns the number of bytes read. 121 | 122 | .. method:: SPI.write(buf) 123 | 124 | Write the bytes contained in ``buf``. 125 | Returns ``None``. 126 | 127 | Note: on WiPy this function returns the number of bytes written. 128 | 129 | .. method:: SPI.write_readinto(write_buf, read_buf) 130 | 131 | Write the bytes from ``write_buf`` while reading into ``read_buf``. The 132 | buffers can be the same or different, but both buffers must have the 133 | same length. 134 | Returns ``None``. 135 | 136 | Note: on WiPy this function returns the number of bytes written. 137 | 138 | Constants 139 | --------- 140 | 141 | .. data:: SPI.CONTROLLER 142 | 143 | for initialising the SPI bus to controller; this is only used for the WiPy 144 | 145 | .. data:: SPI.MSB 146 | SoftSPI.MSB 147 | 148 | set the first bit to be the most significant bit 149 | 150 | .. data:: SPI.LSB 151 | SoftSPI.LSB 152 | 153 | set the first bit to be the least significant bit 154 | -------------------------------------------------------------------------------- /docs/library/machine.Signal.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: machine 2 | .. _machine.Signal: 3 | 4 | class Signal -- control and sense external I/O devices 5 | ====================================================== 6 | 7 | The Signal class is a simple extension of the `Pin` class. Unlike Pin, which 8 | can be only in "absolute" 0 and 1 states, a Signal can be in "asserted" 9 | (on) or "deasserted" (off) states, while being inverted (active-low) or 10 | not. In other words, it adds logical inversion support to Pin functionality. 11 | While this may seem a simple addition, it is exactly what is needed to 12 | support wide array of simple digital devices in a way portable across 13 | different boards, which is one of the major MicroPython goals. Regardless 14 | of whether different users have an active-high or active-low LED, a normally 15 | open or normally closed relay - you can develop a single, nicely looking 16 | application which works with each of them, and capture hardware 17 | configuration differences in few lines in the config file of your app. 18 | 19 | Example:: 20 | 21 | from machine import Pin, Signal 22 | 23 | # Suppose you have an active-high LED on pin 0 24 | led1_pin = Pin(0, Pin.OUT) 25 | # ... and active-low LED on pin 1 26 | led2_pin = Pin(1, Pin.OUT) 27 | 28 | # Now to light up both of them using Pin class, you'll need to set 29 | # them to different values 30 | led1_pin.value(1) 31 | led2_pin.value(0) 32 | 33 | # Signal class allows to abstract away active-high/active-low 34 | # difference 35 | led1 = Signal(led1_pin, invert=False) 36 | led2 = Signal(led2_pin, invert=True) 37 | 38 | # Now lighting up them looks the same 39 | led1.value(1) 40 | led2.value(1) 41 | 42 | # Even better: 43 | led1.on() 44 | led2.on() 45 | 46 | Following is the guide when Signal vs Pin should be used: 47 | 48 | * Use Signal: If you want to control a simple on/off (including software 49 | PWM!) devices like LEDs, multi-segment indicators, relays, buzzers, or 50 | read simple binary sensors, like normally open or normally closed buttons, 51 | pulled high or low, Reed switches, moisture/flame detectors, etc. etc. 52 | Summing up, if you have a real physical device/sensor requiring GPIO 53 | access, you likely should use a Signal. 54 | 55 | * Use Pin: If you implement a higher-level protocol or bus to communicate 56 | with more complex devices. 57 | 58 | The split between Pin and Signal come from the use cases above and the 59 | architecture of MicroPython: Pin offers the lowest overhead, which may 60 | be important when bit-banging protocols. But Signal adds additional 61 | flexibility on top of Pin, at the cost of minor overhead (much smaller 62 | than if you implemented active-high vs active-low device differences in 63 | Python manually!). Also, Pin is a low-level object which needs to be 64 | implemented for each support board, while Signal is a high-level object 65 | which comes for free once Pin is implemented. 66 | 67 | If in doubt, give the Signal a try! Once again, it is offered to save 68 | developers from the need to handle unexciting differences like active-low 69 | vs active-high signals, and allow other users to share and enjoy your 70 | application, instead of being frustrated by the fact that it doesn't 71 | work for them simply because their LEDs or relays are wired in a slightly 72 | different way. 73 | 74 | Constructors 75 | ------------ 76 | 77 | .. class:: Signal(pin_obj, invert=False) 78 | Signal(pin_arguments..., *, invert=False) 79 | 80 | Create a Signal object. There're two ways to create it: 81 | 82 | * By wrapping existing Pin object - universal method which works for 83 | any board. 84 | * By passing required Pin parameters directly to Signal constructor, 85 | skipping the need to create intermediate Pin object. Available on 86 | many, but not all boards. 87 | 88 | The arguments are: 89 | 90 | - ``pin_obj`` is existing Pin object. 91 | 92 | - ``pin_arguments`` are the same arguments as can be passed to Pin constructor. 93 | 94 | - ``invert`` - if True, the signal will be inverted (active low). 95 | 96 | Methods 97 | ------- 98 | 99 | .. method:: Signal.value([x]) 100 | 101 | This method allows to set and get the value of the signal, depending on whether 102 | the argument ``x`` is supplied or not. 103 | 104 | If the argument is omitted then this method gets the signal level, 1 meaning 105 | signal is asserted (active) and 0 - signal inactive. 106 | 107 | If the argument is supplied then this method sets the signal level. The 108 | argument ``x`` can be anything that converts to a boolean. If it converts 109 | to ``True``, the signal is active, otherwise it is inactive. 110 | 111 | Correspondence between signal being active and actual logic level on the 112 | underlying pin depends on whether signal is inverted (active-low) or not. 113 | For non-inverted signal, active status corresponds to logical 1, inactive - 114 | to logical 0. For inverted/active-low signal, active status corresponds 115 | to logical 0, while inactive - to logical 1. 116 | 117 | .. method:: Signal.on() 118 | 119 | Activate signal. 120 | 121 | .. method:: Signal.off() 122 | 123 | Deactivate signal. 124 | -------------------------------------------------------------------------------- /docs/library/machine.Timer.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: machine 2 | .. _machine.Timer: 3 | 4 | class Timer -- control hardware timers 5 | ====================================== 6 | 7 | Hardware timers deal with timing of periods and events. Timers are perhaps 8 | the most flexible and heterogeneous kind of hardware in MCUs and SoCs, 9 | differently greatly from a model to a model. MicroPython's Timer class 10 | defines a baseline operation of executing a callback with a given period 11 | (or once after some delay), and allow specific boards to define more 12 | non-standard behaviour (which thus won't be portable to other boards). 13 | 14 | See discussion of :ref:`important constraints ` on 15 | Timer callbacks. 16 | 17 | .. note:: 18 | 19 | Memory can't be allocated inside irq handlers (an interrupt) and so 20 | exceptions raised within a handler don't give much information. See 21 | :func:`micropython.alloc_emergency_exception_buf` for how to get around this 22 | limitation. 23 | 24 | Constructors 25 | ------------ 26 | 27 | .. class:: Timer(id, /, ...) 28 | 29 | Construct a new timer object of the given ``id``. ``id`` of -1 constructs a 30 | virtual timer (if supported by a board). 31 | ``id`` shall not be passed as a keyword argument. 32 | 33 | See ``init`` for parameters of initialisation. 34 | 35 | Methods 36 | ------- 37 | 38 | .. method:: Timer.init(*, mode=Timer.PERIODIC, freq=-1, period=-1, callback=None) 39 | 40 | Initialise the timer. Example:: 41 | 42 | def mycallback(t): 43 | pass 44 | 45 | # periodic at 1kHz 46 | tim.init(mode=Timer.PERIODIC, freq=1000, callback=mycallback) 47 | 48 | # periodic with 100ms period 49 | tim.init(period=100, callback=mycallback) 50 | 51 | # one shot firing after 1000ms 52 | tim.init(mode=Timer.ONE_SHOT, period=1000, callback=mycallback) 53 | 54 | Keyword arguments: 55 | 56 | - ``mode`` can be one of: 57 | 58 | - ``Timer.ONE_SHOT`` - The timer runs once until the configured 59 | period of the channel expires. 60 | - ``Timer.PERIODIC`` - The timer runs periodically at the configured 61 | frequency of the channel. 62 | 63 | - ``freq`` - The timer frequency, in units of Hz. The upper bound of 64 | the frequency is dependent on the port. When both the ``freq`` and 65 | ``period`` arguments are given, ``freq`` has a higher priority and 66 | ``period`` is ignored. 67 | 68 | - ``period`` - The timer period, in milliseconds. 69 | 70 | - ``callback`` - The callable to call upon expiration of the timer period. 71 | The callback must take one argument, which is passed the Timer object. 72 | The ``callback`` argument shall be specified. Otherwise an exception 73 | will occur upon timer expiration: 74 | ``TypeError: 'NoneType' object isn't callable`` 75 | 76 | .. method:: Timer.deinit() 77 | 78 | Deinitialises the timer. Stops the timer, and disables the timer peripheral. 79 | 80 | Constants 81 | --------- 82 | 83 | .. data:: Timer.ONE_SHOT 84 | Timer.PERIODIC 85 | 86 | Timer operating mode. 87 | -------------------------------------------------------------------------------- /docs/library/machine.WDT.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: machine 2 | .. _machine.WDT: 3 | 4 | class WDT -- watchdog timer 5 | =========================== 6 | 7 | The WDT is used to restart the system when the application crashes and ends 8 | up into a non recoverable state. Once started it cannot be stopped or 9 | reconfigured in any way. After enabling, the application must "feed" the 10 | watchdog periodically to prevent it from expiring and resetting the system. 11 | 12 | Example usage:: 13 | 14 | from machine import WDT 15 | wdt = WDT(timeout=2000) # enable it with a timeout of 2s 16 | wdt.feed() 17 | 18 | Availability of this class: pyboard, WiPy, esp8266, esp32, rp2040, mimxrt. 19 | 20 | Constructors 21 | ------------ 22 | 23 | .. class:: WDT(id=0, timeout=5000) 24 | 25 | Create a WDT object and start it. The timeout must be given in milliseconds. 26 | Once it is running the timeout cannot be changed and the WDT cannot be stopped either. 27 | 28 | Notes: On the esp8266 a timeout cannot be specified, it is determined by the underlying system. 29 | On rp2040 devices, the maximum timeout is 8388 ms. 30 | 31 | Methods 32 | ------- 33 | 34 | .. method:: WDT.feed() 35 | 36 | Feed the WDT to prevent it from resetting the system. The application 37 | should place this call in a sensible place ensuring that the WDT is 38 | only fed after verifying that everything is functioning correctly. 39 | -------------------------------------------------------------------------------- /docs/library/math.rst: -------------------------------------------------------------------------------- 1 | :mod:`math` -- mathematical functions 2 | ===================================== 3 | 4 | .. module:: math 5 | :synopsis: mathematical functions 6 | 7 | |see_cpython_module| :mod:`python:math`. 8 | 9 | The ``math`` module provides some basic mathematical functions for 10 | working with floating-point numbers. 11 | 12 | *Note:* On the pyboard, floating-point numbers have 32-bit precision. 13 | 14 | Availability: not available on WiPy. Floating point support required 15 | for this module. 16 | 17 | Functions 18 | --------- 19 | 20 | .. function:: acos(x) 21 | 22 | Return the inverse cosine of ``x``. 23 | 24 | .. function:: acosh(x) 25 | 26 | Return the inverse hyperbolic cosine of ``x``. 27 | 28 | .. function:: asin(x) 29 | 30 | Return the inverse sine of ``x``. 31 | 32 | .. function:: asinh(x) 33 | 34 | Return the inverse hyperbolic sine of ``x``. 35 | 36 | .. function:: atan(x) 37 | 38 | Return the inverse tangent of ``x``. 39 | 40 | .. function:: atan2(y, x) 41 | 42 | Return the principal value of the inverse tangent of ``y/x``. 43 | 44 | .. function:: atanh(x) 45 | 46 | Return the inverse hyperbolic tangent of ``x``. 47 | 48 | .. function:: ceil(x) 49 | 50 | Return an integer, being ``x`` rounded towards positive infinity. 51 | 52 | .. function:: copysign(x, y) 53 | 54 | Return ``x`` with the sign of ``y``. 55 | 56 | .. function:: cos(x) 57 | 58 | Return the cosine of ``x``. 59 | 60 | .. function:: cosh(x) 61 | 62 | Return the hyperbolic cosine of ``x``. 63 | 64 | .. function:: degrees(x) 65 | 66 | Return radians ``x`` converted to degrees. 67 | 68 | .. function:: erf(x) 69 | 70 | Return the error function of ``x``. 71 | 72 | .. function:: erfc(x) 73 | 74 | Return the complementary error function of ``x``. 75 | 76 | .. function:: exp(x) 77 | 78 | Return the exponential of ``x``. 79 | 80 | .. function:: expm1(x) 81 | 82 | Return ``exp(x) - 1``. 83 | 84 | .. function:: fabs(x) 85 | 86 | Return the absolute value of ``x``. 87 | 88 | .. function:: floor(x) 89 | 90 | Return an integer, being ``x`` rounded towards negative infinity. 91 | 92 | .. function:: fmod(x, y) 93 | 94 | Return the remainder of ``x/y``. 95 | 96 | .. function:: frexp(x) 97 | 98 | Decomposes a floating-point number into its mantissa and exponent. 99 | The returned value is the tuple ``(m, e)`` such that ``x == m * 2**e`` 100 | exactly. If ``x == 0`` then the function returns ``(0.0, 0)``, otherwise 101 | the relation ``0.5 <= abs(m) < 1`` holds. 102 | 103 | .. function:: gamma(x) 104 | 105 | Return the gamma function of ``x``. 106 | 107 | .. function:: isfinite(x) 108 | 109 | Return ``True`` if ``x`` is finite. 110 | 111 | .. function:: isinf(x) 112 | 113 | Return ``True`` if ``x`` is infinite. 114 | 115 | .. function:: isnan(x) 116 | 117 | Return ``True`` if ``x`` is not-a-number 118 | 119 | .. function:: ldexp(x, exp) 120 | 121 | Return ``x * (2**exp)``. 122 | 123 | .. function:: lgamma(x) 124 | 125 | Return the natural logarithm of the gamma function of ``x``. 126 | 127 | .. function:: log(x) 128 | 129 | Return the natural logarithm of ``x``. 130 | 131 | .. function:: log10(x) 132 | 133 | Return the base-10 logarithm of ``x``. 134 | 135 | .. function:: log2(x) 136 | 137 | Return the base-2 logarithm of ``x``. 138 | 139 | .. function:: modf(x) 140 | 141 | Return a tuple of two floats, being the fractional and integral parts of 142 | ``x``. Both return values have the same sign as ``x``. 143 | 144 | .. function:: pow(x, y) 145 | 146 | Returns ``x`` to the power of ``y``. 147 | 148 | .. function:: radians(x) 149 | 150 | Return degrees ``x`` converted to radians. 151 | 152 | .. function:: sin(x) 153 | 154 | Return the sine of ``x``. 155 | 156 | .. function:: sinh(x) 157 | 158 | Return the hyperbolic sine of ``x``. 159 | 160 | .. function:: sqrt(x) 161 | 162 | Return the square root of ``x``. 163 | 164 | .. function:: tan(x) 165 | 166 | Return the tangent of ``x``. 167 | 168 | .. function:: tanh(x) 169 | 170 | Return the hyperbolic tangent of ``x``. 171 | 172 | .. function:: trunc(x) 173 | 174 | Return an integer, being ``x`` rounded towards 0. 175 | 176 | Constants 177 | --------- 178 | 179 | .. data:: e 180 | 181 | base of the natural logarithm 182 | 183 | .. data:: pi 184 | 185 | the ratio of a circle's circumference to its diameter 186 | -------------------------------------------------------------------------------- /docs/library/micropython.rst: -------------------------------------------------------------------------------- 1 | :mod:`micropython` -- access and control MicroPython internals 2 | ============================================================== 3 | 4 | .. module:: micropython 5 | :synopsis: access and control MicroPython internals 6 | 7 | Functions 8 | --------- 9 | 10 | .. function:: const(expr) 11 | 12 | Used to declare that the expression is a constant so that the compiler can 13 | optimise it. The use of this function should be as follows:: 14 | 15 | from micropython import const 16 | 17 | CONST_X = const(123) 18 | CONST_Y = const(2 * CONST_X + 1) 19 | 20 | Constants declared this way are still accessible as global variables from 21 | outside the module they are declared in. On the other hand, if a constant 22 | begins with an underscore then it is hidden, it is not available as a global 23 | variable, and does not take up any memory during execution. 24 | 25 | This `const` function is recognised directly by the MicroPython parser and is 26 | provided as part of the :mod:`micropython` module mainly so that scripts can be 27 | written which run under both CPython and MicroPython, by following the above 28 | pattern. 29 | 30 | .. function:: opt_level([level]) 31 | 32 | If *level* is given then this function sets the optimisation level for subsequent 33 | compilation of scripts, and returns ``None``. Otherwise it returns the current 34 | optimisation level. 35 | 36 | The optimisation level controls the following compilation features: 37 | 38 | - Assertions: at level 0 assertion statements are enabled and compiled into the 39 | bytecode; at levels 1 and higher assertions are not compiled. 40 | - Built-in ``__debug__`` variable: at level 0 this variable expands to ``True``; 41 | at levels 1 and higher it expands to ``False``. 42 | - Source-code line numbers: at levels 0, 1 and 2 source-code line number are 43 | stored along with the bytecode so that exceptions can report the line number 44 | they occurred at; at levels 3 and higher line numbers are not stored. 45 | 46 | The default optimisation level is usually level 0. 47 | 48 | .. function:: alloc_emergency_exception_buf(size) 49 | 50 | Allocate *size* bytes of RAM for the emergency exception buffer (a good 51 | size is around 100 bytes). The buffer is used to create exceptions in cases 52 | when normal RAM allocation would fail (eg within an interrupt handler) and 53 | therefore give useful traceback information in these situations. 54 | 55 | A good way to use this function is to put it at the start of your main script 56 | (eg ``boot.py`` or ``main.py``) and then the emergency exception buffer will be active 57 | for all the code following it. 58 | 59 | .. function:: mem_info([verbose]) 60 | 61 | Print information about currently used memory. If the *verbose* argument 62 | is given then extra information is printed. 63 | 64 | The information that is printed is implementation dependent, but currently 65 | includes the amount of stack and heap used. In verbose mode it prints out 66 | the entire heap indicating which blocks are used and which are free. 67 | 68 | .. function:: qstr_info([verbose]) 69 | 70 | Print information about currently interned strings. If the *verbose* 71 | argument is given then extra information is printed. 72 | 73 | The information that is printed is implementation dependent, but currently 74 | includes the number of interned strings and the amount of RAM they use. In 75 | verbose mode it prints out the names of all RAM-interned strings. 76 | 77 | .. function:: stack_use() 78 | 79 | Return an integer representing the current amount of stack that is being 80 | used. The absolute value of this is not particularly useful, rather it 81 | should be used to compute differences in stack usage at different points. 82 | 83 | .. function:: heap_lock() 84 | .. function:: heap_unlock() 85 | .. function:: heap_locked() 86 | 87 | Lock or unlock the heap. When locked no memory allocation can occur and a 88 | `MemoryError` will be raised if any heap allocation is attempted. 89 | `heap_locked()` returns a true value if the heap is currently locked. 90 | 91 | These functions can be nested, ie `heap_lock()` can be called multiple times 92 | in a row and the lock-depth will increase, and then `heap_unlock()` must be 93 | called the same number of times to make the heap available again. 94 | 95 | Both `heap_unlock()` and `heap_locked()` return the current lock depth 96 | (after unlocking for the former) as a non-negative integer, with 0 meaning 97 | the heap is not locked. 98 | 99 | If the REPL becomes active with the heap locked then it will be forcefully 100 | unlocked. 101 | 102 | Note: `heap_locked()` is not enabled on most ports by default, 103 | requires ``MICROPY_PY_MICROPYTHON_HEAP_LOCKED``. 104 | 105 | .. function:: kbd_intr(chr) 106 | 107 | Set the character that will raise a `KeyboardInterrupt` exception. By 108 | default this is set to 3 during script execution, corresponding to Ctrl-C. 109 | Passing -1 to this function will disable capture of Ctrl-C, and passing 3 110 | will restore it. 111 | 112 | This function can be used to prevent the capturing of Ctrl-C on the 113 | incoming stream of characters that is usually used for the REPL, in case 114 | that stream is used for other purposes. 115 | 116 | .. function:: schedule(func, arg) 117 | 118 | Schedule the function *func* to be executed "very soon". The function 119 | is passed the value *arg* as its single argument. "Very soon" means that 120 | the MicroPython runtime will do its best to execute the function at the 121 | earliest possible time, given that it is also trying to be efficient, and 122 | that the following conditions hold: 123 | 124 | - A scheduled function will never preempt another scheduled function. 125 | - Scheduled functions are always executed "between opcodes" which means 126 | that all fundamental Python operations (such as appending to a list) 127 | are guaranteed to be atomic. 128 | - A given port may define "critical regions" within which scheduled 129 | functions will never be executed. Functions may be scheduled within 130 | a critical region but they will not be executed until that region 131 | is exited. An example of a critical region is a preempting interrupt 132 | handler (an IRQ). 133 | 134 | A use for this function is to schedule a callback from a preempting IRQ. 135 | Such an IRQ puts restrictions on the code that runs in the IRQ (for example 136 | the heap may be locked) and scheduling a function to call later will lift 137 | those restrictions. 138 | 139 | Note: If `schedule()` is called from a preempting IRQ, when memory 140 | allocation is not allowed and the callback to be passed to `schedule()` is 141 | a bound method, passing this directly will fail. This is because creating a 142 | reference to a bound method causes memory allocation. A solution is to 143 | create a reference to the method in the class constructor and to pass that 144 | reference to `schedule()`. This is discussed in detail here 145 | :ref:`reference documentation ` under "Creation of Python 146 | objects". 147 | 148 | There is a finite queue to hold the scheduled functions and `schedule()` 149 | will raise a `RuntimeError` if the queue is full. 150 | -------------------------------------------------------------------------------- /docs/library/neopixel.rst: -------------------------------------------------------------------------------- 1 | :mod:`neopixel` --- control of WS2812 / NeoPixel LEDs 2 | ===================================================== 3 | 4 | .. module:: neopixel 5 | :synopsis: control of WS2812 / NeoPixel LEDs 6 | 7 | This module provides a driver for WS2818 / NeoPixel LEDs. 8 | 9 | .. note:: This module is only included by default on the ESP8266, ESP32 and RP2 10 | ports. On STM32 / Pyboard and others, you can either install the 11 | ``neopixel`` package using :term:`mip`, or you can download the module 12 | directly from :term:`micropython-lib` and copy it to the filesystem. 13 | 14 | class NeoPixel 15 | -------------- 16 | 17 | This class stores pixel data for a WS2812 LED strip connected to a pin. The 18 | application should set pixel data and then call :meth:`NeoPixel.write` 19 | when it is ready to update the strip. 20 | 21 | For example:: 22 | 23 | import neopixel 24 | 25 | # 32 LED strip connected to X8. 26 | p = machine.Pin.board.X8 27 | n = neopixel.NeoPixel(p, 32) 28 | 29 | # Draw a red gradient. 30 | for i in range(32): 31 | n[i] = (i * 8, 0, 0) 32 | 33 | # Update the strip. 34 | n.write() 35 | 36 | Constructors 37 | ------------ 38 | 39 | .. class:: NeoPixel(pin, n, *, bpp=3, timing=1) 40 | 41 | Construct an NeoPixel object. The parameters are: 42 | 43 | - *pin* is a machine.Pin instance. 44 | - *n* is the number of LEDs in the strip. 45 | - *bpp* is 3 for RGB LEDs, and 4 for RGBW LEDs. 46 | - *timing* is 0 for 400KHz, and 1 for 800kHz LEDs (most are 800kHz). 47 | 48 | Pixel access methods 49 | -------------------- 50 | 51 | .. method:: NeoPixel.fill(pixel) 52 | 53 | Sets the value of all pixels to the specified *pixel* value (i.e. an 54 | RGB/RGBW tuple). 55 | 56 | .. method:: NeoPixel.__len__() 57 | 58 | Returns the number of LEDs in the strip. 59 | 60 | .. method:: NeoPixel.__setitem__(index, val) 61 | 62 | Set the pixel at *index* to the value, which is an RGB/RGBW tuple. 63 | 64 | .. method:: NeoPixel.__getitem__(index) 65 | 66 | Returns the pixel at *index* as an RGB/RGBW tuple. 67 | 68 | Output methods 69 | -------------- 70 | 71 | .. method:: NeoPixel.write() 72 | 73 | Writes the current pixel data to the strip. 74 | -------------------------------------------------------------------------------- /docs/library/network.WLAN.rst: -------------------------------------------------------------------------------- 1 | .. currentmodule:: network 2 | .. _network.WLAN: 3 | 4 | class WLAN -- control built-in WiFi interfaces 5 | ============================================== 6 | 7 | This class provides a driver for WiFi network processors. Example usage:: 8 | 9 | import network 10 | # enable station interface and connect to WiFi access point 11 | nic = network.WLAN(network.STA_IF) 12 | nic.active(True) 13 | nic.connect('your-ssid', 'your-key') 14 | # now use sockets as usual 15 | 16 | Constructors 17 | ------------ 18 | .. class:: WLAN(interface_id) 19 | 20 | Create a WLAN network interface object. Supported interfaces are 21 | ``network.STA_IF`` (station aka client, connects to upstream WiFi access 22 | points) and ``network.AP_IF`` (access point, allows other WiFi clients to 23 | connect). Availability of the methods below depends on interface type. 24 | For example, only STA interface may `WLAN.connect()` to an access point. 25 | 26 | Methods 27 | ------- 28 | 29 | .. method:: WLAN.active([is_active]) 30 | 31 | Activate ("up") or deactivate ("down") network interface, if boolean 32 | argument is passed. Otherwise, query current state if no argument is 33 | provided. Most other methods require active interface. 34 | 35 | .. method:: WLAN.connect(ssid=None, key=None, *, bssid=None) 36 | 37 | Connect to the specified wireless network, using the specified key. 38 | If *bssid* is given then the connection will be restricted to the 39 | access-point with that MAC address (the *ssid* must also be specified 40 | in this case). 41 | 42 | .. method:: WLAN.disconnect() 43 | 44 | Disconnect from the currently connected wireless network. 45 | 46 | .. method:: WLAN.scan() 47 | 48 | Scan for the available wireless networks. 49 | Hidden networks -- where the SSID is not broadcast -- will also be scanned 50 | if the WLAN interface allows it. 51 | 52 | Scanning is only possible on STA interface. Returns list of tuples with 53 | the information about WiFi access points: 54 | 55 | (ssid, bssid, channel, RSSI, security, hidden) 56 | 57 | *bssid* is hardware address of an access point, in binary form, returned as 58 | bytes object. You can use `binascii.hexlify()` to convert it to ASCII form. 59 | 60 | There are five values for security: 61 | 62 | * 0 -- open 63 | * 1 -- WEP 64 | * 2 -- WPA-PSK 65 | * 3 -- WPA2-PSK 66 | * 4 -- WPA/WPA2-PSK 67 | 68 | and two for hidden: 69 | 70 | * 0 -- visible 71 | * 1 -- hidden 72 | 73 | .. method:: WLAN.status([param]) 74 | 75 | Return the current status of the wireless connection. 76 | 77 | When called with no argument the return value describes the network link status. 78 | The possible statuses are defined as constants: 79 | 80 | * ``STAT_IDLE`` -- no connection and no activity, 81 | * ``STAT_CONNECTING`` -- connecting in progress, 82 | * ``STAT_WRONG_PASSWORD`` -- failed due to incorrect password, 83 | * ``STAT_NO_AP_FOUND`` -- failed because no access point replied, 84 | * ``STAT_CONNECT_FAIL`` -- failed due to other problems, 85 | * ``STAT_GOT_IP`` -- connection successful. 86 | 87 | When called with one argument *param* should be a string naming the status 88 | parameter to retrieve. Supported parameters in WiFI STA mode are: ``'rssi'``. 89 | 90 | .. method:: WLAN.isconnected() 91 | 92 | In case of STA mode, returns ``True`` if connected to a WiFi access 93 | point and has a valid IP address. In AP mode returns ``True`` when a 94 | station is connected. Returns ``False`` otherwise. 95 | 96 | .. method:: WLAN.ifconfig([(ip, subnet, gateway, dns)]) 97 | 98 | Get/set IP-level network interface parameters: IP address, subnet mask, 99 | gateway and DNS server. When called with no arguments, this method returns 100 | a 4-tuple with the above information. To set the above values, pass a 101 | 4-tuple with the required information. For example:: 102 | 103 | nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8')) 104 | 105 | .. method:: WLAN.config('param') 106 | WLAN.config(param=value, ...) 107 | 108 | Get or set general network interface parameters. These methods allow to work 109 | with additional parameters beyond standard IP configuration (as dealt with by 110 | `WLAN.ifconfig()`). These include network-specific and hardware-specific 111 | parameters. For setting parameters, keyword argument syntax should be used, 112 | multiple parameters can be set at once. For querying, parameters name should 113 | be quoted as a string, and only one parameter can be queries at time:: 114 | 115 | # Set WiFi access point name (formally known as SSID) and WiFi channel 116 | ap.config(ssid='My AP', channel=11) 117 | # Query params one by one 118 | print(ap.config('ssid')) 119 | print(ap.config('channel')) 120 | 121 | Following are commonly supported parameters (availability of a specific parameter 122 | depends on network technology type, driver, and :term:`MicroPython port`). 123 | 124 | ============= =========== 125 | Parameter Description 126 | ============= =========== 127 | mac MAC address (bytes) 128 | ssid WiFi access point name (string) 129 | channel WiFi channel (integer) 130 | hidden Whether SSID is hidden (boolean) 131 | security Security protocol supported (enumeration, see module constants) 132 | key Access key (string) 133 | hostname The hostname that will be sent to DHCP (STA interfaces) and mDNS (if supported, both STA and AP). (Deprecated, use :func:`network.hostname` instead) 134 | reconnects Number of reconnect attempts to make (integer, 0=none, -1=unlimited) 135 | txpower Maximum transmit power in dBm (integer or float) 136 | pm WiFi Power Management setting (see below for allowed values) 137 | ============= =========== 138 | 139 | Constants 140 | --------- 141 | 142 | .. data:: WLAN.PM_PERFORMANCE 143 | WLAN.PM_POWERSAVE 144 | WLAN.PM_NONE 145 | 146 | Allowed values for the ``WLAN.config(pm=...)`` network interface parameter: 147 | 148 | * ``PM_PERFORMANCE``: enable WiFi power management to balance power 149 | savings and WiFi performance 150 | * ``PM_POWERSAVE``: enable WiFi power management with additional power 151 | savings and reduced WiFi performance 152 | * ``PM_NONE``: disable wifi power management 153 | -------------------------------------------------------------------------------- /docs/library/os.rst: -------------------------------------------------------------------------------- 1 | :mod:`os` -- basic "operating system" services 2 | ============================================== 3 | 4 | .. module:: os 5 | :synopsis: basic "operating system" services 6 | 7 | |see_cpython_module| :mod:`python:os`. 8 | 9 | The ``os`` module contains functions for filesystem access and mounting, 10 | terminal redirection and duplication, and the ``uname`` and ``urandom`` 11 | functions. 12 | 13 | General functions 14 | ----------------- 15 | 16 | .. function:: uname() 17 | 18 | Return a tuple (possibly a named tuple) containing information about the 19 | underlying machine and/or its operating system. The tuple has five fields 20 | in the following order, each of them being a string: 21 | 22 | * ``sysname`` -- the name of the underlying system 23 | * ``nodename`` -- the network name (can be the same as ``sysname``) 24 | * ``release`` -- the version of the underlying system 25 | * ``version`` -- the MicroPython version and build date 26 | * ``machine`` -- an identifier for the underlying hardware (eg board, CPU) 27 | 28 | .. function:: urandom(n) 29 | 30 | Return a bytes object with *n* random bytes. Whenever possible, it is 31 | generated by the hardware random number generator. 32 | 33 | Filesystem access 34 | ----------------- 35 | 36 | .. function:: chdir(path) 37 | 38 | Change current directory. 39 | 40 | .. function:: getcwd() 41 | 42 | Get the current directory. 43 | 44 | .. function:: ilistdir([dir]) 45 | 46 | This function returns an iterator which then yields tuples corresponding to 47 | the entries in the directory that it is listing. With no argument it lists the 48 | current directory, otherwise it lists the directory given by *dir*. 49 | 50 | The tuples have the form *(name, type, inode[, size])*: 51 | 52 | - *name* is a string (or bytes if *dir* is a bytes object) and is the name of 53 | the entry; 54 | - *type* is an integer that specifies the type of the entry, with 0x4000 for 55 | directories and 0x8000 for regular files; 56 | - *inode* is an integer corresponding to the inode of the file, and may be 0 57 | for filesystems that don't have such a notion. 58 | - Some platforms may return a 4-tuple that includes the entry's *size*. For 59 | file entries, *size* is an integer representing the size of the file 60 | or -1 if unknown. Its meaning is currently undefined for directory 61 | entries. 62 | 63 | .. function:: listdir([dir]) 64 | 65 | With no argument, list the current directory. Otherwise list the given directory. 66 | 67 | .. function:: mkdir(path) 68 | 69 | Create a new directory. 70 | 71 | .. function:: remove(path) 72 | 73 | Remove a file. 74 | 75 | .. function:: rmdir(path) 76 | 77 | Remove a directory. 78 | 79 | .. function:: rename(old_path, new_path) 80 | 81 | Rename a file. 82 | 83 | .. function:: stat(path) 84 | 85 | Get the status of a file or directory. 86 | 87 | .. function:: statvfs(path) 88 | 89 | Get the status of a filesystem. 90 | 91 | Returns a tuple with the filesystem information in the following order: 92 | 93 | * ``f_bsize`` -- file system block size 94 | * ``f_frsize`` -- fragment size 95 | * ``f_blocks`` -- size of fs in f_frsize units 96 | * ``f_bfree`` -- number of free blocks 97 | * ``f_bavail`` -- number of free blocks for unprivileged users 98 | * ``f_files`` -- number of inodes 99 | * ``f_ffree`` -- number of free inodes 100 | * ``f_favail`` -- number of free inodes for unprivileged users 101 | * ``f_flag`` -- mount flags 102 | * ``f_namemax`` -- maximum filename length 103 | 104 | Parameters related to inodes: ``f_files``, ``f_ffree``, ``f_avail`` 105 | and the ``f_flags`` parameter may return ``0`` as they can be unavailable 106 | in a port-specific implementation. 107 | 108 | .. function:: sync() 109 | 110 | Sync all filesystems. 111 | 112 | Filesystem mounting 113 | ------------------- 114 | 115 | The following functions and classes have been moved to the :mod:`vfs` module. 116 | They are provided in this module only for backwards compatibility and will be 117 | removed in version 2 of MicroPython. 118 | 119 | .. function:: mount(fsobj, mount_point, *, readonly) 120 | 121 | See `vfs.mount`. 122 | 123 | .. function:: umount(mount_point) 124 | 125 | See `vfs.umount`. 126 | 127 | .. class:: VfsFat(block_dev) 128 | 129 | See `vfs.VfsFat`. 130 | 131 | .. class:: VfsLfs1(block_dev, readsize=32, progsize=32, lookahead=32) 132 | 133 | See `vfs.VfsLfs1`. 134 | 135 | .. class:: VfsLfs2(block_dev, readsize=32, progsize=32, lookahead=32, mtime=True) 136 | 137 | See `vfs.VfsLfs2`. 138 | 139 | .. class:: VfsPosix(root=None) 140 | 141 | See `vfs.VfsPosix`. 142 | -------------------------------------------------------------------------------- /docs/library/platform.rst: -------------------------------------------------------------------------------- 1 | :mod:`platform` -- access to underlying platform’s identifying data 2 | =================================================================== 3 | 4 | .. module:: platform 5 | :synopsis: access to underlying platform’s identifying data 6 | 7 | |see_cpython_module| :mod:`python:platform`. 8 | 9 | This module tries to retrieve as much platform-identifying data as possible. It 10 | makes this information available via function APIs. 11 | 12 | Functions 13 | --------- 14 | 15 | .. function:: platform() 16 | 17 | Returns a string identifying the underlying platform. This string is composed 18 | of several substrings in the following order, delimited by dashes (``-``): 19 | 20 | - the name of the platform system (e.g. Unix, Windows or MicroPython) 21 | - the MicroPython version 22 | - the architecture of the platform 23 | - the version of the underlying platform 24 | - the concatenation of the name of the libc that MicroPython is linked to 25 | and its corresponding version. 26 | 27 | For example, this could be 28 | ``"MicroPython-1.20.0-xtensa-IDFv4.2.4-with-newlib3.0.0"``. 29 | 30 | .. function:: python_compiler() 31 | 32 | Returns a string identifying the compiler used for compiling MicroPython. 33 | 34 | .. function:: libc_ver() 35 | 36 | Returns a tuple of strings *(lib, version)*, where *lib* is the name of the 37 | libc that MicroPython is linked to, and *version* the corresponding version 38 | of this libc. 39 | -------------------------------------------------------------------------------- /docs/library/random.rst: -------------------------------------------------------------------------------- 1 | :mod:`random` -- generate random numbers 2 | ======================================== 3 | 4 | .. module:: random 5 | :synopsis: random numbers 6 | 7 | This module implements a pseudo-random number generator (PRNG). 8 | 9 | |see_cpython_module| :mod:`python:random` . 10 | 11 | .. note:: 12 | 13 | The following notation is used for intervals: 14 | 15 | - () are open interval brackets and do not include their endpoints. 16 | For example, (0, 1) means greater than 0 and less than 1. 17 | In set notation: (0, 1) = {x | 0 < x < 1}. 18 | 19 | - [] are closed interval brackets which include all their limit points. 20 | For example, [0, 1] means greater than or equal to 0 and less than 21 | or equal to 1. 22 | In set notation: [0, 1] = {x | 0 <= x <= 1}. 23 | 24 | .. note:: 25 | 26 | The :func:`randrange`, :func:`randint` and :func:`choice` functions are only 27 | available if the ``MICROPY_PY_RANDOM_EXTRA_FUNCS`` configuration option is 28 | enabled. 29 | 30 | 31 | Functions for integers 32 | ---------------------- 33 | 34 | .. function:: getrandbits(n) 35 | 36 | Return an integer with *n* random bits (0 <= n <= 32). 37 | 38 | .. function:: randint(a, b) 39 | 40 | Return a random integer in the range [*a*, *b*]. 41 | 42 | .. function:: randrange(stop) 43 | randrange(start, stop) 44 | randrange(start, stop[, step]) 45 | 46 | The first form returns a random integer from the range [0, *stop*). 47 | The second form returns a random integer from the range [*start*, *stop*). 48 | The third form returns a random integer from the range [*start*, *stop*) in 49 | steps of *step*. For instance, calling ``randrange(1, 10, 2)`` will 50 | return odd numbers between 1 and 9 inclusive. 51 | 52 | 53 | Functions for floats 54 | -------------------- 55 | 56 | .. function:: random() 57 | 58 | Return a random floating point number in the range [0.0, 1.0). 59 | 60 | .. function:: uniform(a, b) 61 | 62 | Return a random floating point number N such that *a* <= N <= *b* for *a* <= *b*, 63 | and *b* <= N <= *a* for *b* < *a*. 64 | 65 | 66 | Other Functions 67 | --------------- 68 | 69 | .. function:: seed(n=None, /) 70 | 71 | Initialise the random number generator module with the seed *n* which should 72 | be an integer. When no argument (or ``None``) is passed in it will (if 73 | supported by the port) initialise the PRNG with a true random number 74 | (usually a hardware generated random number). 75 | 76 | The ``None`` case only works if ``MICROPY_PY_RANDOM_SEED_INIT_FUNC`` is 77 | enabled by the port, otherwise it raises ``ValueError``. 78 | 79 | .. function:: choice(sequence) 80 | 81 | Chooses and returns one item at random from *sequence* (tuple, list or 82 | any object that supports the subscript operation). 83 | -------------------------------------------------------------------------------- /docs/library/re.rst: -------------------------------------------------------------------------------- 1 | :mod:`re` -- simple regular expressions 2 | ======================================= 3 | 4 | .. module:: re 5 | :synopsis: regular expressions 6 | 7 | |see_cpython_module| :mod:`python:re`. 8 | 9 | This module implements regular expression operations. Regular expression 10 | syntax supported is a subset of CPython ``re`` module (and actually is 11 | a subset of POSIX extended regular expressions). 12 | 13 | Supported operators and special sequences are: 14 | 15 | ``.`` 16 | Match any character. 17 | 18 | ``[...]`` 19 | Match set of characters. Individual characters and ranges are supported, 20 | including negated sets (e.g. ``[^a-c]``). 21 | 22 | ``^`` 23 | Match the start of the string. 24 | 25 | ``$`` 26 | Match the end of the string. 27 | 28 | ``?`` 29 | Match zero or one of the previous sub-pattern. 30 | 31 | ``*`` 32 | Match zero or more of the previous sub-pattern. 33 | 34 | ``+`` 35 | Match one or more of the previous sub-pattern. 36 | 37 | ``??`` 38 | Non-greedy version of ``?``, match zero or one, with the preference 39 | for zero. 40 | 41 | ``*?`` 42 | Non-greedy version of ``*``, match zero or more, with the preference 43 | for the shortest match. 44 | 45 | ``+?`` 46 | Non-greedy version of ``+``, match one or more, with the preference 47 | for the shortest match. 48 | 49 | ``|`` 50 | Match either the left-hand side or the right-hand side sub-patterns of 51 | this operator. 52 | 53 | ``(...)`` 54 | Grouping. Each group is capturing (a substring it captures can be accessed 55 | with `match.group()` method). 56 | 57 | ``\d`` 58 | Matches digit. Equivalent to ``[0-9]``. 59 | 60 | ``\D`` 61 | Matches non-digit. Equivalent to ``[^0-9]``. 62 | 63 | ``\s`` 64 | Matches whitespace. Equivalent to ``[ \t-\r]``. 65 | 66 | ``\S`` 67 | Matches non-whitespace. Equivalent to ``[^ \t-\r]``. 68 | 69 | ``\w`` 70 | Matches "word characters" (ASCII only). Equivalent to ``[A-Za-z0-9_]``. 71 | 72 | ``\W`` 73 | Matches non "word characters" (ASCII only). Equivalent to ``[^A-Za-z0-9_]``. 74 | 75 | ``\`` 76 | Escape character. Any other character following the backslash, except 77 | for those listed above, is taken literally. For example, ``\*`` is 78 | equivalent to literal ``*`` (not treated as the ``*`` operator). 79 | Note that ``\r``, ``\n``, etc. are not handled specially, and will be 80 | equivalent to literal letters ``r``, ``n``, etc. Due to this, it's 81 | not recommended to use raw Python strings (``r""``) for regular 82 | expressions. For example, ``r"\r\n"`` when used as the regular 83 | expression is equivalent to ``"rn"``. To match CR character followed 84 | by LF, use ``"\r\n"``. 85 | 86 | **NOT SUPPORTED**: 87 | 88 | * counted repetitions (``{m,n}``) 89 | * named groups (``(?P...)``) 90 | * non-capturing groups (``(?:...)``) 91 | * more advanced assertions (``\b``, ``\B``) 92 | * special character escapes like ``\r``, ``\n`` - use Python's own escaping 93 | instead 94 | * etc. 95 | 96 | Example:: 97 | 98 | import re 99 | 100 | # As re doesn't support escapes itself, use of r"" strings is not 101 | # recommended. 102 | regex = re.compile("[\r\n]") 103 | 104 | regex.split("line1\rline2\nline3\r\n") 105 | 106 | # Result: 107 | # ['line1', 'line2', 'line3', '', ''] 108 | 109 | Functions 110 | --------- 111 | 112 | .. function:: compile(regex_str, [flags]) 113 | 114 | Compile regular expression, return `regex ` object. 115 | 116 | .. function:: match(regex_str, string) 117 | 118 | Compile *regex_str* and match against *string*. Match always happens 119 | from starting position in a string. 120 | 121 | .. function:: search(regex_str, string) 122 | 123 | Compile *regex_str* and search it in a *string*. Unlike `match`, this will search 124 | string for first position which matches regex (which still may be 125 | 0 if regex is anchored). 126 | 127 | .. function:: sub(regex_str, replace, string, count=0, flags=0, /) 128 | 129 | Compile *regex_str* and search for it in *string*, replacing all matches 130 | with *replace*, and returning the new string. 131 | 132 | *replace* can be a string or a function. If it is a string then escape 133 | sequences of the form ``\`` and ``\g`` can be used to 134 | expand to the corresponding group (or an empty string for unmatched groups). 135 | If *replace* is a function then it must take a single argument (the match) 136 | and should return a replacement string. 137 | 138 | If *count* is specified and non-zero then substitution will stop after 139 | this many substitutions are made. The *flags* argument is ignored. 140 | 141 | Note: availability of this function depends on :term:`MicroPython port`. 142 | 143 | .. data:: DEBUG 144 | 145 | Flag value, display debug information about compiled expression. 146 | (Availability depends on :term:`MicroPython port`.) 147 | 148 | 149 | .. _regex: 150 | 151 | Regex objects 152 | ------------- 153 | 154 | Compiled regular expression. Instances of this class are created using 155 | `re.compile()`. 156 | 157 | .. method:: regex.match(string) 158 | regex.search(string) 159 | regex.sub(replace, string, count=0, flags=0, /) 160 | 161 | Similar to the module-level functions :meth:`match`, :meth:`search` 162 | and :meth:`sub`. 163 | Using methods is (much) more efficient if the same regex is applied to 164 | multiple strings. 165 | 166 | .. method:: regex.split(string, max_split=-1, /) 167 | 168 | Split a *string* using regex. If *max_split* is given, it specifies 169 | maximum number of splits to perform. Returns list of strings (there 170 | may be up to *max_split+1* elements if it's specified). 171 | 172 | Match objects 173 | ------------- 174 | 175 | Match objects as returned by `match()` and `search()` methods, and passed 176 | to the replacement function in `sub()`. 177 | 178 | .. method:: match.group(index) 179 | 180 | Return matching (sub)string. *index* is 0 for entire match, 181 | 1 and above for each capturing group. Only numeric groups are supported. 182 | 183 | .. method:: match.groups() 184 | 185 | Return a tuple containing all the substrings of the groups of the match. 186 | 187 | Note: availability of this method depends on :term:`MicroPython port`. 188 | 189 | .. method:: match.start([index]) 190 | match.end([index]) 191 | 192 | Return the index in the original string of the start or end of the 193 | substring group that was matched. *index* defaults to the entire 194 | group, otherwise it will select a group. 195 | 196 | Note: availability of these methods depends on :term:`MicroPython port`. 197 | 198 | .. method:: match.span([index]) 199 | 200 | Returns the 2-tuple ``(match.start(index), match.end(index))``. 201 | 202 | Note: availability of this method depends on :term:`MicroPython port`. 203 | -------------------------------------------------------------------------------- /docs/library/select.rst: -------------------------------------------------------------------------------- 1 | :mod:`select` -- wait for events on a set of streams 2 | ==================================================== 3 | 4 | .. module:: select 5 | :synopsis: wait for events on a set of streams 6 | 7 | |see_cpython_module| :mod:`python:select`. 8 | 9 | This module provides functions to efficiently wait for events on multiple 10 | `streams ` (select streams which are ready for operations). 11 | 12 | Functions 13 | --------- 14 | 15 | .. function:: poll() 16 | 17 | Create an instance of the Poll class. 18 | 19 | .. function:: select(rlist, wlist, xlist[, timeout]) 20 | 21 | Wait for activity on a set of objects. 22 | 23 | This function is provided by some MicroPython ports for compatibility 24 | and is not efficient. Usage of :class:`Poll` is recommended instead. 25 | 26 | .. _class: Poll 27 | 28 | class ``Poll`` 29 | -------------- 30 | 31 | Methods 32 | ~~~~~~~ 33 | 34 | .. method:: poll.register(obj[, eventmask]) 35 | 36 | Register `stream` *obj* for polling. *eventmask* is logical OR of: 37 | 38 | * ``select.POLLIN`` - data available for reading 39 | * ``select.POLLOUT`` - more data can be written 40 | 41 | Note that flags like ``select.POLLHUP`` and ``select.POLLERR`` are 42 | *not* valid as input eventmask (these are unsolicited events which 43 | will be returned from `poll()` regardless of whether they are asked 44 | for). This semantics is per POSIX. 45 | 46 | *eventmask* defaults to ``select.POLLIN | select.POLLOUT``. 47 | 48 | It is OK to call this function multiple times for the same *obj*. 49 | Successive calls will update *obj*'s eventmask to the value of 50 | *eventmask* (i.e. will behave as `modify()`). 51 | 52 | .. method:: poll.unregister(obj) 53 | 54 | Unregister *obj* from polling. 55 | 56 | .. method:: poll.modify(obj, eventmask) 57 | 58 | Modify the *eventmask* for *obj*. If *obj* is not registered, `OSError` 59 | is raised with error of ENOENT. 60 | 61 | .. method:: poll.poll(timeout=-1, /) 62 | 63 | Wait for at least one of the registered objects to become ready or have an 64 | exceptional condition, with optional timeout in milliseconds (if *timeout* 65 | arg is not specified or -1, there is no timeout). 66 | 67 | Returns list of (``obj``, ``event``, ...) tuples. There may be other elements in 68 | tuple, depending on a platform and version, so don't assume that its size is 2. 69 | The ``event`` element specifies which events happened with a stream and 70 | is a combination of ``select.POLL*`` constants described above. Note that 71 | flags ``select.POLLHUP`` and ``select.POLLERR`` can be returned at any time 72 | (even if were not asked for), and must be acted on accordingly (the 73 | corresponding stream unregistered from poll and likely closed), because 74 | otherwise all further invocations of `poll()` may return immediately with 75 | these flags set for this stream again. 76 | 77 | In case of timeout, an empty list is returned. 78 | 79 | .. admonition:: Difference to CPython 80 | :class: attention 81 | 82 | Tuples returned may contain more than 2 elements as described above. 83 | 84 | .. method:: poll.ipoll(timeout=-1, flags=0, /) 85 | 86 | Like :meth:`poll.poll`, but instead returns an iterator which yields a 87 | `callee-owned tuple`. This function provides an efficient, allocation-free 88 | way to poll on streams. 89 | 90 | If *flags* is 1, one-shot behaviour for events is employed: streams for 91 | which events happened will have their event masks automatically reset 92 | (equivalent to ``poll.modify(obj, 0)``), so new events for such a stream 93 | won't be processed until new mask is set with `poll.modify()`. This 94 | behaviour is useful for asynchronous I/O schedulers. 95 | 96 | .. admonition:: Difference to CPython 97 | :class: attention 98 | 99 | This function is a MicroPython extension. 100 | -------------------------------------------------------------------------------- /docs/library/ssl.rst: -------------------------------------------------------------------------------- 1 | :mod:`ssl` -- SSL/TLS module 2 | ============================ 3 | 4 | .. module:: ssl 5 | :synopsis: TLS/SSL wrapper for socket objects 6 | 7 | |see_cpython_module| :mod:`python:ssl`. 8 | 9 | This module provides access to Transport Layer Security (previously and 10 | widely known as “Secure Sockets Layer”) encryption and peer authentication 11 | facilities for network sockets, both client-side and server-side. 12 | 13 | Functions 14 | --------- 15 | 16 | .. function:: ssl.wrap_socket(sock, server_side=False, key=None, cert=None, cert_reqs=CERT_NONE, cadata=None, server_hostname=None, do_handshake=True) 17 | 18 | Wrap the given *sock* and return a new wrapped-socket object. The implementation 19 | of this function is to first create an `SSLContext` and then call the `SSLContext.wrap_socket` 20 | method on that context object. The arguments *sock*, *server_side* and *server_hostname* are 21 | passed through unchanged to the method call. The argument *do_handshake* is passed through as 22 | *do_handshake_on_connect*. The remaining arguments have the following behaviour: 23 | 24 | - *cert_reqs* determines whether the peer (server or client) must present a valid certificate. 25 | Note that for mbedtls based ports, ``ssl.CERT_NONE`` and ``ssl.CERT_OPTIONAL`` will not 26 | validate any certificate, only ``ssl.CERT_REQUIRED`` will. 27 | 28 | - *cadata* is a bytes object containing the CA certificate chain (in DER format) that will 29 | validate the peer's certificate. Currently only a single DER-encoded certificate is supported. 30 | 31 | Depending on the underlying module implementation in a particular 32 | :term:`MicroPython port`, some or all keyword arguments above may be not supported. 33 | 34 | class SSLContext 35 | ---------------- 36 | 37 | .. class:: SSLContext(protocol, /) 38 | 39 | Create a new SSLContext instance. The *protocol* argument must be one of the ``PROTOCOL_*`` 40 | constants. 41 | 42 | .. method:: SSLContext.load_cert_chain(certfile, keyfile) 43 | 44 | Load a private key and the corresponding certificate. The *certfile* is a string 45 | with the file path of the certificate. The *keyfile* is a string with the file path 46 | of the private key. 47 | 48 | .. admonition:: Difference to CPython 49 | :class: attention 50 | 51 | MicroPython extension: *certfile* and *keyfile* can be bytes objects instead of 52 | strings, in which case they are interpreted as the actual certificate/key data. 53 | 54 | .. method:: SSLContext.load_verify_locations(cafile=None, cadata=None) 55 | 56 | Load the CA certificate chain that will validate the peer's certificate. 57 | *cafile* is the file path of the CA certificates. *cadata* is a bytes object 58 | containing the CA certificates. Only one of these arguments should be provided. 59 | 60 | .. method:: SSLContext.get_ciphers() 61 | 62 | Get a list of enabled ciphers, returned as a list of strings. 63 | 64 | .. method:: SSLContext.set_ciphers(ciphers) 65 | 66 | Set the available ciphers for sockets created with this context. *ciphers* should be 67 | a list of strings in the `IANA cipher suite format `_ . 68 | 69 | .. method:: SSLContext.wrap_socket(sock, *, server_side=False, do_handshake_on_connect=True, server_hostname=None) 70 | 71 | Takes a `stream` *sock* (usually socket.socket instance of ``SOCK_STREAM`` type), 72 | and returns an instance of ssl.SSLSocket, wrapping the underlying stream. 73 | The returned object has the usual `stream` interface methods like 74 | ``read()``, ``write()``, etc. 75 | 76 | - *server_side* selects whether the wrapped socket is on the server or client side. 77 | A server-side SSL socket should be created from a normal socket returned from 78 | :meth:`~socket.socket.accept()` on a non-SSL listening server socket. 79 | 80 | - *do_handshake_on_connect* determines whether the handshake is done as part of the ``wrap_socket`` 81 | or whether it is deferred to be done as part of the initial reads or writes 82 | For blocking sockets doing the handshake immediately is standard. For non-blocking 83 | sockets (i.e. when the *sock* passed into ``wrap_socket`` is in non-blocking mode) 84 | the handshake should generally be deferred because otherwise ``wrap_socket`` blocks 85 | until it completes. Note that in AXTLS the handshake can be deferred until the first 86 | read or write but it then blocks until completion. 87 | 88 | - *server_hostname* is for use as a client, and sets the hostname to check against the received 89 | server certificate. It also sets the name for Server Name Indication (SNI), allowing the server 90 | to present the proper certificate. 91 | 92 | .. warning:: 93 | 94 | Some implementations of ``ssl`` module do NOT validate server certificates, 95 | which makes an SSL connection established prone to man-in-the-middle attacks. 96 | 97 | CPython's ``wrap_socket`` returns an ``SSLSocket`` object which has methods typical 98 | for sockets, such as ``send``, ``recv``, etc. MicroPython's ``wrap_socket`` 99 | returns an object more similar to CPython's ``SSLObject`` which does not have 100 | these socket methods. 101 | 102 | .. attribute:: SSLContext.verify_mode 103 | 104 | Set or get the behaviour for verification of peer certificates. Must be one of the 105 | ``CERT_*`` constants. 106 | 107 | .. note:: 108 | 109 | ``ssl.CERT_REQUIRED`` requires the device's date/time to be properly set, e.g. using 110 | `mpremote rtc --set ` or ``ntptime``, and ``server_hostname`` 111 | must be specified when on the client side. 112 | 113 | Exceptions 114 | ---------- 115 | 116 | .. data:: ssl.SSLError 117 | 118 | This exception does NOT exist. Instead its base class, OSError, is used. 119 | 120 | Constants 121 | --------- 122 | 123 | .. data:: ssl.PROTOCOL_TLS_CLIENT 124 | ssl.PROTOCOL_TLS_SERVER 125 | 126 | Supported values for the *protocol* parameter. 127 | 128 | .. data:: ssl.CERT_NONE 129 | ssl.CERT_OPTIONAL 130 | ssl.CERT_REQUIRED 131 | 132 | Supported values for *cert_reqs* parameter, and the :attr:`SSLContext.verify_mode` 133 | attribute. 134 | -------------------------------------------------------------------------------- /docs/library/struct.rst: -------------------------------------------------------------------------------- 1 | :mod:`struct` -- pack and unpack primitive data types 2 | ===================================================== 3 | 4 | .. module:: struct 5 | :synopsis: pack and unpack primitive data types 6 | 7 | |see_cpython_module| :mod:`python:struct`. 8 | 9 | The following byte orders are supported: 10 | 11 | +-----------+------------------------+----------+-----------+ 12 | | Character | Byte order | Size | Alignment | 13 | +===========+========================+==========+===========+ 14 | | @ | native | native | native | 15 | +-----------+------------------------+----------+-----------+ 16 | | < | little-endian | standard | none | 17 | +-----------+------------------------+----------+-----------+ 18 | | > | big-endian | standard | none | 19 | +-----------+------------------------+----------+-----------+ 20 | | ! | network (= big-endian) | standard | none | 21 | +-----------+------------------------+----------+-----------+ 22 | 23 | The following data types are supported: 24 | 25 | +--------+--------------------+-------------------+---------------+ 26 | | Format | C Type | Python type | Standard size | 27 | +========+====================+===================+===============+ 28 | | b | signed char | integer | 1 | 29 | +--------+--------------------+-------------------+---------------+ 30 | | B | unsigned char | integer | 1 | 31 | +--------+--------------------+-------------------+---------------+ 32 | | h | short | integer | 2 | 33 | +--------+--------------------+-------------------+---------------+ 34 | | H | unsigned short | integer | 2 | 35 | +--------+--------------------+-------------------+---------------+ 36 | | i | int | integer (`1`) | 4 | 37 | +--------+--------------------+-------------------+---------------+ 38 | | I | unsigned int | integer (`1`) | 4 | 39 | +--------+--------------------+-------------------+---------------+ 40 | | l | long | integer (`1`) | 4 | 41 | +--------+--------------------+-------------------+---------------+ 42 | | L | unsigned long | integer (`1`) | 4 | 43 | +--------+--------------------+-------------------+---------------+ 44 | | q | long long | integer (`1`) | 8 | 45 | +--------+--------------------+-------------------+---------------+ 46 | | Q | unsigned long long | integer (`1`) | 8 | 47 | +--------+--------------------+-------------------+---------------+ 48 | | e | n/a (half-float) | float (`2`) | 2 | 49 | +--------+--------------------+-------------------+---------------+ 50 | | f | float | float (`2`) | 4 | 51 | +--------+--------------------+-------------------+---------------+ 52 | | d | double | float (`2`) | 8 | 53 | +--------+--------------------+-------------------+---------------+ 54 | | s | char[] | bytes | | 55 | +--------+--------------------+-------------------+---------------+ 56 | | P | void * | integer | | 57 | +--------+--------------------+-------------------+---------------+ 58 | 59 | .. _fn: 60 | 61 | (1) Requires long support when used with values larger than 30 bits. 62 | (2) Requires floating point support. 63 | 64 | .. admonition:: Difference to CPython 65 | :class: attention 66 | 67 | Whitespace is not supported in format strings. 68 | 69 | Functions 70 | --------- 71 | 72 | .. function:: calcsize(fmt) 73 | 74 | Return the number of bytes needed to store the given *fmt*. 75 | 76 | .. function:: pack(fmt, v1, v2, ...) 77 | 78 | Pack the values *v1*, *v2*, ... according to the format string *fmt*. 79 | The return value is a bytes object encoding the values. 80 | 81 | .. function:: pack_into(fmt, buffer, offset, v1, v2, ...) 82 | 83 | Pack the values *v1*, *v2*, ... according to the format string *fmt* 84 | into a *buffer* starting at *offset*. *offset* may be negative to count 85 | from the end of *buffer*. 86 | 87 | .. function:: unpack(fmt, data) 88 | 89 | Unpack from the *data* according to the format string *fmt*. 90 | The return value is a tuple of the unpacked values. 91 | 92 | .. function:: unpack_from(fmt, data, offset=0, /) 93 | 94 | Unpack from the *data* starting at *offset* according to the format string 95 | *fmt*. *offset* may be negative to count from the end of *data*. The return 96 | value is a tuple of the unpacked values. 97 | -------------------------------------------------------------------------------- /docs/library/sys.rst: -------------------------------------------------------------------------------- 1 | :mod:`sys` -- system specific functions 2 | ======================================= 3 | 4 | .. module:: sys 5 | :synopsis: system specific functions 6 | 7 | |see_cpython_module| :mod:`python:sys`. 8 | 9 | Functions 10 | --------- 11 | 12 | .. function:: exit(retval=0, /) 13 | 14 | Terminate current program with a given exit code. Underlyingly, this 15 | function raise as `SystemExit` exception. If an argument is given, its 16 | value given as an argument to `SystemExit`. 17 | 18 | .. function:: atexit(func) 19 | 20 | Register *func* to be called upon termination. *func* must be a callable 21 | that takes no arguments, or ``None`` to disable the call. The ``atexit`` 22 | function will return the previous value set by this function, which is 23 | initially ``None``. 24 | 25 | .. admonition:: Difference to CPython 26 | :class: attention 27 | 28 | This function is a MicroPython extension intended to provide similar 29 | functionality to the :mod:`atexit` module in CPython. 30 | 31 | .. function:: print_exception(exc, file=sys.stdout, /) 32 | 33 | Print exception with a traceback to a file-like object *file* (or 34 | `sys.stdout` by default). 35 | 36 | .. admonition:: Difference to CPython 37 | :class: attention 38 | 39 | This is simplified version of a function which appears in the 40 | ``traceback`` module in CPython. Unlike ``traceback.print_exception()``, 41 | this function takes just exception value instead of exception type, 42 | exception value, and traceback object; *file* argument should be 43 | positional; further arguments are not supported. CPython-compatible 44 | ``traceback`` module can be found in `micropython-lib`. 45 | 46 | .. function:: settrace(tracefunc) 47 | 48 | Enable tracing of bytecode execution. For details see the `CPython 49 | documentation `_. 50 | 51 | This function requires a custom MicroPython build as it is typically not 52 | present in pre-built firmware (due to it affecting performance). The relevant 53 | configuration option is *MICROPY_PY_SYS_SETTRACE*. 54 | 55 | Constants 56 | --------- 57 | 58 | .. data:: argv 59 | 60 | A mutable list of arguments the current program was started with. 61 | 62 | .. data:: byteorder 63 | 64 | The byte order of the system (``"little"`` or ``"big"``). 65 | 66 | .. data:: implementation 67 | 68 | Object with information about the current Python implementation. For 69 | MicroPython, it has following attributes: 70 | 71 | * *name* - string "micropython" 72 | * *version* - tuple (major, minor, micro, releaselevel), e.g. (1, 22, 0, '') 73 | * *_machine* - string describing the underlying machine 74 | * *_mpy* - supported mpy file-format version (optional attribute) 75 | 76 | This object is the recommended way to distinguish MicroPython from other 77 | Python implementations (note that it still may not exist in the very 78 | minimal ports). 79 | 80 | Starting with version 1.22.0-preview, the fourth node *releaselevel* in 81 | *implementation.version* is either an empty string or ``"preview"``. 82 | 83 | .. admonition:: Difference to CPython 84 | :class: attention 85 | 86 | CPython mandates more attributes for this object, but the actual useful 87 | bare minimum is implemented in MicroPython. 88 | 89 | .. data:: maxsize 90 | 91 | Maximum value which a native integer type can hold on the current platform, 92 | or maximum value representable by MicroPython integer type, if it's smaller 93 | than platform max value (that is the case for MicroPython ports without 94 | long int support). 95 | 96 | This attribute is useful for detecting "bitness" of a platform (32-bit vs 97 | 64-bit, etc.). It's recommended to not compare this attribute to some 98 | value directly, but instead count number of bits in it:: 99 | 100 | bits = 0 101 | v = sys.maxsize 102 | while v: 103 | bits += 1 104 | v >>= 1 105 | if bits > 32: 106 | # 64-bit (or more) platform 107 | ... 108 | else: 109 | # 32-bit (or less) platform 110 | # Note that on 32-bit platform, value of bits may be less than 32 111 | # (e.g. 31) due to peculiarities described above, so use "> 16", 112 | # "> 32", "> 64" style of comparisons. 113 | 114 | .. data:: modules 115 | 116 | Dictionary of loaded modules. On some ports, it may not include builtin 117 | modules. 118 | 119 | .. data:: path 120 | 121 | A mutable list of directories to search for imported modules. 122 | 123 | .. admonition:: Difference to CPython 124 | :class: attention 125 | 126 | On MicroPython, an entry with the value ``".frozen"`` will indicate that import 127 | should search :term:`frozen modules ` at that point in the search. 128 | If no frozen module is found then search will *not* look for a directory called 129 | ``.frozen``, instead it will continue with the next entry in ``sys.path``. 130 | 131 | .. data:: platform 132 | 133 | The platform that MicroPython is running on. For OS/RTOS ports, this is 134 | usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it 135 | is an identifier of a board, e.g. ``"pyboard"`` for the original MicroPython 136 | reference board. It thus can be used to distinguish one board from another. 137 | If you need to check whether your program runs on MicroPython (vs other 138 | Python implementation), use `sys.implementation` instead. 139 | 140 | .. data:: ps1 141 | ps2 142 | 143 | Mutable attributes holding strings, which are used for the REPL prompt. The defaults 144 | give the standard Python prompt of ``>>>`` and ``...``. 145 | 146 | .. data:: stderr 147 | 148 | Standard error `stream`. 149 | 150 | .. data:: stdin 151 | 152 | Standard input `stream`. 153 | 154 | .. data:: stdout 155 | 156 | Standard output `stream`. 157 | 158 | .. data:: tracebacklimit 159 | 160 | A mutable attribute holding an integer value which is the maximum number of traceback 161 | entries to store in an exception. Set to 0 to disable adding tracebacks. Defaults 162 | to 1000. 163 | 164 | Note: this is not available on all ports. 165 | 166 | .. data:: version 167 | 168 | Python language version that this implementation conforms to, as a string. 169 | 170 | .. data:: version_info 171 | 172 | Python language version that this implementation conforms to, as a tuple of ints. 173 | 174 | .. admonition:: Difference to CPython 175 | :class: attention 176 | 177 | Only the first three version numbers (major, minor, micro) are supported and 178 | they can be referenced only by index, not by name. 179 | -------------------------------------------------------------------------------- /docs/library/zlib.rst: -------------------------------------------------------------------------------- 1 | :mod:`zlib` -- zlib compression & decompression 2 | =============================================== 3 | 4 | .. module:: zlib 5 | :synopsis: zlib compression & decompression 6 | 7 | |see_cpython_module| :mod:`python:zlib`. 8 | 9 | This module allows compression and decompression of binary data with the 10 | `DEFLATE algorithm `_ 11 | (commonly used in the zlib library and gzip archiver). 12 | 13 | .. note:: Prefer to use :class:`deflate.DeflateIO` instead of the functions in this 14 | module as it provides a streaming interface to compression and decompression 15 | which is convenient and more memory efficient when working with reading or 16 | writing compressed data to a file, socket, or stream. 17 | 18 | **Availability:** 19 | 20 | * From MicroPython v1.21 onwards, this module may not be present by default on 21 | all MicroPython firmware as it duplicates functionality available in 22 | the :mod:`deflate ` module. 23 | 24 | * A copy of this module can be installed (or frozen) 25 | from :term:`micropython-lib` (`source `_). 26 | See :ref:`packages` for more information. This documentation describes that module. 27 | 28 | * Requires the built-in :mod:`deflate ` module (available since MicroPython v1.21) 29 | 30 | * Compression support will only be available if compression support is enabled 31 | in the built-in :mod:`deflate ` module. 32 | 33 | Functions 34 | --------- 35 | 36 | .. function:: decompress(data, wbits=15, /) 37 | 38 | Decompresses *data* into a bytes object. 39 | 40 | The *wbits* parameter works the same way as for :meth:`zlib.compress` 41 | with the following additional valid values: 42 | 43 | * ``0``: Automatically determine the window size from the zlib header 44 | (*data* must be in zlib format). 45 | * ``35`` to ``47``: Auto-detect either the zlib or gzip format. 46 | 47 | As for :meth:`zlib.compress`, see the :mod:`CPython documentation for zlib ` 48 | for more information about the *wbits* parameter. As for :meth:`zlib.compress`, 49 | MicroPython also supports smaller window sizes than CPython. See more 50 | :ref:`MicroPython-specific details ` in the 51 | :mod:`deflate ` module documentation. 52 | 53 | If the data to be decompressed requires a larger window size, it will 54 | fail during decompression. 55 | 56 | .. function:: compress(data, wbits=15, /) 57 | 58 | Compresses *data* into a bytes object. 59 | 60 | *wbits* allows you to configure the DEFLATE dictionary window size and the 61 | output format. The window size allows you to trade-off memory usage for 62 | compression level. A larger window size will allow the compressor to 63 | reference fragments further back in the input. The output formats are "raw" 64 | DEFLATE (no header/footer), zlib, and gzip, where the latter two 65 | include a header and checksum. 66 | 67 | The low four bits of the absolute value of *wbits* set the base-2 logarithm of 68 | the DEFLATE dictionary window size. So for example, ``wbits=10``, 69 | ``wbits=-10``, and ``wbits=26`` all set the window size to 1024 bytes. Valid 70 | window sizes are ``5`` to ``15`` inclusive (corresponding to 32 to 32k bytes). 71 | 72 | Negative values of *wbits* between ``-5`` and ``-15`` correspond to "raw" 73 | output mode, positive values between ``5`` and ``15`` correspond to zlib 74 | output mode, and positive values between ``21`` and ``31`` correspond to 75 | gzip output mode. 76 | 77 | See the :mod:`CPython documentation for zlib ` for more 78 | information about the *wbits* parameter. Note that MicroPython allows 79 | for smaller window sizes, which is useful when memory is constrained while 80 | still achieving a reasonable level of compression. It also speeds up 81 | the compressor. See more :ref:`MicroPython-specific details ` 82 | in the :mod:`deflate ` module documentation. 83 | -------------------------------------------------------------------------------- /docs/license.rst: -------------------------------------------------------------------------------- 1 | CyberBrick Codebase license information 2 | ======================================= 3 | 4 | CyberBrick Codebase License: 5 | 6 | Copyright (C) 2025 MakerWorld 7 | 8 | Permission is hereby granted, free of charge, to any person obtaining 9 | a copy of this software and associated documentation files (the "Software"), 10 | to use, copy, modify, reproduce and distribute (the "Use") the Software, 11 | subject to the following conditions: 12 | 13 | 1. Only Use in MakerWorld 14 | The Software may only be used through services, programs, 15 | or products provided by MakerWorld, or those expressly authorized 16 | by a written license from MakerWorld. When using the Software, 17 | strict compliance with MakerWorld's Terms of Use and Community Guidelines is mandatory. 18 | 19 | 2. Derivative Works 20 | You may reproduce and distribute copies of your derivative works 21 | based on the Software (the "Derivative Works") under the license of Article 1. 22 | You may add Your own copyright statement to Your modifications 23 | and may provide additional or different license terms and 24 | conditions of Your modifications, or for any such Derivative Works as a whole. 25 | 26 | 3. License Notice 27 | This License including but not limited to the copyright of 28 | MakerWorld shall be included in all copies or substantial portions of the Software. 29 | 30 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 31 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 32 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 33 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 34 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 35 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 36 | 37 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=build 9 | set SPHINXOPTS=-W --keep-going 10 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 11 | set I18NSPHINXOPTS=%SPHINXOPTS% . 12 | if NOT "%PAPER%" == "" ( 13 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 14 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 15 | ) 16 | 17 | if "%1" == "" goto help 18 | 19 | if "%1" == "help" ( 20 | :help 21 | echo.Please use `make ^` where ^ is one of 22 | echo. html to make standalone HTML files 23 | echo. dirhtml to make HTML files named index.html in directories 24 | echo. singlehtml to make a single large HTML file 25 | echo. pickle to make pickle files 26 | echo. json to make JSON files 27 | echo. htmlhelp to make HTML files and a HTML help project 28 | echo. qthelp to make HTML files and a qthelp project 29 | echo. devhelp to make HTML files and a Devhelp project 30 | echo. epub to make an epub 31 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 32 | echo. text to make text files 33 | echo. man to make manual pages 34 | echo. texinfo to make Texinfo files 35 | echo. gettext to make PO message catalogs 36 | echo. changes to make an overview over all changed/added/deprecated items 37 | echo. xml to make Docutils-native XML files 38 | echo. pseudoxml to make pseudoxml-XML files for display purposes 39 | echo. linkcheck to check all external links for integrity 40 | echo. doctest to run all doctests embedded in the documentation if enabled 41 | goto end 42 | ) 43 | 44 | if "%1" == "clean" ( 45 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 46 | del /q /s %BUILDDIR%\* 47 | goto end 48 | ) 49 | 50 | 51 | %SPHINXBUILD% 2> nul 52 | if errorlevel 9009 ( 53 | echo. 54 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 55 | echo.installed, then set the SPHINXBUILD environment variable to point 56 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 57 | echo.may add the Sphinx directory to PATH. 58 | echo. 59 | echo.If you don't have Sphinx installed, grab it from 60 | echo.http://sphinx-doc.org/ 61 | exit /b 1 62 | ) 63 | 64 | if "%1" == "html" ( 65 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 66 | if errorlevel 1 exit /b 1 67 | echo. 68 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 69 | goto end 70 | ) 71 | 72 | if "%1" == "dirhtml" ( 73 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 74 | if errorlevel 1 exit /b 1 75 | echo. 76 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 77 | goto end 78 | ) 79 | 80 | if "%1" == "singlehtml" ( 81 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 82 | if errorlevel 1 exit /b 1 83 | echo. 84 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 85 | goto end 86 | ) 87 | 88 | if "%1" == "pickle" ( 89 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 90 | if errorlevel 1 exit /b 1 91 | echo. 92 | echo.Build finished; now you can process the pickle files. 93 | goto end 94 | ) 95 | 96 | if "%1" == "json" ( 97 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 98 | if errorlevel 1 exit /b 1 99 | echo. 100 | echo.Build finished; now you can process the JSON files. 101 | goto end 102 | ) 103 | 104 | if "%1" == "htmlhelp" ( 105 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 106 | if errorlevel 1 exit /b 1 107 | echo. 108 | echo.Build finished; now you can run HTML Help Workshop with the ^ 109 | .hhp project file in %BUILDDIR%/htmlhelp. 110 | goto end 111 | ) 112 | 113 | if "%1" == "qthelp" ( 114 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 115 | if errorlevel 1 exit /b 1 116 | echo. 117 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 118 | .qhcp project file in %BUILDDIR%/qthelp, like this: 119 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\MicroPython.qhcp 120 | echo.To view the help file: 121 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\MicroPython.ghc 122 | goto end 123 | ) 124 | 125 | if "%1" == "devhelp" ( 126 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 127 | if errorlevel 1 exit /b 1 128 | echo. 129 | echo.Build finished. 130 | goto end 131 | ) 132 | 133 | if "%1" == "epub" ( 134 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 135 | if errorlevel 1 exit /b 1 136 | echo. 137 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 138 | goto end 139 | ) 140 | 141 | if "%1" == "latex" ( 142 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 143 | if errorlevel 1 exit /b 1 144 | echo. 145 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 146 | goto end 147 | ) 148 | 149 | if "%1" == "latexpdf" ( 150 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 151 | cd %BUILDDIR%/latex 152 | make all-pdf 153 | cd %BUILDDIR%/.. 154 | echo. 155 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 156 | goto end 157 | ) 158 | 159 | if "%1" == "latexpdfja" ( 160 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 161 | cd %BUILDDIR%/latex 162 | make all-pdf-ja 163 | cd %BUILDDIR%/.. 164 | echo. 165 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 166 | goto end 167 | ) 168 | 169 | if "%1" == "text" ( 170 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 171 | if errorlevel 1 exit /b 1 172 | echo. 173 | echo.Build finished. The text files are in %BUILDDIR%/text. 174 | goto end 175 | ) 176 | 177 | if "%1" == "man" ( 178 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 179 | if errorlevel 1 exit /b 1 180 | echo. 181 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 182 | goto end 183 | ) 184 | 185 | if "%1" == "texinfo" ( 186 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 187 | if errorlevel 1 exit /b 1 188 | echo. 189 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 190 | goto end 191 | ) 192 | 193 | if "%1" == "gettext" ( 194 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 195 | if errorlevel 1 exit /b 1 196 | echo. 197 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 198 | goto end 199 | ) 200 | 201 | if "%1" == "changes" ( 202 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 203 | if errorlevel 1 exit /b 1 204 | echo. 205 | echo.The overview file is in %BUILDDIR%/changes. 206 | goto end 207 | ) 208 | 209 | if "%1" == "linkcheck" ( 210 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 211 | if errorlevel 1 exit /b 1 212 | echo. 213 | echo.Link check complete; look for any errors in the above output ^ 214 | or in %BUILDDIR%/linkcheck/output.txt. 215 | goto end 216 | ) 217 | 218 | if "%1" == "doctest" ( 219 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 220 | if errorlevel 1 exit /b 1 221 | echo. 222 | echo.Testing of doctests in the sources finished, look at the ^ 223 | results in %BUILDDIR%/doctest/output.txt. 224 | goto end 225 | ) 226 | 227 | if "%1" == "xml" ( 228 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 229 | if errorlevel 1 exit /b 1 230 | echo. 231 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 232 | goto end 233 | ) 234 | 235 | if "%1" == "pseudoxml" ( 236 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 237 | if errorlevel 1 exit /b 1 238 | echo. 239 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 240 | goto end 241 | ) 242 | 243 | :end 244 | -------------------------------------------------------------------------------- /docs/readthedocs/settings/local_settings.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | # Directory that the project lives in, aka ../.. 4 | SITE_ROOT = "/".join(os.path.dirname(__file__).split("/")[0:-2]) 5 | 6 | TEMPLATE_DIRS = ( 7 | "%s/templates/" 8 | % SITE_ROOT, # Your custom template directory, before the RTD one to override it. 9 | "%s/readthedocs/templates/" % SITE_ROOT, # Default RTD template dir 10 | ) 11 | -------------------------------------------------------------------------------- /docs/reference/index.rst: -------------------------------------------------------------------------------- 1 | MicroPython language and implementation 2 | ======================================= 3 | 4 | MicroPython aims to implement the Python 3.4 standard (with selected 5 | features from later versions) with respect to language syntax, and most 6 | of the features of MicroPython are identical to those described by the 7 | "Language Reference" documentation at 8 | `docs.python.org `_. 9 | 10 | .. toctree:: 11 | :maxdepth: 1 12 | 13 | glossary.rst 14 | repl.rst 15 | mpremote.rst 16 | mpyfiles.rst 17 | isr_rules.rst 18 | speed_python.rst 19 | constrained.rst 20 | packages.rst 21 | pyboard.py.rst 22 | -------------------------------------------------------------------------------- /docs/reference/packages.rst: -------------------------------------------------------------------------------- 1 | .. _packages: 2 | 3 | Package management 4 | ================== 5 | 6 | Installing packages with ``mip`` 7 | -------------------------------- 8 | 9 | Network-capable boards include the ``mip`` module, which can install packages 10 | from :term:`micropython-lib` and from third-party sites (including GitHub). 11 | 12 | ``mip`` ("mip installs packages") is similar in concept to Python's ``pip`` tool, 13 | however it does not use the PyPI index, rather it uses :term:`micropython-lib` 14 | as its index by default. ``mip`` will automatically fetch compiled 15 | :term:`.mpy file` when downloading from micropython-lib. 16 | 17 | The most common way to use ``mip`` is from the REPL:: 18 | 19 | >>> import mip 20 | >>> mip.install("pkgname") # Installs the latest version of "pkgname" (and dependencies) 21 | >>> mip.install("pkgname", version="x.y") # Installs version x.y of "pkgname" 22 | >>> mip.install("pkgname", mpy=False) # Installs the source version (i.e. .py rather than .mpy files) 23 | 24 | ``mip`` will detect an appropriate location on the filesystem by searching 25 | ``sys.path`` for the first entry ending in ``/lib``. You can override the 26 | destination using ``target``, but note that this path must be in ``sys.path`` to be 27 | able to subsequently import it.:: 28 | 29 | >>> mip.install("pkgname", target="third-party") 30 | >>> sys.path.append("third-party") 31 | 32 | As well as downloading packages from the micropython-lib index, ``mip`` can also 33 | install third-party libraries. The simplest way is to download a file directly:: 34 | 35 | >>> mip.install("http://example.com/x/y/foo.py") 36 | >>> mip.install("http://example.com/x/y/foo.mpy") 37 | 38 | When installing a file directly, the ``target`` argument is still supported to set 39 | the destination path, but ``mpy`` and ``version`` are ignored. 40 | 41 | The URL can also start with ``github:`` as a simple way of pointing to content 42 | hosted on GitHub:: 43 | 44 | >>> mip.install("github:org/repo/path/foo.py") # Uses default branch 45 | >>> mip.install("github:org/repo/path/foo.py", version="branch-or-tag") # Optionally specify the branch or tag 46 | 47 | More sophisticated packages (i.e. with more than one file, or with dependencies) 48 | can be downloaded by specifying the path to their ``package.json``. 49 | 50 | >>> mip.install("http://example.com/x/package.json") 51 | >>> mip.install("github:org/user/path/package.json") 52 | 53 | If no json file is specified, then "package.json" is implicitly added:: 54 | 55 | >>> mip.install("http://example.com/x/") 56 | >>> mip.install("github:org/repo") # Uses default branch of that repo 57 | >>> mip.install("github:org/repo", version="branch-or-tag") 58 | 59 | 60 | Using ``mip`` on the Unix port 61 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 62 | 63 | On the Unix port, ``mip`` can be used at the REPL as above, and also by using ``-m``:: 64 | 65 | $ ./micropython -m mip install pkgname-or-url 66 | $ ./micropython -m mip install pkgname-or-url@version 67 | 68 | The ``--target=path``, ``--no-mpy``, and ``--index`` arguments can be set:: 69 | 70 | $ ./micropython -m mip install --target=third-party pkgname 71 | $ ./micropython -m mip install --no-mpy pkgname 72 | $ ./micropython -m mip install --index https://host/pi pkgname 73 | 74 | Installing packages with ``mpremote`` 75 | ------------------------------------- 76 | 77 | The :term:`mpremote` tool also includes the same functionality as ``mip`` and 78 | can be used from a host PC to install packages to a locally connected device 79 | (e.g. via USB or UART):: 80 | 81 | $ mpremote mip install pkgname 82 | $ mpremote mip install pkgname@x.y 83 | $ mpremote mip install http://example.com/x/y/foo.py 84 | $ mpremote mip install github:org/repo 85 | $ mpremote mip install github:org/repo@branch-or-tag 86 | 87 | The ``--target=path``, ``--no-mpy``, and ``--index`` arguments can be set:: 88 | 89 | $ mpremote mip install --target=/flash/third-party pkgname 90 | $ mpremote mip install --no-mpy pkgname 91 | $ mpremote mip install --index https://host/pi pkgname 92 | 93 | Installing packages manually 94 | ---------------------------- 95 | 96 | Packages can also be installed (in either .py or .mpy form) by manually copying 97 | the files to the device. Depending on the board this might be via USB Mass Storage, 98 | the :term:`mpremote` tool (e.g. ``mpremote fs cp path/to/package.py :package.py``) 99 | 100 | Writing & publishing packages 101 | ----------------------------- 102 | 103 | Publishing to :term:`micropython-lib` is the easiest way to make your package 104 | broadly accessible to MicroPython users, and automatically available via 105 | ``mip`` and ``mpremote`` and compiled to bytecode. See 106 | https://github.com/micropython/micropython-lib for more information. 107 | 108 | To write a "self-hosted" package that can be downloaded by ``mip`` or 109 | ``mpremote``, you need a static webserver (or GitHub) to host either a 110 | single .py file, or a ``package.json`` file alongside your .py files. 111 | 112 | A typical ``package.json`` for an example ``mlx90640`` library looks like:: 113 | 114 | { 115 | "urls": [ 116 | ["mlx90640/__init__.py", "github:org/micropython-mlx90640/mlx90640/__init__.py"], 117 | ["mlx90640/utils.py", "github:org/micropython-mlx90640/mlx90640/utils.py"] 118 | ], 119 | "deps": [ 120 | ["collections-defaultdict", "latest"], 121 | ["os-path", "latest"], 122 | ["github:org/micropython-additions", "main"] 123 | ], 124 | "version": "0.2" 125 | } 126 | 127 | This includes two files, hosted at a GitHub repo named 128 | ``org/micropython-mlx90640``, which install into the ``mlx90640`` directory on 129 | the device. It depends on ``collections-defaultdict`` and ``os-path`` which will 130 | be installed automatically from the :term:`micropython-lib`. The third 131 | dependency installs the content as defined by the ``package.json`` file of the 132 | ``main`` branch of the GitHub repo ``org/micropython-additions``. 133 | 134 | Freezing packages 135 | ----------------- 136 | 137 | When a Python module or package is imported from the device filesystem, it is 138 | compiled into :term:`bytecode` in RAM, ready to be executed by the VM. For 139 | a :term:`.mpy file`, this conversion has been done already, but the bytecode 140 | still ends up in RAM. 141 | 142 | For low-memory devices, or for large applications, it can be advantageous to 143 | instead run the bytecode from ROM (i.e. flash memory). This can be done 144 | by "freezing" the bytecode into the MicroPython firmware, which is then flashed 145 | to the device. The runtime performance is the same (although importing is 146 | faster), but it can free up significant amounts of RAM for your program to 147 | use. 148 | 149 | The downside of this approach is that it's much slower to develop, because you 150 | have to flash the firmware each time, but it can be still useful to freeze 151 | dependencies that don't change often. 152 | 153 | Freezing is done by writing a manifest file and using it in the build, often as 154 | part of a custom board definition. See the :ref:`manifest` guide for more 155 | information. 156 | -------------------------------------------------------------------------------- /docs/reference/pyboard.py.rst: -------------------------------------------------------------------------------- 1 | .. _pyboard_py: 2 | 3 | The pyboard.py tool 4 | =================== 5 | 6 | This is a standalone Python tool that runs on your PC that provides a way to: 7 | 8 | * Quickly run a Python script or command on a MicroPython device. This is useful 9 | while developing MicroPython programs to quickly test code without needing to 10 | copy files to/from the device. 11 | 12 | * Access the filesystem on a device. This allows you to deploy your code to the 13 | device (even if the board doesn't support USB MSC). 14 | 15 | Despite the name, ``pyboard.py`` works on all MicroPython ports that support the 16 | raw REPL (including STM32, ESP32, ESP8266, NRF). 17 | 18 | You can download the latest version from `GitHub 19 | `_. The 20 | only dependency is the ``pyserial`` library which can be installed from PiPy or 21 | your system package manager. 22 | 23 | Running ``pyboard.py --help`` gives the following output: 24 | 25 | .. code-block:: text 26 | 27 | usage: pyboard [-h] [-d DEVICE] [-b BAUDRATE] [-u USER] [-p PASSWORD] 28 | [-c COMMAND] [-w WAIT] [--follow | --no-follow] [-f] 29 | [files [files ...]] 30 | 31 | Run scripts on the pyboard. 32 | 33 | positional arguments: 34 | files input files 35 | 36 | optional arguments: 37 | -h, --help show this help message and exit 38 | -d DEVICE, --device DEVICE 39 | the serial device or the IP address of the pyboard 40 | -b BAUDRATE, --baudrate BAUDRATE 41 | the baud rate of the serial device 42 | -u USER, --user USER the telnet login username 43 | -p PASSWORD, --password PASSWORD 44 | the telnet login password 45 | -c COMMAND, --command COMMAND 46 | program passed in as string 47 | -w WAIT, --wait WAIT seconds to wait for USB connected board to become 48 | available 49 | --follow follow the output after running the scripts 50 | [default if no scripts given] 51 | -f, --filesystem perform a filesystem action: cp local :device | cp 52 | :device local | cat path | ls [path] | rm path | mkdir 53 | path | rmdir path 54 | 55 | Running a command on the device 56 | ------------------------------- 57 | 58 | This is useful for testing short snippets of code, or to script an interaction 59 | with the device.:: 60 | 61 | $ pyboard.py --device /dev/ttyACM0 -c 'print(1+1)' 62 | 2 63 | 64 | If you are often interacting with the same device, you can set the environment 65 | variable ``PYBOARD_DEVICE`` as an alternative to using the ``--device`` 66 | command line option. For example, the following is equivalent to the previous 67 | example:: 68 | 69 | $ export PYBOARD_DEVICE=/dev/ttyACM0 70 | $ pyboard.py -c 'print(1+1)' 71 | 72 | Similarly, the ``PYBOARD_BAUDRATE`` environment variable can be used 73 | to set the default for the ``--baudrate`` option. 74 | 75 | Running a script on the device 76 | ------------------------------ 77 | 78 | If you have a script, ``app.py`` that you want to run on a device, then use:: 79 | 80 | $ pyboard.py --device /dev/ttyACM0 app.py 81 | 82 | Note that this doesn't actually copy app.py to the device's filesystem, it just 83 | loads the code into RAM and executes it. Any output generated by the program 84 | will be displayed. 85 | 86 | If the program app.py does not finish then you'll need to stop ``pyboard.py``, 87 | eg with Ctrl-C. The program ``app.py`` will still continue to run on the 88 | MicroPython device. 89 | 90 | Filesystem access 91 | ----------------- 92 | 93 | Using the ``-f`` flag, the following filesystem operations are supported: 94 | 95 | * ``cat path`` Print the contents of a file on the device. 96 | * ``cp src [src...] dest`` Copy files to/from the device. 97 | * ``ls [path]`` List contents of a directory (defaults to current working directory). 98 | * ``mkdir path`` Create a directory. 99 | * ``rm path`` Remove a file. 100 | * ``rmdir path`` Remove a directory. 101 | * ``touch path`` Create a file if it doesn't already exist. 102 | 103 | The ``cp`` command uses a ``ssh``-like convention for referring to local and 104 | remote files. Any path starting with a ``:`` will be interpreted as on the 105 | device, otherwise it will be local. So:: 106 | 107 | $ pyboard.py --device /dev/ttyACM0 -f cp main.py :main.py 108 | 109 | will copy main.py from the current directory on the PC to a file named main.py 110 | on the device. The filename can be omitted, e.g.:: 111 | 112 | $ pyboard.py --device /dev/ttyACM0 -f cp main.py : 113 | 114 | is equivalent to the above. 115 | 116 | Some more examples:: 117 | 118 | # Copy main.py from the device to the local PC. 119 | $ pyboard.py --device /dev/ttyACM0 -f cp :main.py main.py 120 | # Same, but using . instead. 121 | $ pyboard.py --device /dev/ttyACM0 -f cp :main.py . 122 | 123 | # Copy three files to the device, keeping their names 124 | # and paths (note: `lib` must exist on the device) 125 | $ pyboard.py --device /dev/ttyACM0 -f cp main.py app.py lib/foo.py : 126 | 127 | # Remove a file from the device. 128 | $ pyboard.py --device /dev/ttyACM0 -f rm util.py 129 | 130 | # Print the contents of a file on the device. 131 | $ pyboard.py --device /dev/ttyACM0 -f cat boot.py 132 | ...contents of boot.py... 133 | 134 | Using the pyboard library 135 | ------------------------- 136 | 137 | You can also use ``pyboard.py`` as a library for scripting interactions with a 138 | MicroPython board. 139 | 140 | .. code-block:: python 141 | 142 | import pyboard 143 | pyb = pyboard.Pyboard('/dev/ttyACM0', 115200) 144 | pyb.enter_raw_repl() 145 | ret = pyb.exec('print(1+1)') 146 | print(ret) 147 | pyb.exit_raw_repl() 148 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | sphinx~=7.2.6 2 | sphinxcontrib.jquery==4.1 3 | -------------------------------------------------------------------------------- /docs/static/custom.css: -------------------------------------------------------------------------------- 1 | /* Workaround to force Sphinx to render tables to 100% and wordwrap */ 2 | /* See https://stackoverflow.com/questions/69359978/grid-table-does-not-word-wrap for more details */ 3 | .wy-table-responsive table td, .wy-table-responsive table th { 4 | white-space: inherit; 5 | } 6 | -------------------------------------------------------------------------------- /docs/static/customstyle.css: -------------------------------------------------------------------------------- 1 | /* custom CSS for MicroPython docs 2 | */ 3 | 4 | .admonition-difference-to-cpython { 5 | border: 1px solid black; 6 | } 7 | 8 | .admonition-difference-to-cpython .admonition-title { 9 | margin: 4px; 10 | } 11 | -------------------------------------------------------------------------------- /docs/static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CyberBrick-Official/CyberBrick_Controller_Core/b5fc07d44d65143cfef1164ae6234099fcb11d62/docs/static/favicon.ico -------------------------------------------------------------------------------- /docs/templates/layout.html: -------------------------------------------------------------------------------- 1 | {% extends "!layout.html" %} 2 | {% set css_files = css_files + ["_static/customstyle.css"] %} 3 | 4 | {# we change the master_doc variable so that links to the index 5 | page are to index.html instead of _index.html #} 6 | {% set master_doc = "index" %} 7 | 8 | {% block document %} 9 |
10 |

11 | This documentation is adapted from the official MicroPython project. 12 | The CyberBrick team has extended the source code with custom interfaces 13 | and features to our hardware and application needs. 14 |

15 |

16 | In addition to these enhancements, certain built-in MicroPython interfaces have been 17 | intentionally disabled to protect the system's integrity, and ensure the overall security and reliability of the device. 18 | This also facilitates content protection for creators' intellectual property, where applicable. 19 |

20 |

21 | Portions of the content are derived from the official MicroPython documentation and 22 | have been included here under its open-source license to provide users with a consistent 23 | and enriched development experience tailored to the CyberBrick platform. 24 |

25 |
26 | {{ super() }} 27 | {% endblock %} 28 | -------------------------------------------------------------------------------- /docs/templates/replace.inc: -------------------------------------------------------------------------------- 1 | .. comment: This file is intended for global "replace" definitions. 2 | 3 | .. |see_cpython| replace:: See CPython documentation: 4 | 5 | .. |see_cpython_module| replace:: 6 | 7 | *This module implements a subset of the corresponding* :term:`CPython` *module, 8 | as described below. For more information, refer to the original 9 | CPython documentation:* 10 | -------------------------------------------------------------------------------- /docs/templates/topindex.html: -------------------------------------------------------------------------------- 1 | {% extends "layout.html" %} 2 | {% set title = _('Overview') %} 3 | {% block body %} 4 | 5 |

MicroPython documentation

6 | 7 |

8 | {{ _('Welcome! This is the documentation for MicroPython') }}{% if last_updated %}, {{ _('last updated') }} {{ last_updated|e }}{% endif %}. 9 |

10 | 11 |

12 | MicroPython runs on a variety of systems and hardware platforms. Here you can read 13 | the general documentation which applies to all systems, as well as specific information 14 | about the various platforms - 15 | also known as ports 16 | - that MicroPython runs on. 17 |

18 | 19 |

General documentation for MicroPython:

20 | 21 | 22 | 32 | 38 |
23 | 27 | 31 | 33 | 37 |
39 | 40 |

References and tutorials for specific platforms:

41 | 42 | 43 | 49 |
44 | 48 |
50 | 51 |

Indices and tables:

52 | 53 | 54 | 64 | 74 |
55 | 59 | 63 | 65 | 69 | 73 |
75 | 76 |

External links:

77 | 78 | 79 | 89 | 95 |
80 | 84 | 88 | 90 | 94 |
96 | 97 | {% endblock %} 98 | -------------------------------------------------------------------------------- /docs/templates/versions.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | Versions and Downloads 4 | {{ cur_version }} 5 | 6 | 7 |
8 |
9 |
Versions
10 | {% for slug, url in all_versions %} 11 |
{{ slug }}
12 | {% endfor %} 13 |
14 |
15 |
Downloads
16 | {% for type, url in downloads %} 17 |
{{ type }}
18 | {% endfor %} 19 |
20 |
21 |
22 |
External links
23 |
24 | micropython.org 25 |
26 |
27 | GitHub 28 |
29 |
30 |
31 |
32 | -------------------------------------------------------------------------------- /src/app_rc/app/devices.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | # 3 | # The CyberBrick Codebase License, see the file LICENSE for details. 4 | # 5 | # Copyright (c) 2025 MakerWorld 6 | # 7 | 8 | __all__ = ["Devices"] 9 | 10 | 11 | class Devices: 12 | MOTOR_1 = 1 13 | MOTOR_2 = 2 14 | LED_1 = 3 15 | LED_2 = 4 16 | PWM_1 = 5 17 | PWM_2 = 6 18 | PWM_3 = 7 19 | PWM_4 = 8 20 | BUZZER_1 = 9 21 | BUZZER_2 = 10 22 | CODE_EXEC = 11 23 | 24 | _max_value = max(v for k, v in locals().items() if isinstance(v, int)) 25 | 26 | _base_multiplier = 10 ** len(str(_max_value)) 27 | 28 | @classmethod 29 | def get_base_multiplier(cls): 30 | return cls._base_multiplier 31 | 32 | 33 | if __name__ == '__main__': 34 | print(Devices.get_base_multiplier()) # 14us 35 | -------------------------------------------------------------------------------- /src/app_rc/app/rc_main.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | # 3 | # The CyberBrick Codebase License, see the file LICENSE for details. 4 | # 5 | # Copyright (c) 2025 MakerWorld 6 | # 7 | 8 | import sys 9 | import machine 10 | import uasyncio 11 | import time 12 | import ulogger 13 | 14 | sys.path.append("/app") 15 | if '.frozen' in sys.path: 16 | sys.path.remove('.frozen') 17 | sys.path.append('.frozen') 18 | 19 | 20 | async def master_init(): 21 | import rc_module 22 | 23 | logger = ulogger.Logger() 24 | logger.info("[MAIN]MASTER INIT.") 25 | 26 | if rc_module.rc_master_init() is False: 27 | return 28 | 29 | async def rc_task(): 30 | while True: 31 | rc_module.file_transfer() 32 | await uasyncio.sleep(1) 33 | 34 | await uasyncio.gather(rc_task()) 35 | 36 | 37 | conf_updata_flag = True 38 | 39 | 40 | async def slave_init(): 41 | import rc_module 42 | import gc 43 | import ujson 44 | 45 | logger = ulogger.Logger() 46 | logger.info("[MAIN]SLAVE INIT.") 47 | 48 | if rc_module.rc_slave_init() is False: 49 | return 50 | 51 | from control import BBL_Controller 52 | from parser import DataParser 53 | gc.collect() 54 | 55 | data_parser = DataParser() 56 | bbl_controller = BBL_Controller() 57 | 58 | async def period_task(): 59 | global conf_updata_flag 60 | 61 | while True: 62 | updata_flag = rc_module.file_transfer() 63 | if updata_flag is True: 64 | logger.info("[MAIN]CONFIG UPDATE. ") 65 | conf_updata_flag = True 66 | 67 | await uasyncio.sleep(0.5) 68 | 69 | async def control_task(): 70 | EMPTY_DATA = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 71 | global conf_updata_flag 72 | setting = None 73 | rc_index = 0 74 | 75 | while True: 76 | try: 77 | if conf_updata_flag is True: 78 | # Free memory before load file. 79 | conf_updata_flag = False 80 | bbl_controller.reinit() 81 | rc_conf = None 82 | setting = None 83 | gc.collect() 84 | 85 | try: 86 | with open('rc_config', 'r') as f: 87 | rc_conf = ujson.load(f) 88 | gc.collect() 89 | except Exception as e: 90 | logger.warn(f"[MAIN]CFG LOAD ERR:{e}.") 91 | gc.collect() 92 | 93 | rc_index = rc_module.rc_index() 94 | data_parser.set_slave_idx(rc_index) 95 | if rc_conf is not None: 96 | setting = data_parser.parse(rc_conf) 97 | del rc_conf 98 | gc.collect() 99 | 100 | logger.info(f"[MAIN]PRASE UPDATE: {rc_index}") 101 | bbl_controller.reinit() 102 | 103 | rc_data = rc_module.rc_slave_data() 104 | data_parser.set_slave_idx(rc_index) 105 | 106 | if rc_index != rc_module.rc_index(): 107 | # Must update config 108 | conf_updata_flag = True 109 | continue 110 | 111 | if rc_data and setting and rc_data != EMPTY_DATA: 112 | bbl_controller.handler(setting, rc_index, rc_data) 113 | else: 114 | bbl_controller.stop('BEHAVIOR') 115 | except Exception as e: 116 | bbl_controller.reinit() 117 | logger.error(f"[MAIN]CRTL TASK: {e}") 118 | machine.reset() 119 | bbl_controller.board_key_handler() 120 | await uasyncio.sleep(0.02) 121 | 122 | async def simulation_task(): 123 | while True: 124 | try: 125 | sim_case = rc_module.rc_simulation() 126 | if sim_case: 127 | try: 128 | sim_case = ujson.loads(sim_case) 129 | except Exception as e: 130 | logger.error(f"[MIAN][SIM_LOADS] {e}") 131 | continue 132 | setting = data_parser.parse_simulation_setting(sim_case) 133 | value = data_parser.parse_simulation_value(sim_case) 134 | idx = data_parser.parse_simulation_receiver(sim_case) 135 | sim_case = None 136 | gc.collect() 137 | bbl_controller.simulation_effect_set(idx, setting, value) 138 | bbl_controller.simulation_effect_handle() 139 | except Exception as e: 140 | bbl_controller.reinit() 141 | logger.error(f"[MAIN]SIM TASK: {e}") 142 | machine.reset() 143 | await uasyncio.sleep(0.02) 144 | 145 | await uasyncio.gather(control_task(), 146 | period_task(), 147 | simulation_task(), 148 | bbl_controller.executor_handle()) 149 | 150 | 151 | class Clock(ulogger.BaseClock): 152 | def __init__(self): 153 | self.start = time.time() 154 | 155 | def __call__(self) -> str: 156 | inv = time.time() - self.start 157 | return '%d' % (inv) 158 | 159 | 160 | if __name__ == "__main__": 161 | from machine import Pin 162 | 163 | rst_c = machine.reset_cause() 164 | log_clock = Clock() 165 | 166 | log_handler_to_term = ulogger.Handler( 167 | level=ulogger.INFO, 168 | colorful=True, 169 | fmt="&(time)%-&(level)%-&(msg)%", 170 | clock=log_clock, 171 | direction=ulogger.TO_TERM, 172 | ) 173 | 174 | log_handler_to_file = ulogger.Handler( 175 | level=ulogger.INFO, 176 | fmt="&(time)%-&(level)%-&(msg)%", 177 | clock=log_clock, 178 | direction=ulogger.TO_FILE, 179 | file_name="./log/logging", 180 | index_file_name="./log/log_index.txt", 181 | max_file_size=10240 182 | ) 183 | 184 | logger = ulogger.Logger(name=__name__, 185 | handlers=( 186 | log_handler_to_term, 187 | log_handler_to_file)) 188 | 189 | rc2str = { 190 | getattr(machine, i): i 191 | for i in ('PWRON_RESET', 192 | 'HARD_RESET', 193 | 'WDT_RESET', 194 | 'DEEPSLEEP_RESET', 195 | 'SOFT_RESET') 196 | } 197 | 198 | logger.info("[MAIN]{}".format(rc2str.get(rst_c, str(rst_c)))) 199 | 200 | # Check the role pin to determine if this is the master or slave instance 201 | role_pin = Pin(10, Pin.IN) 202 | if role_pin.value(): 203 | uasyncio.run(master_init()) 204 | else: 205 | uasyncio.run(slave_init()) 206 | -------------------------------------------------------------------------------- /src/app_rc/bbl/__init__.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | # 3 | # The CyberBrick Codebase License, see the file LICENSE for details. 4 | # 5 | # Copyright (c) 2025 MakerWorld 6 | # 7 | 8 | from .leds import LEDController 9 | from .servos import ServosController 10 | from .motors import MotorsController 11 | from .buzzer import MusicController 12 | from .executor import CommandExecutor 13 | 14 | __all__ = ["LEDController", 15 | "ServosController", 16 | "MotorsController", 17 | "MusicController", 18 | "CommandExecutor"] 19 | -------------------------------------------------------------------------------- /src/app_rc/boot.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | # 3 | # The CyberBrick Codebase License, see the file LICENSE for details. 4 | # 5 | # Copyright (c) 2025 MakerWorld 6 | # 7 | # This file is executed on every boot (including wake-boot from deepsleep) 8 | 9 | import bbl_product 10 | import gc 11 | 12 | _PRODUCT_NAME = "RC" 13 | _PRODUCT_VERSION = "01.00.00.13" 14 | 15 | bbl_product.set_app_name(_PRODUCT_NAME) 16 | bbl_product.set_app_version(_PRODUCT_VERSION) 17 | del bbl_product 18 | 19 | gc.collect() 20 | 21 | exec(open('./app/rc_main.py').read(), globals()) 22 | -------------------------------------------------------------------------------- /src/app_timelapse/boot.py: -------------------------------------------------------------------------------- 1 | # -*-coding:utf-8-*- 2 | # 3 | # The CyberBrick Codebase License, see the file LICENSE for details. 4 | # 5 | # Copyright (c) 2025 MakerWorld 6 | # 7 | # This file is executed on every boot (including wake-boot from deepsleep) 8 | 9 | import bbl_product 10 | import ble_module 11 | import shutter_module 12 | 13 | _PRODUCT_NAME = "SHUTTER" 14 | _PRODUCT_VERSION = "01.00.00.01" 15 | 16 | bbl_product.set_app_name(_PRODUCT_NAME) 17 | bbl_product.set_app_version(_PRODUCT_VERSION) 18 | del bbl_product 19 | 20 | shutter_module.shutter_init() 21 | ble_module.ble_shutter_init() 22 | shutter_module.shutter_task_init() 23 | -------------------------------------------------------------------------------- /tools/HapticOpti_speed_curve.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | # 4 | # The CyberBrick Codebase License, see the file LICENSE for details. 5 | # 6 | # Copyright (c) 2025 MakerWorld 7 | # 8 | 9 | import numpy as np 10 | import matplotlib.pyplot as plt 11 | 12 | _Acceleration = 1.45 13 | _Low_Speed_Zone = 60 # (%) 14 | _Dead_Zone_Width = 200 15 | 16 | def adc_value_deal(x, max=4096, mid= 2000, dz=200): 17 | def convert(x, i_min, i_max, o_min, o_max): 18 | return (x - i_min) * (o_max - o_min) / (i_max - i_min) + o_min 19 | 20 | if mid-dz <= x <= mid+dz: 21 | return 0 22 | 23 | m_mid = max / 2 24 | 25 | if x <= mid: 26 | x = convert(x, 0, mid-dz, -m_mid, 0) 27 | elif x > mid: 28 | x = convert(x, mid + dz, max, 0, m_mid) 29 | return x 30 | 31 | 32 | def _low_speed_map(value, start, end, rate): 33 | if value <= start+1: 34 | return 0 35 | elif value >= end: 36 | return 2047 37 | 38 | mapped_value = rate*((value - start) ** 2) / (2 * (end - start)) 39 | # mapped_value = rate * math.log(value - start) * (end - start) 40 | return int(mapped_value) 41 | 42 | 43 | def nonlinear_map(set_speed, dead_zone=0, low_speed_percentage=0.3, linear_rate=1.18): 44 | THRESHOLD = 2047 45 | speed = abs(set_speed) 46 | if (speed) < dead_zone: 47 | return 0 48 | if speed > THRESHOLD: 49 | speed = THRESHOLD 50 | 51 | low_speed_threshold = dead_zone + (2048 - 2 * dead_zone) * low_speed_percentage 52 | 53 | tracker_speed = _low_speed_map(min(speed, low_speed_threshold - 1), dead_zone, low_speed_threshold, linear_rate) 54 | if speed >= low_speed_threshold: 55 | tracker_speed = tracker_speed + (speed - low_speed_threshold) * linear_rate 56 | 57 | tracker_speed = min(tracker_speed, THRESHOLD) 58 | return int(tracker_speed if set_speed >= 0 else -tracker_speed ) 59 | 60 | 61 | if 1: 62 | set_speeds = np.arange(-2047, 2048, 0.1) 63 | tracker_speeds = [nonlinear_map(speed, dead_zone=_Dead_Zone_Width, low_speed_percentage=_Low_Speed_Zone/100, linear_rate=_Acceleration) for speed in set_speeds] 64 | else: 65 | set_speeds = np.arange(0, 4096, 0.1) 66 | tracker_speeds = [adc_value_deal(speed) for speed in set_speeds] 67 | 68 | 69 | plt.figure(figsize=(10, 5)) 70 | plt.plot(set_speeds, tracker_speeds, label='Nonlinear Mapping') 71 | plt.title('Nonlinear Mapping of Motor Speed') 72 | plt.xlabel('Set Speed (motor1_set_speed)') 73 | plt.ylabel('Tracker Speed (motor1_tracker_speed)') 74 | plt.axhline(0, color='black',linewidth=0.5) 75 | plt.axvline(0, color='black',linewidth=0.5) 76 | plt.grid(color = 'gray', linestyle = '--', linewidth = 0.5) 77 | plt.legend() 78 | plt.show() 79 | -------------------------------------------------------------------------------- /tools/HapticOpti_time2speed_curve.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding=utf-8 3 | # 4 | # The CyberBrick Codebase License, see the file LICENSE for details. 5 | # 6 | # Copyright (c) 2025 MakerWorld 7 | # 8 | 9 | import time 10 | import matplotlib.pyplot as plt 11 | import numpy as np 12 | import math 13 | 14 | _High_Speed_Zone = 40 # (%) 15 | _High_Speed_Zone_Time = 1.0 16 | 17 | def sigmoid(x): 18 | return 1 / (1 + math.exp(-x)) 19 | 20 | 21 | def _high_speed_map(current_speed, target_speed, elapsed_time, total_time=2.0, cycle_time=0.02): 22 | remaining_time = total_time - elapsed_time 23 | 24 | c_speed = abs(current_speed) 25 | t_speed = abs(target_speed) 26 | 27 | if remaining_time < cycle_time: 28 | return target_speed 29 | 30 | if t_speed <= c_speed: 31 | return target_speed 32 | 33 | speed_change_rate = (t_speed - c_speed) / remaining_time 34 | 35 | speed_change_this_cycle = speed_change_rate * cycle_time 36 | 37 | new_speed = c_speed + speed_change_this_cycle 38 | return new_speed if target_speed >= 0 else -new_speed 39 | 40 | 41 | current_speed = 0 42 | target_speed = 0 43 | elapsed_time = 0 44 | cycle_time = 0.02 45 | zone_time = _High_Speed_Zone_Time 46 | total_time = 10 47 | 48 | table_time = 0 49 | 50 | last_tar_speed = 0 51 | last_updata_tar_speed = 0 52 | updata_tar_speed_threadhold = 200 53 | 54 | times = [] 55 | speeds = [] 56 | target_speeds = [] 57 | 58 | while table_time < total_time: 59 | # target_speed += random.uniform(-25, 25) 60 | threahold = 2048 61 | target_speed = 0 + threahold * 6 * np.sin(table_time *2) 62 | if abs(target_speed) > threahold: 63 | target_speed = threahold if target_speed >= 0 else -threahold 64 | target_speeds.append(target_speed) 65 | 66 | # core start 67 | if abs(last_tar_speed - target_speed) > updata_tar_speed_threadhold or elapsed_time > zone_time: 68 | elapsed_time = 0 69 | 70 | if (abs(target_speed) > 2048 * (1 - _High_Speed_Zone / 100.0)): 71 | current_speed = _high_speed_map(current_speed, target_speed, elapsed_time, zone_time, cycle_time) 72 | else : 73 | current_speed = target_speed 74 | 75 | if abs(current_speed) - abs(target_speed) >= 0: 76 | elapsed_time = 0 77 | 78 | last_tar_speed = target_speed 79 | elapsed_time += cycle_time 80 | #core end 81 | 82 | times.append(table_time) 83 | speeds.append(current_speed) 84 | table_time += cycle_time 85 | time.sleep(cycle_time) 86 | 87 | plt.figure(figsize=(10, 6)) 88 | plt.plot(times, speeds, label='Actual Speed', color='blue') 89 | plt.plot(times, target_speeds, label='Target Speed', color='red',linestyle='--') 90 | 91 | plt.xlabel('Time (s)') 92 | plt.ylabel('Speed') 93 | plt.title('Speed Ramp-up Over Time with Target Adjustments') 94 | plt.legend() 95 | plt.grid(True) 96 | plt.show() 97 | -------------------------------------------------------------------------------- /tools/README.md: -------------------------------------------------------------------------------- 1 | # Tools 2 | ------- 3 | 4 | ## How to use 5 | ------------- 6 | 7 | ### HapticOpti_speed_curve.py 8 | 9 | Installation environment dependency: 10 | 11 | $ pip install -r requirements.txt 12 | 13 | Run the HapticOpti_stpeed_curve.py file, and you will see the curve of the input speed of the RC remote control stick. 14 | 15 | $ python ./HapticOpti_speed_curve.py 16 | 17 | According to the parameters of Haptic Optimization, modify the _Acceleration, _Low_Speed_Zone, _Dead_Zone_Width in the source code, Re run to obtain custom curves. 18 | 19 | ### HapticOpti_time2speed_curve.py 20 | 21 | Run the HapticOpti_stpeed_curve.py file, and you will see the motor's high-speed zone time mapped speed curve. 22 | 23 | $ python ./HapticOpti_time2speed_curve.py 24 | 25 | Similarly to the above content, you can modify the values of _High_Speed_Zone and _High_Speed_Zone_Time based on the parameters in Haptic Optimization. 26 | -------------------------------------------------------------------------------- /tools/requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CyberBrick-Official/CyberBrick_Controller_Core/b5fc07d44d65143cfef1164ae6234099fcb11d62/tools/requirements.txt --------------------------------------------------------------------------------