Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • 9Rmain
  • anon/gpndemo
  • anon/update-sim
  • anon/webflasher
  • audio_input
  • audio_io
  • bl00mbox
  • bl00mbox_old
  • captouch-threshold
  • ch3/bl00mbox_docs
  • ci-1690580595
  • compressor
  • dev_p4
  • dev_p4-iggy
  • dev_p4-iggy-rebased
  • dos
  • dos-main-patch-50543
  • events
  • fm_fix
  • fm_fix2
  • fpletz/flake
  • history-rewrite
  • icon-flower
  • iggy/stemming
  • iggy/stemming_merge
  • json-error
  • main
  • main+schneider
  • media-buf
  • micropython_api
  • moon2_applications
  • moon2_demo_temp
  • moon2_gay_drums
  • passthrough
  • phhw
  • pippin/display-python-errors-on-display
  • pippin/make_empty_drawlists_skip_render_and_blit
  • pippin/media_framework
  • pippin/uhm_flash_access_bust
  • pressable_bugfix
  • q3k/doom-poc
  • rahix/big-flow3r
  • rahix/flow3rseeds
  • raw_captouch_new
  • raw_captouch_old
  • release/1.0.0
  • release/1.1.0
  • release/1.1.1
  • rev4_micropython
  • schneider/application-remove-name
  • schneider/bhi581
  • schneider/factory_test
  • schneider/recovery
  • scope
  • scope_hack
  • sdkconfig-spiram-tinyusb
  • sec/auto-nick
  • sec/blinky
  • simtest
  • slewtest
  • t
  • test
  • test2
  • uctx-wip
  • view-think
  • vm-pending
  • vsync
  • wave
  • wip-docs
  • wip-tinyusb
  • v1.0.0
  • v1.0.0+rc1
  • v1.0.0+rc2
  • v1.0.0+rc3
  • v1.0.0+rc4
  • v1.0.0+rc5
  • v1.0.0+rc6
  • v1.1.0
  • v1.1.0+rc1
  • v1.1.1
  • v1.2.0
  • v1.2.0+rc1
  • v1.3.0
83 results

Target

Select target project
  • flow3r/flow3r-firmware
  • Vespasian/flow3r-firmware
  • alxndr42/flow3r-firmware
  • pl/flow3r-firmware
  • Kari/flow3r-firmware
  • raimue/flow3r-firmware
  • grandchild/flow3r-firmware
  • mu5tach3/flow3r-firmware
  • Nervengift/flow3r-firmware
  • arachnist/flow3r-firmware
  • TheNewCivilian/flow3r-firmware
  • alibi/flow3r-firmware
  • manuel_v/flow3r-firmware
  • xeniter/flow3r-firmware
  • maxbachmann/flow3r-firmware
  • yGifoom/flow3r-firmware
  • istobic/flow3r-firmware
  • EiNSTeiN_/flow3r-firmware
  • gnudalf/flow3r-firmware
  • 999eagle/flow3r-firmware
  • toerb/flow3r-firmware
  • pandark/flow3r-firmware
  • teal/flow3r-firmware
  • x42/flow3r-firmware
  • alufers/flow3r-firmware
  • dos/flow3r-firmware
  • yrlf/flow3r-firmware
  • LuKaRo/flow3r-firmware
  • ThomasElRubio/flow3r-firmware
  • ai/flow3r-firmware
  • T_X/flow3r-firmware
  • highTower/flow3r-firmware
  • beanieboi/flow3r-firmware
  • Woazboat/flow3r-firmware
  • gooniesbro/flow3r-firmware
  • marvino/flow3r-firmware
  • kressnerd/flow3r-firmware
  • quazgar/flow3r-firmware
  • aoid/flow3r-firmware
  • jkj/flow3r-firmware
  • naomi/flow3r-firmware
41 results
Select Git revision
  • 89-apps-should-be-able-to-specify-if-they-want-wifi-to-be-disabled-when-entering-them
  • 9Rmain
  • allow-reloading-sunmenu
  • always-have-a-wifi-instance
  • anon/gpndemo
  • anon/update-sim
  • anon/webflasher
  • app_text_viewer
  • audio_input
  • audio_io
  • blm_dev_chan
  • ch3/bl00mbox_docs
  • ci-1690580595
  • dev_p4
  • dev_p4-iggy
  • dev_p4-iggy-rebased
  • dx/dldldld
  • dx/fb-save-restore
  • dx/hint-hint
  • dx/jacksense-headset-mic-only
  • events
  • fil3s-limit-filesize
  • fil3s-media
  • fpletz/flake
  • gr33nhouse-improvements
  • history-rewrite
  • icon-flower
  • iggy/stemming
  • iggy/stemming_merge
  • led_fix_fix
  • main
  • main+schneider
  • media_has_video_has_audio
  • micropython_api
  • mixer2
  • moon2_demo_temp
  • moon2_migrate_apps
  • more-accurate-battery
  • pippin/ctx_sprite_sheet_support
  • pippin/display-python-errors-on-display
  • pippin/make_empty_drawlists_skip_render_and_blit
  • pippin/more-accurate-battery
  • pippin/tcp_redirect_hack
  • pippin/tune_ctx_config_update_from_upstream
  • pippin/uhm_flash_access_bust
  • pressable_bugfix
  • py_only_update_fps_overlay_when_changing
  • q3k/doom-poc
  • q3k/render-to-texture
  • rahix/flow3rseeds
  • raw_captouch_new
  • raw_captouch_old
  • release/1.0.0
  • release/1.1.0
  • release/1.1.1
  • release/1.2.0
  • release/1.3.0
  • release/1.4.0
  • restore_blit
  • return_of_melodic_demo
  • rev4_micropython
  • schneider/application-remove-name
  • schneider/bhi581
  • schneider/factory_test
  • schneider/recovery
  • scope_hack
  • sdkconfig-spiram-tinyusb
  • sec/auto-nick
  • sec/blinky
  • sector_size_512
  • shoegaze-fps
  • smaller_gradient_lut
  • store_delta_ms_and_ins_as_class_members
  • task_cleanup
  • uctx-wip
  • w1f1-in-sim
  • widgets_draw
  • wifi-json-error-handling
  • wip-docs
  • wip-tinyusb
  • v1.0.0
  • v1.0.0+rc1
  • v1.0.0+rc2
  • v1.0.0+rc3
  • v1.0.0+rc4
  • v1.0.0+rc5
  • v1.0.0+rc6
  • v1.1.0
  • v1.1.0+rc1
  • v1.1.1
  • v1.2.0
  • v1.2.0+rc1
  • v1.3.0
  • v1.4.0
94 results
Show changes
Showing
with 2748 additions and 0 deletions
GPIO Pins
=========
The way to connect your board to the external world, and control other
components, is through the GPIO pins. Not all pins are available to use,
in most cases only pins 0, 2, 4, 5, 12, 13, 14, 15, and 16 can be used.
The pins are available in the machine module, so make sure you import that
first. Then you can create a pin using::
>>> pin = machine.Pin(0)
Here, the "0" is the pin that you want to access. Usually you want to
configure the pin to be input or output, and you do this when constructing
it. To make an input pin use::
>>> pin = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP)
You can either use PULL_UP or None for the input pull-mode. If it's
not specified then it defaults to None, which is no pull resistor. GPIO16
has no pull-up mode.
You can read the value on the pin using::
>>> pin.value()
0
The pin on your board may return 0 or 1 here, depending on what it's connected
to. To make an output pin use::
>>> pin = machine.Pin(0, machine.Pin.OUT)
Then set its value using::
>>> pin.value(0)
>>> pin.value(1)
Or::
>>> pin.off()
>>> pin.on()
External interrupts
-------------------
All pins except number 16 can be configured to trigger a hard interrupt if their
input changes. You can set code (a callback function) to be executed on the
trigger.
Let's first define a callback function, which must take a single argument,
being the pin that triggered the function. We will make the function just print
the pin::
>>> def callback(p):
... print('pin change', p)
Next we will create two pins and configure them as inputs::
>>> from machine import Pin
>>> p0 = Pin(0, Pin.IN)
>>> p2 = Pin(2, Pin.IN)
An finally we need to tell the pins when to trigger, and the function to call
when they detect an event::
>>> p0.irq(trigger=Pin.IRQ_FALLING, handler=callback)
>>> p2.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=callback)
We set pin 0 to trigger only on a falling edge of the input (when it goes from
high to low), and set pin 2 to trigger on both a rising and falling edge. After
entering this code you can apply high and low voltages to pins 0 and 2 to see
the interrupt being executed.
A hard interrupt will trigger as soon as the event occurs and will interrupt any
running code, including Python code. As such your callback functions are
limited in what they can do (they cannot allocate memory, for example) and
should be as short and simple as possible.
Power control
=============
The ESP8266 provides the ability to change the CPU frequency on the fly, and
enter a deep-sleep state. Both can be used to manage power consumption.
Changing the CPU frequency
--------------------------
The machine module has a function to get and set the CPU frequency. To get the
current frequency use::
>>> import machine
>>> machine.freq()
80000000
By default the CPU runs at 80MHz. It can be changed to 160MHz if you need more
processing power, at the expense of current consumption::
>>> machine.freq(160000000)
>>> machine.freq()
160000000
You can change to the higher frequency just while your code does the heavy
processing and then change back when it's finished.
Deep-sleep mode
---------------
The deep-sleep mode will shut down the ESP8266 and all its peripherals,
including the WiFi (but not including the real-time-clock, which is used to wake
the chip). This drastically reduces current consumption and is a good way to
make devices that can run for a while on a battery.
To be able to use the deep-sleep feature you must connect GPIO16 to the reset
pin (RST on the Adafruit Feather HUZZAH board). Then the following code can be
used to sleep and wake the device::
import machine
# configure RTC.ALARM0 to be able to wake the device
rtc = machine.RTC()
rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
# set RTC.ALARM0 to fire after 10 seconds (waking the device)
rtc.alarm(rtc.ALARM0, 10000)
# put the device to sleep
machine.deepsleep()
Note that when the chip wakes from a deep-sleep it is completely reset,
including all of the memory. The boot scripts will run as usual and you can
put code in them to check the reset cause to perhaps do something different if
the device just woke from a deep-sleep. For example, to print the reset cause
you can use::
if machine.reset_cause() == machine.DEEPSLEEP_RESET:
print('woke from a deep sleep')
else:
print('power on or hard reset')
Pulse Width Modulation
======================
Pulse width modulation (PWM) is a way to get an artificial analog output on a
digital pin. It achieves this by rapidly toggling the pin from low to high.
There are two parameters associated with this: the frequency of the toggling,
and the duty cycle. The duty cycle is defined to be how long the pin is high
compared with the length of a single period (low plus high time). Maximum
duty cycle is when the pin is high all of the time, and minimum is when it is
low all of the time.
On the ESP8266 the pins 0, 2, 4, 5, 12, 13, 14 and 15 all support PWM. The
limitation is that they must all be at the same frequency, and the frequency
must be between 1Hz and 1kHz.
To use PWM on a pin you must first create the pin object, for example::
>>> import machine
>>> p12 = machine.Pin(12)
Then create the PWM object using::
>>> pwm12 = machine.PWM(p12)
You can set the frequency and duty cycle using::
>>> pwm12.freq(500)
>>> pwm12.duty(512)
Note that the duty cycle is between 0 (all off) and 1023 (all on), with 512
being a 50% duty. Values beyond this min/max will be clipped. If you
print the PWM object then it will tell you its current configuration::
>>> pwm12
PWM(12, freq=500, duty=512)
You can also call the ``freq()`` and ``duty()`` methods with no arguments to
get their current values.
The pin will continue to be in PWM mode until you deinitialise it using::
>>> pwm12.deinit()
Fading an LED
-------------
Let's use the PWM feature to fade an LED. Assuming your board has an LED
connected to pin 2 (ESP-12 modules do) we can create an LED-PWM object using::
>>> led = machine.PWM(machine.Pin(2), freq=1000)
Notice that we can set the frequency in the PWM constructor.
For the next part we will use timing and some math, so import these modules::
>>> import time, math
Then create a function to pulse the LED::
>>> def pulse(l, t):
... for i in range(20):
... l.duty(int(math.sin(i / 10 * math.pi) * 500 + 500))
... time.sleep_ms(t)
You can try this function out using::
>>> pulse(led, 50)
For a nice effect you can pulse many times in a row::
>>> for i in range(10):
... pulse(led, 20)
Remember you can use ctrl-C to interrupt the code.
Control a hobby servo
---------------------
Hobby servo motors can be controlled using PWM. They require a frequency of
50Hz and then a duty between about 40 and 115, with 77 being the centre value.
If you connect a servo to the power and ground pins, and then the signal line
to pin 12 (other pins will work just as well), you can control the motor using::
>>> servo = machine.PWM(machine.Pin(12), freq=50)
>>> servo.duty(40)
>>> servo.duty(115)
>>> servo.duty(77)
Getting a MicroPython REPL prompt
=================================
REPL stands for Read Evaluate Print Loop, and is the name given to the
interactive MicroPython prompt that you can access on the ESP8266. Using the
REPL is by far the easiest way to test out your code and run commands.
There are two ways to access the REPL: either via a wired connection through the
UART serial port, or via WiFi.
REPL over the serial port
-------------------------
The REPL is always available on the UART0 serial peripheral, which is connected
to the pins GPIO1 for TX and GPIO3 for RX. The baudrate of the REPL is 115200.
If your board has a USB-serial convertor on it then you should be able to access
the REPL directly from your PC. Otherwise you will need to have a way of
communicating with the UART.
To access the prompt over USB-serial you need to use a terminal emulator program.
On Windows TeraTerm is a good choice, on Mac you can use the built-in ``screen``
program, and Linux has ``picocom`` and ``minicom``. Of course, there are many
other terminal programs that will work, so pick your favourite!
For example, on Linux you can try running::
picocom /dev/ttyUSB0 -b115200
Once you have made the connection over the serial port you can test if it is
working by hitting enter a few times. You should see the Python REPL prompt,
indicated by ``>>>``.
WebREPL - a prompt over WiFi
----------------------------
WebREPL allows you to use the Python prompt over WiFi, connecting through a
browser. The latest versions of Firefox and Chrome are supported.
For your convenience, WebREPL client is hosted at
`<http://micropython.org/webrepl>`__. Alternatively, you can install it
locally from the the GitHub repository
`<https://github.com/micropython/webrepl>`__.
Before connecting to WebREPL, you should set a password and enable it via
a normal serial connection. Initial versions of MicroPython for ESP8266
came with WebREPL automatically enabled on the boot and with the
ability to set a password via WiFi on the first connection, but as WebREPL
was becoming more widely known and popular, the initial setup has switched
to a wired connection for improved security::
import webrepl_setup
Follow the on-screen instructions and prompts. To make any changes active,
you will need to reboot your device.
To use WebREPL connect your computer to the ESP8266's access point
(MicroPython-xxxxxx, see the previous section about this). If you have
already reconfigured your ESP8266 to connect to a router then you can
skip this part.
Once you are on the same network as the ESP8266 you click the "Connect" button
(if you are connecting via a router then you may need to change the IP address,
by default the IP address is correct when connected to the ESP8266's access
point). If the connection succeeds then you should see a password prompt.
Once you type the password configured at the setup step above, press Enter once
more and you should get a prompt looking like ``>>>``. You can now start
typing Python commands!
Using the REPL
--------------
Once you have a prompt you can start experimenting! Anything you type at the
prompt will be executed after you press the Enter key. MicroPython will run
the code that you enter and print the result (if there is one). If there is an
error with the text that you enter then an error message is printed.
Try typing the following at the prompt::
>>> print('hello esp8266!')
hello esp8266!
Note that you shouldn't type the ``>>>`` arrows, they are there to indicate that
you should type the text after it at the prompt. And then the line following is
what the device should respond with. In the end, once you have entered the text
``print("hello esp8266!")`` and pressed the Enter key, the output on your screen
should look exactly like it does above.
If you already know some python you can now try some basic commands here. For
example::
>>> 1 + 2
3
>>> 1 / 2
0.5
>>> 12**34
4922235242952026704037113243122008064
If your board has an LED attached to GPIO2 (the ESP-12 modules do) then you can
turn it on and off using the following code::
>>> import machine
>>> pin = machine.Pin(2, machine.Pin.OUT)
>>> pin.on()
>>> pin.off()
Note that ``on`` method of a Pin might turn the LED off and ``off`` might
turn it on (or vice versa), depending on how the LED is wired on your board.
To resolve this, machine.Signal class is provided.
Line editing
~~~~~~~~~~~~
You can edit the current line that you are entering using the left and right
arrow keys to move the cursor, as well as the delete and backspace keys. Also,
pressing Home or ctrl-A moves the cursor to the start of the line, and pressing
End or ctrl-E moves to the end of the line.
Input history
~~~~~~~~~~~~~
The REPL remembers a certain number of previous lines of text that you entered
(up to 8 on the ESP8266). To recall previous lines use the up and down arrow
keys.
Tab completion
~~~~~~~~~~~~~~
Pressing the Tab key will do an auto-completion of the current word that you are
entering. This can be very useful to find out functions and methods that a
module or object has. Try it out by typing "ma" and then pressing Tab. It
should complete to "machine" (assuming you imported machine in the above
example). Then type "." and press Tab again to see a list of all the functions
that the machine module has.
Line continuation and auto-indent
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Certain things that you type will need "continuing", that is, will need more
lines of text to make a proper Python statement. In this case the prompt will
change to ``...`` and the cursor will auto-indent the correct amount so you can
start typing the next line straight away. Try this by defining the following
function::
>>> def toggle(p):
... p.value(not p.value())
...
...
...
>>>
In the above, you needed to press the Enter key three times in a row to finish
the compound statement (that's the three lines with just dots on them). The
other way to finish a compound statement is to press backspace to get to the
start of the line, then press the Enter key. (If you did something wrong and
want to escape the continuation mode then press ctrl-C; all lines will be
ignored.)
The function you just defined allows you to toggle a pin. The pin object you
created earlier should still exist (recreate it if it doesn't) and you can
toggle the LED using::
>>> toggle(pin)
Let's now toggle the LED in a loop (if you don't have an LED then you can just
print some text instead of calling toggle, to see the effect)::
>>> import time
>>> while True:
... toggle(pin)
... time.sleep_ms(500)
...
...
...
>>>
This will toggle the LED at 1Hz (half a second on, half a second off). To stop
the toggling press ctrl-C, which will raise a KeyboardInterrupt exception and
break out of the loop.
The time module provides some useful functions for making delays and doing
timing. Use tab completion to find out what they are and play around with them!
Paste mode
~~~~~~~~~~
Pressing ctrl-E will enter a special paste mode. This allows you to copy and
paste a chunk of text into the REPL. If you press ctrl-E you will see the
paste-mode prompt::
paste mode; Ctrl-C to cancel, Ctrl-D to finish
===
You can then paste (or type) your text in. Note that none of the special keys
or commands work in paste mode (eg Tab or backspace), they are just accepted
as-is. Press ctrl-D to finish entering the text and execute it.
Other control commands
~~~~~~~~~~~~~~~~~~~~~~
There are four other control commands:
* Ctrl-A on a blank line will enter raw REPL mode. This is like a permanent
paste mode, except that characters are not echoed back.
* Ctrl-B on a blank like goes to normal REPL mode.
* Ctrl-C cancels any input, or interrupts the currently running code.
* Ctrl-D on a blank line will do a soft reset.
Note that ctrl-A and ctrl-D do not work with WebREPL.
.. _ssd1306:
Using a SSD1306 OLED display
============================
The SSD1306 OLED display uses either a SPI or I2C interface and comes in a variety of
sizes (128x64, 128x32, 72x40, 64x48) and colours (white, yellow, blue, yellow + blue).
Hardware SPI interface::
from machine import Pin, SPI
import ssd1306
hspi = SPI(1) # sck=14 (scl), mosi=13 (sda), miso=12 (unused)
dc = Pin(4) # data/command
rst = Pin(5) # reset
cs = Pin(15) # chip select, some modules do not have a pin for this
display = ssd1306.SSD1306_SPI(128, 64, hspi, dc, rst, cs)
Software SPI interface::
from machine import Pin, SoftSPI
import ssd1306
spi = SoftSPI(baudrate=500000, polarity=1, phase=0, sck=Pin(14), mosi=Pin(13), miso=Pin(12))
dc = Pin(4) # data/command
rst = Pin(5) # reset
cs = Pin(15) # chip select, some modules do not have a pin for this
display = ssd1306.SSD1306_SPI(128, 64, spi, dc, rst, cs)
I2C interface::
from machine import Pin, I2C
import ssd1306
# using default address 0x3C
i2c = I2C(sda=Pin(4), scl=Pin(5))
display = ssd1306.SSD1306_I2C(128, 64, i2c)
Print Hello World on the first line::
display.text('Hello, World!', 0, 0, 1)
display.show()
Basic functions::
display.poweroff() # power off the display, pixels persist in memory
display.poweron() # power on the display, pixels redrawn
display.contrast(0) # dim
display.contrast(255) # bright
display.invert(1) # display inverted
display.invert(0) # display normal
display.rotate(True) # rotate 180 degrees
display.rotate(False) # rotate 0 degrees
display.show() # write the contents of the FrameBuffer to display memory
Subclassing FrameBuffer provides support for graphics primitives::
display.fill(0) # fill entire screen with colour=0
display.pixel(0, 10) # get pixel at x=0, y=10
display.pixel(0, 10, 1) # set pixel at x=0, y=10 to colour=1
display.hline(0, 8, 4, 1) # draw horizontal line x=0, y=8, width=4, colour=1
display.vline(0, 8, 4, 1) # draw vertical line x=0, y=8, height=4, colour=1
display.line(0, 0, 127, 63, 1) # draw a line from 0,0 to 127,63
display.rect(10, 10, 107, 43, 1) # draw a rectangle outline 10,10 to 117,53, colour=1
display.fill_rect(10, 10, 107, 43, 1) # draw a solid rectangle 10,10 to 117,53, colour=1
display.text('Hello World', 0, 0, 1) # draw some text at x=0, y=0, colour=1
display.scroll(20, 0) # scroll 20 pixels to the right
# draw another FrameBuffer on top of the current one at the given coordinates
import framebuf
fbuf = framebuf.FrameBuffer(bytearray(8 * 8 * 1), 8, 8, framebuf.MONO_VLSB)
fbuf.line(0, 0, 7, 7, 1)
display.blit(fbuf, 10, 10, 0) # draw on top at x=10, y=10, key=0
display.show()
Draw the MicroPython logo and print some text::
display.fill(0)
display.fill_rect(0, 0, 32, 32, 1)
display.fill_rect(2, 2, 28, 28, 0)
display.vline(9, 8, 22, 1)
display.vline(16, 2, 22, 1)
display.vline(23, 8, 22, 1)
display.fill_rect(26, 24, 2, 4, 1)
display.text('MicroPython', 40, 0, 1)
display.text('SSD1306', 40, 12, 1)
display.text('OLED 128x64', 40, 24, 1)
display.show()
MicroPython documentation and references
========================================
.. toctree::
library/index.rst
reference/index.rst
genrst/index.rst
develop/index.rst
license.rst
pyboard/quickref.rst
esp8266/quickref.rst
esp32/quickref.rst
rp2/quickref.rst
mimxrt/quickref.rst
wipy/quickref.rst
unix/quickref.rst
zephyr/quickref.rst
renesas-ra/quickref.rst
samd/quickref.rst
:mod:`_thread` -- multithreading support
========================================
.. module:: _thread
:synopsis: multithreading support
|see_cpython_module| :mod:`python:_thread`.
This module implements multithreading support.
This module is highly experimental and its API is not yet fully settled
and not yet described in this documentation.
:mod:`array` -- arrays of numeric data
======================================
.. module:: array
:synopsis: efficient arrays of numeric data
|see_cpython_module| :mod:`python:array`.
Supported format codes: ``b``, ``B``, ``h``, ``H``, ``i``, ``I``, ``l``,
``L``, ``q``, ``Q``, ``f``, ``d`` (the latter 2 depending on the
floating-point support).
Classes
-------
.. class:: array(typecode, [iterable])
Create array with elements of given type. Initial contents of the
array are given by *iterable*. If it is not provided, an empty
array is created.
.. method:: append(val)
Append new element *val* to the end of array, growing it.
.. method:: extend(iterable)
Append new elements as contained in *iterable* to the end of
array, growing it.
.. method:: __getitem__(index)
Indexed read of the array, called as ``a[index]`` (where ``a`` is an ``array``).
Returns a value if *index* is an ``int`` and an ``array`` if *index* is a slice.
Negative indices count from the end and ``IndexError`` is thrown if the index is
out of range.
**Note:** ``__getitem__`` cannot be called directly (``a.__getitem__(index)`` fails) and
is not present in ``__dict__``, however ``a[index]`` does work.
.. method:: __setitem__(index, value)
Indexed write into the array, called as ``a[index] = value`` (where ``a`` is an ``array``).
``value`` is a single value if *index* is an ``int`` and an ``array`` if *index* is a slice.
Negative indices count from the end and ``IndexError`` is thrown if the index is out of range.
**Note:** ``__setitem__`` cannot be called directly (``a.__setitem__(index, value)`` fails) and
is not present in ``__dict__``, however ``a[index] = value`` does work.
.. method:: __len__()
Returns the number of items in the array, called as ``len(a)`` (where ``a`` is an ``array``).
**Note:** ``__len__`` cannot be called directly (``a.__len__()`` fails) and the
method is not present in ``__dict__``, however ``len(a)`` does work.
.. method:: __add__(other)
Return a new ``array`` that is the concatenation of the array with *other*, called as
``a + other`` (where ``a`` and *other* are both ``arrays``).
**Note:** ``__add__`` cannot be called directly (``a.__add__(other)`` fails) and
is not present in ``__dict__``, however ``a + other`` does work.
.. method:: __iadd__(other)
Concatenates the array with *other* in-place, called as ``a += other`` (where ``a`` and *other*
are both ``arrays``). Equivalent to ``extend(other)``.
**Note:** ``__iadd__`` cannot be called directly (``a.__iadd__(other)`` fails) and
is not present in ``__dict__``, however ``a += other`` does work.
.. method:: __repr__()
Returns the string representation of the array, called as ``str(a)`` or ``repr(a)```
(where ``a`` is an ``array``). Returns the string ``"array(<type>, [<elements>])"``,
where ``<type>`` is the type code letter for the array and ``<elements>`` is a comma
seperated list of the elements of the array.
**Note:** ``__repr__`` cannot be called directly (``a.__repr__()`` fails) and
is not present in ``__dict__``, however ``str(a)`` and ``repr(a)`` both work.
:mod:`binascii` -- binary/ASCII conversions
===========================================
.. module:: binascii
:synopsis: binary/ASCII conversions
|see_cpython_module| :mod:`python:binascii`.
This module implements conversions between binary data and various
encodings of it in ASCII form (in both directions).
Functions
---------
.. function:: hexlify(data, [sep])
Convert the bytes in the *data* object to a hexadecimal representation.
Returns a bytes object.
If the additional argument *sep* is supplied it is used as a separator
between hexadecimal values.
.. function:: unhexlify(data)
Convert hexadecimal data to binary representation. Returns bytes string.
(i.e. inverse of hexlify)
.. function:: a2b_base64(data)
Decode base64-encoded data, ignoring invalid characters in the input.
Conforms to `RFC 2045 s.6.8 <https://tools.ietf.org/html/rfc2045#section-6.8>`_.
Returns a bytes object.
.. function:: b2a_base64(data, *, newline=True)
Encode binary data in base64 format, as in `RFC 3548
<https://tools.ietf.org/html/rfc3548.html>`_. Returns the encoded data
followed by a newline character if newline is true, as a bytes object.
:mod:`bluetooth` --- low-level Bluetooth
========================================
.. module:: bluetooth
:synopsis: Low-level Bluetooth radio functionality
This module provides an interface to a Bluetooth controller on a board.
Currently this supports Bluetooth Low Energy (BLE) in Central, Peripheral,
Broadcaster, and Observer roles, as well as GATT Server and Client and L2CAP
connection-oriented-channels. A device may operate in multiple roles
concurrently. Pairing (and bonding) is supported on some ports.
This API is intended to match the low-level Bluetooth protocol and provide
building-blocks for higher-level abstractions such as specific device types.
.. note:: For most applications, we recommend using the higher-level
`aioble library <https://github.com/micropython/micropython-lib/tree/master/micropython/bluetooth/aioble>`_.
.. note:: This module is still under development and its classes, functions,
methods and constants are subject to change.
class BLE
---------
Constructor
-----------
.. class:: BLE()
Returns the singleton BLE object.
Configuration
-------------
.. method:: BLE.active([active], /)
Optionally changes the active state of the BLE radio, and returns the
current state.
The radio must be made active before using any other methods on this class.
.. method:: BLE.config('param', /)
BLE.config(*, param=value, ...)
Get or set configuration values of the BLE interface. To get a value the
parameter name should be quoted as a string, and just one parameter is
queried at a time. To set values use the keyword syntax, and one ore more
parameter can be set at a time.
Currently supported values are:
- ``'mac'``: The current address in use, depending on the current address mode.
This returns a tuple of ``(addr_type, addr)``.
See :meth:`gatts_write <BLE.gatts_write>` for details about address type.
This may only be queried while the interface is currently active.
- ``'addr_mode'``: Sets the address mode. Values can be:
* 0x00 - PUBLIC - Use the controller's public address.
* 0x01 - RANDOM - Use a generated static address.
* 0x02 - RPA - Use resolvable private addresses.
* 0x03 - NRPA - Use non-resolvable private addresses.
By default the interface mode will use a PUBLIC address if available, otherwise
it will use a RANDOM address.
- ``'gap_name'``: Get/set the GAP device name used by service 0x1800,
characteristic 0x2a00. This can be set at any time and changed multiple
times.
- ``'rxbuf'``: Get/set the size in bytes of the internal buffer used to store
incoming events. This buffer is global to the entire BLE driver and so
handles incoming data for all events, including all characteristics.
Increasing this allows better handling of bursty incoming data (for
example scan results) and the ability to receive larger characteristic values.
- ``'mtu'``: Get/set the MTU that will be used during a ATT MTU exchange. The
resulting MTU will be the minimum of this and the remote device's MTU.
ATT MTU exchange will not happen automatically (unless the remote device initiates
it), and must be manually initiated with
:meth:`gattc_exchange_mtu<BLE.gattc_exchange_mtu>`.
Use the ``_IRQ_MTU_EXCHANGED`` event to discover the MTU for a given connection.
- ``'bond'``: Sets whether bonding will be enabled during pairing. When
enabled, pairing requests will set the "bond" flag and the keys will be stored
by both devices.
- ``'mitm'``: Sets whether MITM-protection is required for pairing.
- ``'io'``: Sets the I/O capabilities of this device.
Available options are::
_IO_CAPABILITY_DISPLAY_ONLY = const(0)
_IO_CAPABILITY_DISPLAY_YESNO = const(1)
_IO_CAPABILITY_KEYBOARD_ONLY = const(2)
_IO_CAPABILITY_NO_INPUT_OUTPUT = const(3)
_IO_CAPABILITY_KEYBOARD_DISPLAY = const(4)
- ``'le_secure'``: Sets whether "LE Secure" pairing is required. Default is
false (i.e. allow "Legacy Pairing").
Event Handling
--------------
.. method:: BLE.irq(handler, /)
Registers a callback for events from the BLE stack. The *handler* takes two
arguments, ``event`` (which will be one of the codes below) and ``data``
(which is an event-specific tuple of values).
**Note:** As an optimisation to prevent unnecessary allocations, the ``addr``,
``adv_data``, ``char_data``, ``notify_data``, and ``uuid`` entries in the
tuples are read-only memoryview instances pointing to :mod:`bluetooth`'s internal
ringbuffer, and are only valid during the invocation of the IRQ handler
function. If your program needs to save one of these values to access after
the IRQ handler has returned (e.g. by saving it in a class instance or global
variable), then it needs to take a copy of the data, either by using ``bytes()``
or ``bluetooth.UUID()``, like this::
connected_addr = bytes(addr) # equivalently: adv_data, char_data, or notify_data
matched_uuid = bluetooth.UUID(uuid)
For example, the IRQ handler for a scan result might inspect the ``adv_data``
to decide if it's the correct device, and only then copy the address data to be
used elsewhere in the program. And to print data from within the IRQ handler,
``print(bytes(addr))`` will be needed.
An event handler showing all possible events::
def bt_irq(event, data):
if event == _IRQ_CENTRAL_CONNECT:
# A central has connected to this peripheral.
conn_handle, addr_type, addr = data
elif event == _IRQ_CENTRAL_DISCONNECT:
# A central has disconnected from this peripheral.
conn_handle, addr_type, addr = data
elif event == _IRQ_GATTS_WRITE:
# A client has written to this characteristic or descriptor.
conn_handle, attr_handle = data
elif event == _IRQ_GATTS_READ_REQUEST:
# A client has issued a read. Note: this is only supported on STM32.
# Return a non-zero integer to deny the read (see below), or zero (or None)
# to accept the read.
conn_handle, attr_handle = data
elif event == _IRQ_SCAN_RESULT:
# A single scan result.
addr_type, addr, adv_type, rssi, adv_data = data
elif event == _IRQ_SCAN_DONE:
# Scan duration finished or manually stopped.
pass
elif event == _IRQ_PERIPHERAL_CONNECT:
# A successful gap_connect().
conn_handle, addr_type, addr = data
elif event == _IRQ_PERIPHERAL_DISCONNECT:
# Connected peripheral has disconnected.
conn_handle, addr_type, addr = data
elif event == _IRQ_GATTC_SERVICE_RESULT:
# Called for each service found by gattc_discover_services().
conn_handle, start_handle, end_handle, uuid = data
elif event == _IRQ_GATTC_SERVICE_DONE:
# Called once service discovery is complete.
# Note: Status will be zero on success, implementation-specific value otherwise.
conn_handle, status = data
elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
# Called for each characteristic found by gattc_discover_services().
conn_handle, end_handle, value_handle, properties, uuid = data
elif event == _IRQ_GATTC_CHARACTERISTIC_DONE:
# Called once service discovery is complete.
# Note: Status will be zero on success, implementation-specific value otherwise.
conn_handle, status = data
elif event == _IRQ_GATTC_DESCRIPTOR_RESULT:
# Called for each descriptor found by gattc_discover_descriptors().
conn_handle, dsc_handle, uuid = data
elif event == _IRQ_GATTC_DESCRIPTOR_DONE:
# Called once service discovery is complete.
# Note: Status will be zero on success, implementation-specific value otherwise.
conn_handle, status = data
elif event == _IRQ_GATTC_READ_RESULT:
# A gattc_read() has completed.
conn_handle, value_handle, char_data = data
elif event == _IRQ_GATTC_READ_DONE:
# A gattc_read() has completed.
# Note: The value_handle will be zero on btstack (but present on NimBLE).
# Note: Status will be zero on success, implementation-specific value otherwise.
conn_handle, value_handle, status = data
elif event == _IRQ_GATTC_WRITE_DONE:
# A gattc_write() has completed.
# Note: The value_handle will be zero on btstack (but present on NimBLE).
# Note: Status will be zero on success, implementation-specific value otherwise.
conn_handle, value_handle, status = data
elif event == _IRQ_GATTC_NOTIFY:
# A server has sent a notify request.
conn_handle, value_handle, notify_data = data
elif event == _IRQ_GATTC_INDICATE:
# A server has sent an indicate request.
conn_handle, value_handle, notify_data = data
elif event == _IRQ_GATTS_INDICATE_DONE:
# A client has acknowledged the indication.
# Note: Status will be zero on successful acknowledgment, implementation-specific value otherwise.
conn_handle, value_handle, status = data
elif event == _IRQ_MTU_EXCHANGED:
# ATT MTU exchange complete (either initiated by us or the remote device).
conn_handle, mtu = data
elif event == _IRQ_L2CAP_ACCEPT:
# A new channel has been accepted.
# Return a non-zero integer to reject the connection, or zero (or None) to accept.
conn_handle, cid, psm, our_mtu, peer_mtu = data
elif event == _IRQ_L2CAP_CONNECT:
# A new channel is now connected (either as a result of connecting or accepting).
conn_handle, cid, psm, our_mtu, peer_mtu = data
elif event == _IRQ_L2CAP_DISCONNECT:
# Existing channel has disconnected (status is zero), or a connection attempt failed (non-zero status).
conn_handle, cid, psm, status = data
elif event == _IRQ_L2CAP_RECV:
# New data is available on the channel. Use l2cap_recvinto to read.
conn_handle, cid = data
elif event == _IRQ_L2CAP_SEND_READY:
# A previous l2cap_send that returned False has now completed and the channel is ready to send again.
# If status is non-zero, then the transmit buffer overflowed and the application should re-send the data.
conn_handle, cid, status = data
elif event == _IRQ_CONNECTION_UPDATE:
# The remote device has updated connection parameters.
conn_handle, conn_interval, conn_latency, supervision_timeout, status = data
elif event == _IRQ_ENCRYPTION_UPDATE:
# The encryption state has changed (likely as a result of pairing or bonding).
conn_handle, encrypted, authenticated, bonded, key_size = data
elif event == _IRQ_GET_SECRET:
# Return a stored secret.
# If key is None, return the index'th value of this sec_type.
# Otherwise return the corresponding value for this sec_type and key.
sec_type, index, key = data
return value
elif event == _IRQ_SET_SECRET:
# Save a secret to the store for this sec_type and key.
sec_type, key, value = data
return True
elif event == _IRQ_PASSKEY_ACTION:
# Respond to a passkey request during pairing.
# See gap_passkey() for details.
# action will be an action that is compatible with the configured "io" config.
# passkey will be non-zero if action is "numeric comparison".
conn_handle, action, passkey = data
The event codes are::
from micropython import const
_IRQ_CENTRAL_CONNECT = const(1)
_IRQ_CENTRAL_DISCONNECT = const(2)
_IRQ_GATTS_WRITE = const(3)
_IRQ_GATTS_READ_REQUEST = const(4)
_IRQ_SCAN_RESULT = const(5)
_IRQ_SCAN_DONE = const(6)
_IRQ_PERIPHERAL_CONNECT = const(7)
_IRQ_PERIPHERAL_DISCONNECT = const(8)
_IRQ_GATTC_SERVICE_RESULT = const(9)
_IRQ_GATTC_SERVICE_DONE = const(10)
_IRQ_GATTC_CHARACTERISTIC_RESULT = const(11)
_IRQ_GATTC_CHARACTERISTIC_DONE = const(12)
_IRQ_GATTC_DESCRIPTOR_RESULT = const(13)
_IRQ_GATTC_DESCRIPTOR_DONE = const(14)
_IRQ_GATTC_READ_RESULT = const(15)
_IRQ_GATTC_READ_DONE = const(16)
_IRQ_GATTC_WRITE_DONE = const(17)
_IRQ_GATTC_NOTIFY = const(18)
_IRQ_GATTC_INDICATE = const(19)
_IRQ_GATTS_INDICATE_DONE = const(20)
_IRQ_MTU_EXCHANGED = const(21)
_IRQ_L2CAP_ACCEPT = const(22)
_IRQ_L2CAP_CONNECT = const(23)
_IRQ_L2CAP_DISCONNECT = const(24)
_IRQ_L2CAP_RECV = const(25)
_IRQ_L2CAP_SEND_READY = const(26)
_IRQ_CONNECTION_UPDATE = const(27)
_IRQ_ENCRYPTION_UPDATE = const(28)
_IRQ_GET_SECRET = const(29)
_IRQ_SET_SECRET = const(30)
For the ``_IRQ_GATTS_READ_REQUEST`` event, the available return codes are::
_GATTS_NO_ERROR = const(0x00)
_GATTS_ERROR_READ_NOT_PERMITTED = const(0x02)
_GATTS_ERROR_WRITE_NOT_PERMITTED = const(0x03)
_GATTS_ERROR_INSUFFICIENT_AUTHENTICATION = const(0x05)
_GATTS_ERROR_INSUFFICIENT_AUTHORIZATION = const(0x08)
_GATTS_ERROR_INSUFFICIENT_ENCRYPTION = const(0x0f)
For the ``_IRQ_PASSKEY_ACTION`` event, the available actions are::
_PASSKEY_ACTION_NONE = const(0)
_PASSKEY_ACTION_INPUT = const(2)
_PASSKEY_ACTION_DISPLAY = const(3)
_PASSKEY_ACTION_NUMERIC_COMPARISON = const(4)
In order to save space in the firmware, these constants are not included on the
:mod:`bluetooth` module. Add the ones that you need from the list above to your
program.
Broadcaster Role (Advertiser)
-----------------------------
.. method:: BLE.gap_advertise(interval_us, adv_data=None, *, resp_data=None, connectable=True)
Starts advertising at the specified interval (in **micro**\ seconds). This
interval will be rounded down to the nearest 625us. To stop advertising, set
*interval_us* to ``None``.
*adv_data* and *resp_data* can be any type that implements the buffer
protocol (e.g. ``bytes``, ``bytearray``, ``str``). *adv_data* is included
in all broadcasts, and *resp_data* is send in reply to an active scan.
**Note:** if *adv_data* (or *resp_data*) is ``None``, then the data passed
to the previous call to ``gap_advertise`` will be re-used. This allows a
broadcaster to resume advertising with just ``gap_advertise(interval_us)``.
To clear the advertising payload pass an empty ``bytes``, i.e. ``b''``.
Observer Role (Scanner)
-----------------------
.. method:: BLE.gap_scan(duration_ms, interval_us=1280000, window_us=11250, active=False, /)
Run a scan operation lasting for the specified duration (in **milli**\ seconds).
To scan indefinitely, set *duration_ms* to ``0``.
To stop scanning, set *duration_ms* to ``None``.
Use *interval_us* and *window_us* to optionally configure the duty cycle.
The scanner will run for *window_us* **micro**\ seconds every *interval_us*
**micro**\ seconds for a total of *duration_ms* **milli**\ seconds. The default
interval and window are 1.28 seconds and 11.25 milliseconds respectively
(background scanning).
For each scan result the ``_IRQ_SCAN_RESULT`` event will be raised, with event
data ``(addr_type, addr, adv_type, rssi, adv_data)``.
``addr_type`` values indicate public or random addresses:
* 0x00 - PUBLIC
* 0x01 - RANDOM (either static, RPA, or NRPA, the type is encoded in the address itself)
``adv_type`` values correspond to the Bluetooth Specification:
* 0x00 - ADV_IND - connectable and scannable undirected advertising
* 0x01 - ADV_DIRECT_IND - connectable directed advertising
* 0x02 - ADV_SCAN_IND - scannable undirected advertising
* 0x03 - ADV_NONCONN_IND - non-connectable undirected advertising
* 0x04 - SCAN_RSP - scan response
``active`` can be set ``True`` if you want to receive scan responses in the results.
When scanning is stopped (either due to the duration finishing or when
explicitly stopped), the ``_IRQ_SCAN_DONE`` event will be raised.
Central Role
------------
A central device can connect to peripherals that it has discovered using the observer role (see :meth:`gap_scan<BLE.gap_scan>`) or with a known address.
.. method:: BLE.gap_connect(addr_type, addr, scan_duration_ms=2000, min_conn_interval_us=None, max_conn_interval_us=None, /)
Connect to a peripheral.
See :meth:`gap_scan <BLE.gap_scan>` for details about address types.
To cancel an outstanding connection attempt early, call
``gap_connect(None)``.
On success, the ``_IRQ_PERIPHERAL_CONNECT`` event will be raised. If
cancelling a connection attempt, the ``_IRQ_PERIPHERAL_DISCONNECT`` event
will be raised.
The device will wait up to *scan_duration_ms* to receive an advertising
payload from the device.
The connection interval can be configured in **micro**\ seconds using either
or both of *min_conn_interval_us* and *max_conn_interval_us*. Otherwise a
default interval will be chosen, typically between 30000 and 50000
microseconds. A shorter interval will increase throughput, at the expense
of power usage.
Peripheral Role
---------------
A peripheral device is expected to send connectable advertisements (see
:meth:`gap_advertise<BLE.gap_advertise>`). It will usually be acting as a GATT
server, having first registered services and characteristics using
:meth:`gatts_register_services<BLE.gatts_register_services>`.
When a central connects, the ``_IRQ_CENTRAL_CONNECT`` event will be raised.
Central & Peripheral Roles
--------------------------
.. method:: BLE.gap_disconnect(conn_handle, /)
Disconnect the specified connection handle. This can either be a
central that has connected to this device (if acting as a peripheral)
or a peripheral that was previously connected to by this device (if acting
as a central).
On success, the ``_IRQ_PERIPHERAL_DISCONNECT`` or ``_IRQ_CENTRAL_DISCONNECT``
event will be raised.
Returns ``False`` if the connection handle wasn't connected, and ``True``
otherwise.
GATT Server
-----------
A GATT server has a set of registered services. Each service may contain
characteristics, which each have a value. Characteristics can also contain
descriptors, which themselves have values.
These values are stored locally, and are accessed by their "value handle" which
is generated during service registration. They can also be read from or written
to by a remote client device. Additionally, a server can "notify" a
characteristic to a connected client via a connection handle.
A device in either central or peripheral roles may function as a GATT server,
however in most cases it will be more common for a peripheral device to act
as the server.
Characteristics and descriptors have a default maximum size of 20 bytes.
Anything written to them by a client will be truncated to this length. However,
any local write will increase the maximum size, so if you want to allow larger
writes from a client to a given characteristic, use
:meth:`gatts_write<BLE.gatts_write>` after registration. e.g.
``gatts_write(char_handle, bytes(100))``.
.. method:: BLE.gatts_register_services(services_definition, /)
Configures the server with the specified services, replacing any
existing services.
*services_definition* is a list of **services**, where each **service** is a
two-element tuple containing a UUID and a list of **characteristics**.
Each **characteristic** is a two-or-three-element tuple containing a UUID, a
**flags** value, and optionally a list of *descriptors*.
Each **descriptor** is a two-element tuple containing a UUID and a **flags**
value.
The **flags** are a bitwise-OR combination of the flags defined below. These
set both the behaviour of the characteristic (or descriptor) as well as the
security and privacy requirements.
The return value is a list (one element per service) of tuples (each element
is a value handle). Characteristics and descriptor handles are flattened
into the same tuple, in the order that they are defined.
The following example registers two services (Heart Rate, and Nordic UART)::
HR_UUID = bluetooth.UUID(0x180D)
HR_CHAR = (bluetooth.UUID(0x2A37), bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,)
HR_SERVICE = (HR_UUID, (HR_CHAR,),)
UART_UUID = bluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')
UART_TX = (bluetooth.UUID('6E400003-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,)
UART_RX = (bluetooth.UUID('6E400002-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_WRITE,)
UART_SERVICE = (UART_UUID, (UART_TX, UART_RX,),)
SERVICES = (HR_SERVICE, UART_SERVICE,)
( (hr,), (tx, rx,), ) = bt.gatts_register_services(SERVICES)
The three value handles (``hr``, ``tx``, ``rx``) can be used with
:meth:`gatts_read <BLE.gatts_read>`, :meth:`gatts_write <BLE.gatts_write>`, :meth:`gatts_notify <BLE.gatts_notify>`, and
:meth:`gatts_indicate <BLE.gatts_indicate>`.
**Note:** Advertising must be stopped before registering services.
Available flags for characteristics and descriptors are::
from micropython import const
_FLAG_BROADCAST = const(0x0001)
_FLAG_READ = const(0x0002)
_FLAG_WRITE_NO_RESPONSE = const(0x0004)
_FLAG_WRITE = const(0x0008)
_FLAG_NOTIFY = const(0x0010)
_FLAG_INDICATE = const(0x0020)
_FLAG_AUTHENTICATED_SIGNED_WRITE = const(0x0040)
_FLAG_AUX_WRITE = const(0x0100)
_FLAG_READ_ENCRYPTED = const(0x0200)
_FLAG_READ_AUTHENTICATED = const(0x0400)
_FLAG_READ_AUTHORIZED = const(0x0800)
_FLAG_WRITE_ENCRYPTED = const(0x1000)
_FLAG_WRITE_AUTHENTICATED = const(0x2000)
_FLAG_WRITE_AUTHORIZED = const(0x4000)
As for the IRQs above, any required constants should be added to your Python code.
.. method:: BLE.gatts_read(value_handle, /)
Reads the local value for this handle (which has either been written by
:meth:`gatts_write <BLE.gatts_write>` or by a remote client).
.. method:: BLE.gatts_write(value_handle, data, send_update=False, /)
Writes the local value for this handle, which can be read by a client.
If *send_update* is ``True``, then any subscribed clients will be notified
(or indicated, depending on what they're subscribed to and which operations
the characteristic supports) about this write.
.. method:: BLE.gatts_notify(conn_handle, value_handle, data=None, /)
Sends a notification request to a connected client.
If *data* is not ``None``, then that value is sent to the client as part of
the notification. The local value will not be modified.
Otherwise, if *data* is ``None``, then the current local value (as
set with :meth:`gatts_write <BLE.gatts_write>`) will be sent.
**Note:** The notification will be sent regardless of the subscription
status of the client to this characteristic.
.. method:: BLE.gatts_indicate(conn_handle, value_handle, /)
Sends an indication request containing the characteristic's current value to
a connected client.
On acknowledgment (or failure, e.g. timeout), the
``_IRQ_GATTS_INDICATE_DONE`` event will be raised.
**Note:** The indication will be sent regardless of the subscription
status of the client to this characteristic.
.. method:: BLE.gatts_set_buffer(value_handle, len, append=False, /)
Sets the internal buffer size for a value in bytes. This will limit the
largest possible write that can be received. The default is 20.
Setting *append* to ``True`` will make all remote writes append to, rather
than replace, the current value. At most *len* bytes can be buffered in
this way. When you use :meth:`gatts_read <BLE.gatts_read>`, the value will
be cleared after reading. This feature is useful when implementing something
like the Nordic UART Service.
GATT Client
-----------
A GATT client can discover and read/write characteristics on a remote GATT server.
It is more common for a central role device to act as the GATT client, however
it's also possible for a peripheral to act as a client in order to discover
information about the central that has connected to it (e.g. to read the
device name from the device information service).
.. method:: BLE.gattc_discover_services(conn_handle, uuid=None, /)
Query a connected server for its services.
Optionally specify a service *uuid* to query for that service only.
For each service discovered, the ``_IRQ_GATTC_SERVICE_RESULT`` event will
be raised, followed by ``_IRQ_GATTC_SERVICE_DONE`` on completion.
.. method:: BLE.gattc_discover_characteristics(conn_handle, start_handle, end_handle, uuid=None, /)
Query a connected server for characteristics in the specified range.
Optionally specify a characteristic *uuid* to query for that
characteristic only.
You can use ``start_handle=1``, ``end_handle=0xffff`` to search for a
characteristic in any service.
For each characteristic discovered, the ``_IRQ_GATTC_CHARACTERISTIC_RESULT``
event will be raised, followed by ``_IRQ_GATTC_CHARACTERISTIC_DONE`` on completion.
.. method:: BLE.gattc_discover_descriptors(conn_handle, start_handle, end_handle, /)
Query a connected server for descriptors in the specified range.
For each descriptor discovered, the ``_IRQ_GATTC_DESCRIPTOR_RESULT`` event
will be raised, followed by ``_IRQ_GATTC_DESCRIPTOR_DONE`` on completion.
.. method:: BLE.gattc_read(conn_handle, value_handle, /)
Issue a remote read to a connected server for the specified
characteristic or descriptor handle.
When a value is available, the ``_IRQ_GATTC_READ_RESULT`` event will be
raised. Additionally, the ``_IRQ_GATTC_READ_DONE`` will be raised.
.. method:: BLE.gattc_write(conn_handle, value_handle, data, mode=0, /)
Issue a remote write to a connected server for the specified
characteristic or descriptor handle.
The argument *mode* specifies the write behaviour, with the currently
supported values being:
* ``mode=0`` (default) is a write-without-response: the write will
be sent to the remote server but no confirmation will be
returned, and no event will be raised.
* ``mode=1`` is a write-with-response: the remote server is
requested to send a response/acknowledgement that it received the
data.
If a response is received from the remote server the
``_IRQ_GATTC_WRITE_DONE`` event will be raised.
.. method:: BLE.gattc_exchange_mtu(conn_handle, /)
Initiate MTU exchange with a connected server, using the preferred MTU
set using ``BLE.config(mtu=value)``.
The ``_IRQ_MTU_EXCHANGED`` event will be raised when MTU exchange
completes.
**Note:** MTU exchange is typically initiated by the central. When using
the BlueKitchen stack in the central role, it does not support a remote
peripheral initiating the MTU exchange. NimBLE works for both roles.
L2CAP connection-oriented-channels
----------------------------------
This feature allows for socket-like data exchange between two BLE devices.
Once the devices are connected via GAP, either device can listen for the
other to connect on a numeric PSM (Protocol/Service Multiplexer).
**Note:** This is currently only supported when using the NimBLE stack on
STM32 and Unix (not ESP32). Only one L2CAP channel may be active at a given
time (i.e. you cannot connect while listening).
Active L2CAP channels are identified by the connection handle that they were
established on and a CID (channel ID).
Connection-oriented channels have built-in credit-based flow control. Unlike
ATT, where devices negotiate a shared MTU, both the listening and connecting
devices each set an independent MTU which limits the maximum amount of
outstanding data that the remote device can send before it is fully consumed
in :meth:`l2cap_recvinto <BLE.l2cap_recvinto>`.
.. method:: BLE.l2cap_listen(psm, mtu, /)
Start listening for incoming L2CAP channel requests on the specified *psm*
with the local MTU set to *mtu*.
When a remote device initiates a connection, the ``_IRQ_L2CAP_ACCEPT``
event will be raised, which gives the listening server a chance to reject
the incoming connection (by returning a non-zero integer).
Once the connection is accepted, the ``_IRQ_L2CAP_CONNECT`` event will be
raised, allowing the server to obtain the channel id (CID) and the local and
remote MTU.
**Note:** It is not currently possible to stop listening.
.. method:: BLE.l2cap_connect(conn_handle, psm, mtu, /)
Connect to a listening peer on the specified *psm* with local MTU set to *mtu*.
On successful connection, the the ``_IRQ_L2CAP_CONNECT`` event will be
raised, allowing the client to obtain the CID and the local and remote (peer) MTU.
An unsuccessful connection will raise the ``_IRQ_L2CAP_DISCONNECT`` event
with a non-zero status.
.. method:: BLE.l2cap_disconnect(conn_handle, cid, /)
Disconnect an active L2CAP channel with the specified *conn_handle* and
*cid*.
.. method:: BLE.l2cap_send(conn_handle, cid, buf, /)
Send the specified *buf* (which must support the buffer protocol) on the
L2CAP channel identified by *conn_handle* and *cid*.
The specified buffer cannot be larger than the remote (peer) MTU, and no
more than twice the size of the local MTU.
This will return ``False`` if the channel is now "stalled", which means that
:meth:`l2cap_send <BLE.l2cap_send>` must not be called again until the
``_IRQ_L2CAP_SEND_READY`` event is received (which will happen when the
remote device grants more credits, typically after it has received and
processed the data).
.. method:: BLE.l2cap_recvinto(conn_handle, cid, buf, /)
Receive data from the specified *conn_handle* and *cid* into the provided
*buf* (which must support the buffer protocol, e.g. bytearray or
memoryview).
Returns the number of bytes read from the channel.
If *buf* is None, then returns the number of bytes available.
**Note:** After receiving the ``_IRQ_L2CAP_RECV`` event, the application should
continue calling :meth:`l2cap_recvinto <BLE.l2cap_recvinto>` until no more
bytes are available in the receive buffer (typically up to the size of the
remote (peer) MTU).
Until the receive buffer is empty, the remote device will not be granted
more channel credits and will be unable to send any more data.
Pairing and bonding
-------------------
Pairing allows a connection to be encrypted and authenticated via exchange
of secrets (with optional MITM protection via passkey authentication).
Bonding is the process of storing those secrets into non-volatile storage.
When bonded, a device is able to resolve a resolvable private address (RPA)
from another device based on the stored identity resolving key (IRK).
To support bonding, an application must implement the ``_IRQ_GET_SECRET``
and ``_IRQ_SET_SECRET`` events.
**Note:** This is currently only supported when using the NimBLE stack on
STM32 and Unix (not ESP32).
.. method:: BLE.gap_pair(conn_handle, /)
Initiate pairing with the remote device.
Before calling this, ensure that the ``io``, ``mitm``, ``le_secure``, and
``bond`` configuration options are set (via :meth:`config<BLE.config>`).
On successful pairing, the ``_IRQ_ENCRYPTION_UPDATE`` event will be raised.
.. method:: BLE.gap_passkey(conn_handle, action, passkey, /)
Respond to a ``_IRQ_PASSKEY_ACTION`` event for the specified *conn_handle*
and *action*.
The *passkey* is a numeric value and will depend on on the
*action* (which will depend on what I/O capability has been set):
* When the *action* is ``_PASSKEY_ACTION_INPUT``, then the application should
prompt the user to enter the passkey that is shown on the remote device.
* When the *action* is ``_PASSKEY_ACTION_DISPLAY``, then the application should
generate a random 6-digit passkey and show it to the user.
* When the *action* is ``_PASSKEY_ACTION_NUMERIC_COMPARISON``, then the application
should show the passkey that was provided in the ``_IRQ_PASSKEY_ACTION`` event
and then respond with either ``0`` (cancel pairing), or ``1`` (accept pairing).
class UUID
----------
Constructor
-----------
.. class:: UUID(value, /)
Creates a UUID instance with the specified **value**.
The **value** can be either:
- A 16-bit integer. e.g. ``0x2908``.
- A 128-bit UUID string. e.g. ``'6E400001-B5A3-F393-E0A9-E50E24DCCA9E'``.
:mod:`btree` -- simple BTree database
=====================================
.. module:: btree
:synopsis: simple BTree database
The ``btree`` module implements a simple key-value database using external
storage (disk files, or in general case, a random-access `stream`). Keys are
stored sorted in the database, and besides efficient retrieval by a key
value, a database also supports efficient ordered range scans (retrieval
of values with the keys in a given range). On the application interface
side, BTree database work as close a possible to a way standard `dict`
type works, one notable difference is that both keys and values must
be `bytes`-like objects (so, if you want to store objects of other types, you
need to first serialize them to `str` or `bytes` or another type that supports
the buffer protocol).
The module is based on the well-known BerkelyDB library, version 1.xx.
Example::
import btree
# First, we need to open a stream which holds a database
# This is usually a file, but can be in-memory database
# using io.BytesIO, a raw flash partition, etc.
# Oftentimes, you want to create a database file if it doesn't
# exist and open if it exists. Idiom below takes care of this.
# DO NOT open database with "a+b" access mode.
try:
f = open("mydb", "r+b")
except OSError:
f = open("mydb", "w+b")
# Now open a database itself
db = btree.open(f)
# The keys you add will be sorted internally in the database
db[b"3"] = b"three"
db[b"1"] = b"one"
db[b"2"] = b"two"
# Assume that any changes are cached in memory unless
# explicitly flushed (or database closed). Flush database
# at the end of each "transaction".
db.flush()
# Prints b'two'
print(db[b"2"])
# Iterate over sorted keys in the database, starting from b"2"
# until the end of the database, returning only values.
# Mind that arguments passed to values() method are *key* values.
# Prints:
# b'two'
# b'three'
for word in db.values(b"2"):
print(word)
del db[b"2"]
# No longer true, prints False
print(b"2" in db)
# Prints:
# b"1"
# b"3"
for key in db:
print(key)
db.close()
# Don't forget to close the underlying stream!
f.close()
Functions
---------
.. function:: open(stream, *, flags=0, pagesize=0, cachesize=0, minkeypage=0)
Open a database from a random-access `stream` (like an open file). All
other parameters are optional and keyword-only, and allow to tweak advanced
parameters of the database operation (most users will not need them):
* *flags* - Currently unused.
* *pagesize* - Page size used for the nodes in BTree. Acceptable range
is 512-65536. If 0, a port-specific default will be used, optimized for
port's memory usage and/or performance.
* *cachesize* - Suggested memory cache size in bytes. For a
board with enough memory using larger values may improve performance.
Cache policy is as follows: entire cache is not allocated at once;
instead, accessing a new page in database will allocate a memory buffer
for it, until value specified by *cachesize* is reached. Then, these
buffers will be managed using LRU (least recently used) policy. More
buffers may still be allocated if needed (e.g., if a database contains
big keys and/or values). Allocated cache buffers aren't reclaimed.
* *minkeypage* - Minimum number of keys to store per page. Default value
of 0 equivalent to 2.
Returns a BTree object, which implements a dictionary protocol (set
of methods), and some additional methods described below.
Methods
-------
.. method:: btree.close()
Close the database. It's mandatory to close the database at the end of
processing, as some unwritten data may be still in the cache. Note that
this does not close underlying stream with which the database was opened,
it should be closed separately (which is also mandatory to make sure that
data flushed from buffer to the underlying storage).
.. method:: btree.flush()
Flush any data in cache to the underlying stream.
.. method:: btree.__getitem__(key)
btree.get(key, default=None, /)
btree.__setitem__(key, val)
btree.__delitem__(key)
btree.__contains__(key)
Standard dictionary methods.
.. method:: btree.__iter__()
A BTree object can be iterated over directly (similar to a dictionary)
to get access to all keys in order.
.. method:: btree.keys([start_key, [end_key, [flags]]])
btree.values([start_key, [end_key, [flags]]])
btree.items([start_key, [end_key, [flags]]])
These methods are similar to standard dictionary methods, but also can
take optional parameters to iterate over a key sub-range, instead of
the entire database. Note that for all 3 methods, *start_key* and
*end_key* arguments represent key values. For example, `values()`
method will iterate over values corresponding to they key range
given. None values for *start_key* means "from the first key", no
*end_key* or its value of None means "until the end of database".
By default, range is inclusive of *start_key* and exclusive of
*end_key*, you can include *end_key* in iteration by passing *flags*
of `btree.INCL`. You can iterate in descending key direction
by passing *flags* of `btree.DESC`. The flags values can be ORed
together.
Constants
---------
.. data:: INCL
A flag for `keys()`, `values()`, `items()` methods to specify that
scanning should be inclusive of the end key.
.. data:: DESC
A flag for `keys()`, `values()`, `items()` methods to specify that
scanning should be in descending direction of keys.
:mod:`builtins` -- builtin functions and exceptions
===================================================
All builtin functions and exceptions are described here. They are also
available via ``builtins`` module.
Functions and types
-------------------
.. function:: abs()
.. function:: all()
.. function:: any()
.. function:: bin()
.. class:: bool()
.. class:: bytearray()
.. class:: bytes()
|see_cpython| `python:bytes`.
.. function:: callable()
.. function:: chr()
.. function:: classmethod()
.. function:: compile()
.. class:: complex()
.. function:: delattr(obj, name)
The argument *name* should be a string, and this function deletes the named
attribute from the object given by *obj*.
.. class:: dict()
.. function:: dir()
.. function:: divmod()
.. function:: enumerate()
.. function:: eval()
.. function:: exec()
.. function:: filter()
.. class:: float()
.. class:: frozenset()
.. function:: getattr()
.. function:: globals()
.. function:: hasattr()
.. function:: hash()
.. function:: hex()
.. function:: id()
.. function:: input()
.. class:: int()
.. classmethod:: from_bytes(bytes, byteorder)
In MicroPython, `byteorder` parameter must be positional (this is
compatible with CPython).
.. method:: to_bytes(size, byteorder)
In MicroPython, `byteorder` parameter must be positional (this is
compatible with CPython).
.. function:: isinstance()
.. function:: issubclass()
.. function:: iter()
.. function:: len()
.. class:: list()
.. function:: locals()
.. function:: map()
.. function:: max()
.. class:: memoryview()
.. function:: min()
.. function:: next()
.. class:: object()
.. function:: oct()
.. function:: open()
.. function:: ord()
.. function:: pow()
.. function:: print()
.. function:: property()
.. function:: range()
.. function:: repr()
.. function:: reversed()
.. function:: round()
.. class:: set()
.. function:: setattr()
.. class:: slice()
The *slice* builtin is the type that slice objects have.
.. function:: sorted()
.. function:: staticmethod()
.. class:: str()
.. function:: sum()
.. function:: super()
.. class:: tuple()
.. function:: type()
.. function:: zip()
Exceptions
----------
.. exception:: AssertionError
.. exception:: AttributeError
.. exception:: Exception
.. exception:: ImportError
.. exception:: IndexError
.. exception:: KeyboardInterrupt
.. exception:: KeyError
.. exception:: MemoryError
.. exception:: NameError
.. exception:: NotImplementedError
.. exception:: OSError
.. exception:: RuntimeError
.. exception:: StopIteration
.. exception:: SyntaxError
.. exception:: SystemExit
|see_cpython| `python:SystemExit`.
.. exception:: TypeError
|see_cpython| `python:TypeError`.
.. exception:: ValueError
.. exception:: ZeroDivisionError
:mod:`cmath` -- mathematical functions for complex numbers
==========================================================
.. module:: cmath
:synopsis: mathematical functions for complex numbers
|see_cpython_module| :mod:`python:cmath`.
The ``cmath`` module provides some basic mathematical functions for
working with complex numbers.
Availability: not available on WiPy and ESP8266. Floating point support
required for this module.
Functions
---------
.. function:: cos(z)
Return the cosine of ``z``.
.. function:: exp(z)
Return the exponential of ``z``.
.. function:: log(z)
Return the natural logarithm of ``z``. The branch cut is along the negative real axis.
.. function:: log10(z)
Return the base-10 logarithm of ``z``. The branch cut is along the negative real axis.
.. function:: phase(z)
Returns the phase of the number ``z``, in the range (-pi, +pi].
.. function:: polar(z)
Returns, as a tuple, the polar form of ``z``.
.. function:: rect(r, phi)
Returns the complex number with modulus ``r`` and phase ``phi``.
.. function:: sin(z)
Return the sine of ``z``.
.. function:: sqrt(z)
Return the square-root of ``z``.
Constants
---------
.. data:: e
base of the natural logarithm
.. data:: pi
the ratio of a circle's circumference to its diameter
:mod:`collections` -- collection and container types
====================================================
.. module:: collections
:synopsis: collection and container types
|see_cpython_module| :mod:`python:collections`.
This module implements advanced collection and container types to
hold/accumulate various objects.
Classes
-------
.. class:: deque(iterable, maxlen[, flags])
Deques (double-ended queues) are a list-like container that support O(1)
appends and pops from either side of the deque. New deques are created
using the following arguments:
- *iterable* must be the empty tuple, and the new deque is created empty.
- *maxlen* must be specified and the deque will be bounded to this
maximum length. Once the deque is full, any new items added will
discard items from the opposite end.
- The optional *flags* can be 1 to check for overflow when adding items.
As well as supporting `bool` and `len`, deque objects have the following
methods:
.. method:: deque.append(x)
Add *x* to the right side of the deque.
Raises IndexError if overflow checking is enabled and there is no more room left.
.. method:: deque.popleft()
Remove and return an item from the left side of the deque.
Raises IndexError if no items are present.
.. function:: namedtuple(name, fields)
This is factory function to create a new namedtuple type with a specific
name and set of fields. A namedtuple is a subclass of tuple which allows
to access its fields not just by numeric index, but also with an attribute
access syntax using symbolic field names. Fields is a sequence of strings
specifying field names. For compatibility with CPython it can also be a
a string with space-separated field named (but this is less efficient).
Example of use::
from collections import namedtuple
MyTuple = namedtuple("MyTuple", ("id", "name"))
t1 = MyTuple(1, "foo")
t2 = MyTuple(2, "bar")
print(t1.name)
assert t2.name == t2[1]
.. class:: OrderedDict(...)
``dict`` type subclass which remembers and preserves the order of keys
added. When ordered dict is iterated over, keys/items are returned in
the order they were added::
from collections import OrderedDict
# To make benefit of ordered keys, OrderedDict should be initialized
# from sequence of (key, value) pairs.
d = OrderedDict([("z", 1), ("a", 2)])
# More items can be added as usual
d["w"] = 5
d["b"] = 3
for k, v in d.items():
print(k, v)
Output::
z 1
a 2
w 5
b 3
:mod:`cryptolib` -- cryptographic ciphers
=========================================
.. module:: cryptolib
:synopsis: cryptographic ciphers
Classes
-------
.. class:: aes
.. classmethod:: __init__(key, mode, [IV])
Initialize cipher object, suitable for encryption/decryption. Note:
after initialization, cipher object can be use only either for
encryption or decryption. Running decrypt() operation after encrypt()
or vice versa is not supported.
Parameters are:
* *key* is an encryption/decryption key (bytes-like).
* *mode* is:
* ``1`` (or ``cryptolib.MODE_ECB`` if it exists) for Electronic Code Book (ECB).
* ``2`` (or ``cryptolib.MODE_CBC`` if it exists) for Cipher Block Chaining (CBC).
* ``6`` (or ``cryptolib.MODE_CTR`` if it exists) for Counter mode (CTR).
* *IV* is an initialization vector for CBC mode.
* For Counter mode, *IV* is the initial value for the counter.
.. method:: encrypt(in_buf, [out_buf])
Encrypt *in_buf*. If no *out_buf* is given result is returned as a
newly allocated `bytes` object. Otherwise, result is written into
mutable buffer *out_buf*. *in_buf* and *out_buf* can also refer
to the same mutable buffer, in which case data is encrypted in-place.
.. method:: decrypt(in_buf, [out_buf])
Like `encrypt()`, but for decryption.
:mod:`errno` -- system error codes
==================================
.. module:: errno
:synopsis: system error codes
|see_cpython_module| :mod:`python:errno`.
This module provides access to symbolic error codes for `OSError` exception.
A particular inventory of codes depends on :term:`MicroPython port`.
Constants
---------
.. data:: EEXIST, EAGAIN, etc.
Error codes, based on ANSI C/POSIX standard. All error codes start with
"E". As mentioned above, inventory of the codes depends on
:term:`MicroPython port`. Errors are usually accessible as ``exc.errno``
where ``exc`` is an instance of `OSError`. Usage example::
try:
os.mkdir("my_dir")
except OSError as exc:
if exc.errno == errno.EEXIST:
print("Directory already exists")
.. data:: errorcode
Dictionary mapping numeric error codes to strings with symbolic error
code (see above)::
>>> print(errno.errorcode[errno.EEXIST])
EEXIST
:mod:`esp` --- functions related to the ESP8266 and ESP32
=========================================================
.. module:: esp
:synopsis: functions related to the ESP8266 and ESP32
The ``esp`` module contains specific functions related to both the ESP8266 and
ESP32 modules. Some functions are only available on one or the other of these
ports.
Functions
---------
.. function:: sleep_type([sleep_type])
**Note**: ESP8266 only
Get or set the sleep type.
If the *sleep_type* parameter is provided, sets the sleep type to its
value. If the function is called without parameters, returns the current
sleep type.
The possible sleep types are defined as constants:
* ``SLEEP_NONE`` -- all functions enabled,
* ``SLEEP_MODEM`` -- modem sleep, shuts down the WiFi Modem circuit.
* ``SLEEP_LIGHT`` -- light sleep, shuts down the WiFi Modem circuit
and suspends the processor periodically.
The system enters the set sleep mode automatically when possible.
.. function:: deepsleep(time_us=0, /)
**Note**: ESP8266 only - use `machine.deepsleep()` on ESP32
Enter deep sleep.
The whole module powers down, except for the RTC clock circuit, which can
be used to restart the module after the specified time if the pin 16 is
connected to the reset pin. Otherwise the module will sleep until manually
reset.
.. function:: flash_id()
**Note**: ESP8266 only
Read the device ID of the flash memory.
.. function:: flash_size()
Read the total size of the flash memory.
.. function:: flash_user_start()
Read the memory offset at which the user flash space begins.
.. function:: flash_read(byte_offset, length_or_buffer)
.. function:: flash_write(byte_offset, bytes)
.. function:: flash_erase(sector_no)
.. function:: osdebug(level)
Turn esp os debugging messages on or off.
The *level* parameter sets the threshold for the log messages for all esp components.
The log levels are defined as constants:
* ``LOG_NONE`` -- No log output
* ``LOG_ERROR`` -- Critical errors, software module can not recover on its own
* ``LOG_WARN`` -- Error conditions from which recovery measures have been taken
* ``LOG_INFO`` -- Information messages which describe normal flow of events
* ``LOG_DEBUG`` -- Extra information which is not necessary for normal use (values, pointers, sizes, etc)
* ``LOG_VERBOSE`` -- Bigger chunks of debugging information, or frequent messages
which can potentially flood the output
.. function:: set_native_code_location(start, length)
**Note**: ESP8266 only
Set the location that native code will be placed for execution after it is
compiled. Native code is emitted when the ``@micropython.native``,
``@micropython.viper`` and ``@micropython.asm_xtensa`` decorators are applied
to a function. The ESP8266 must execute code from either iRAM or the lower
1MByte of flash (which is memory mapped), and this function controls the
location.
If *start* and *length* are both ``None`` then the native code location is
set to the unused portion of memory at the end of the iRAM1 region. The
size of this unused portion depends on the firmware and is typically quite
small (around 500 bytes), and is enough to store a few very small
functions. The advantage of using this iRAM1 region is that it does not
get worn out by writing to it.
If neither *start* nor *length* are ``None`` then they should be integers.
*start* should specify the byte offset from the beginning of the flash at
which native code should be stored. *length* specifies how many bytes of
flash from *start* can be used to store native code. *start* and *length*
should be multiples of the sector size (being 4096 bytes). The flash will
be automatically erased before writing to it so be sure to use a region of
flash that is not otherwise used, for example by the firmware or the
filesystem.
When using the flash to store native code *start+length* must be less
than or equal to 1MByte. Note that the flash can be worn out if repeated
erasures (and writes) are made so use this feature sparingly.
In particular, native code needs to be recompiled and rewritten to flash
on each boot (including wake from deepsleep).
In both cases above, using iRAM1 or flash, if there is no more room left
in the specified region then the use of a native decorator on a function
will lead to `MemoryError` exception being raised during compilation of
that function.
.. currentmodule:: esp32
:mod:`esp32` --- functionality specific to the ESP32
====================================================
.. module:: esp32
:synopsis: functionality specific to the ESP32
The ``esp32`` module contains functions and classes specifically aimed at
controlling ESP32 modules.
Functions
---------
.. function:: wake_on_touch(wake)
Configure whether or not a touch will wake the device from sleep.
*wake* should be a boolean value.
.. function:: wake_on_ulp(wake)
Configure whether or not the Ultra-Low-Power co-processor can wake the
device from sleep. *wake* should be a boolean value.
.. function:: wake_on_ext0(pin, level)
Configure how EXT0 wakes the device from sleep. *pin* can be ``None``
or a valid Pin object. *level* should be ``esp32.WAKEUP_ALL_LOW`` or
``esp32.WAKEUP_ANY_HIGH``.
.. function:: wake_on_ext1(pins, level)
Configure how EXT1 wakes the device from sleep. *pins* can be ``None``
or a tuple/list of valid Pin objects. *level* should be ``esp32.WAKEUP_ALL_LOW``
or ``esp32.WAKEUP_ANY_HIGH``.
.. function:: gpio_deep_sleep_hold(enable)
Configure whether non-RTC GPIO pin configuration is retained during
deep-sleep mode for held pads. *enable* should be a boolean value.
.. function:: raw_temperature()
Read the raw value of the internal temperature sensor, returning an integer.
.. function:: hall_sensor()
Read the raw value of the internal Hall sensor, returning an integer.
.. function:: idf_heap_info(capabilities)
Returns information about the ESP-IDF heap memory regions. One of them contains
the MicroPython heap and the others are used by ESP-IDF, e.g., for network
buffers and other data. This data is useful to get a sense of how much memory
is available to ESP-IDF and the networking stack in particular. It may shed
some light on situations where ESP-IDF operations fail due to allocation failures.
The information returned is *not* useful to troubleshoot Python allocation failures,
use `micropython.mem_info()` instead.
The capabilities parameter corresponds to ESP-IDF's ``MALLOC_CAP_XXX`` values but the
two most useful ones are predefined as `esp32.HEAP_DATA` for data heap regions and
`esp32.HEAP_EXEC` for executable regions as used by the native code emitter.
The return value is a list of 4-tuples, where each 4-tuple corresponds to one heap
and contains: the total bytes, the free bytes, the largest free block, and
the minimum free seen over time.
Example after booting::
>>> import esp32; esp32.idf_heap_info(esp32.HEAP_DATA)
[(240, 0, 0, 0), (7288, 0, 0, 0), (16648, 4, 4, 4), (79912, 35712, 35512, 35108),
(15072, 15036, 15036, 15036), (113840, 0, 0, 0)]
Flash partitions
----------------
This class gives access to the partitions in the device's flash memory and includes
methods to enable over-the-air (OTA) updates.
.. class:: Partition(id, block_size=4096, /)
Create an object representing a partition. *id* can be a string which is the label
of the partition to retrieve, or one of the constants: ``BOOT`` or ``RUNNING``.
*block_size* specifies the byte size of an individual block.
.. classmethod:: Partition.find(type=TYPE_APP, subtype=0xff, label=None, block_size=4096)
Find a partition specified by *type*, *subtype* and *label*. Returns a
(possibly empty) list of Partition objects. Note: ``subtype=0xff`` matches any subtype
and ``label=None`` matches any label.
*block_size* specifies the byte size of an individual block used by the returned
objects.
.. method:: Partition.info()
Returns a 6-tuple ``(type, subtype, addr, size, label, encrypted)``.
.. method:: Partition.readblocks(block_num, buf)
Partition.readblocks(block_num, buf, offset)
.. method:: Partition.writeblocks(block_num, buf)
Partition.writeblocks(block_num, buf, offset)
.. method:: Partition.ioctl(cmd, arg)
These methods implement the simple and :ref:`extended
<block-device-interface>` block protocol defined by
:class:`os.AbstractBlockDev`.
.. method:: Partition.set_boot()
Sets the partition as the boot partition.
.. method:: Partition.get_next_update()
Gets the next update partition after this one, and returns a new Partition object.
Typical usage is ``Partition(Partition.RUNNING).get_next_update()``
which returns the next partition to update given the current running one.
.. classmethod:: Partition.mark_app_valid_cancel_rollback()
Signals that the current boot is considered successful.
Calling ``mark_app_valid_cancel_rollback`` is required on the first boot of a new
partition to avoid an automatic rollback at the next boot.
This uses the ESP-IDF "app rollback" feature with "CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE"
and an ``OSError(-261)`` is raised if called on firmware that doesn't have the
feature enabled.
It is OK to call ``mark_app_valid_cancel_rollback`` on every boot and it is not
necessary when booting firmare that was loaded using esptool.
Constants
~~~~~~~~~
.. data:: Partition.BOOT
Partition.RUNNING
Used in the `Partition` constructor to fetch various partitions: ``BOOT`` is the
partition that will be booted at the next reset and ``RUNNING`` is the currently
running partition.
.. data:: Partition.TYPE_APP
Partition.TYPE_DATA
Used in `Partition.find` to specify the partition type: ``APP`` is for bootable
firmware partitions (typically labelled ``factory``, ``ota_0``, ``ota_1``), and
``DATA`` is for other partitions, e.g. ``nvs``, ``otadata``, ``phy_init``, ``vfs``.
.. data:: HEAP_DATA
HEAP_EXEC
Used in `idf_heap_info`.
.. _esp32.RMT:
RMT
---
The RMT (Remote Control) module, specific to the ESP32, was originally designed
to send and receive infrared remote control signals. However, due to a flexible
design and very accurate (as low as 12.5ns) pulse generation, it can also be
used to transmit or receive many other types of digital signals::
import esp32
from machine import Pin
r = esp32.RMT(0, pin=Pin(18), clock_div=8)
r # RMT(channel=0, pin=18, source_freq=80000000, clock_div=8, idle_level=0)
# To apply a carrier frequency to the high output
r = esp32.RMT(0, pin=Pin(18), clock_div=8, tx_carrier=(38000, 50, 1))
# The channel resolution is 100ns (1/(source_freq/clock_div)).
r.write_pulses((1, 20, 2, 40), 0) # Send 0 for 100ns, 1 for 2000ns, 0 for 200ns, 1 for 4000ns
The input to the RMT module is an 80MHz clock (in the future it may be able to
configure the input clock but, for now, it's fixed). ``clock_div`` *divides*
the clock input which determines the resolution of the RMT channel. The
numbers specified in ``write_pulses`` are multiplied by the resolution to
define the pulses.
``clock_div`` is an 8-bit divider (0-255) and each pulse can be defined by
multiplying the resolution by a 15-bit (0-32,768) number. There are eight
channels (0-7) and each can have a different clock divider.
So, in the example above, the 80MHz clock is divided by 8. Thus the
resolution is (1/(80Mhz/8)) 100ns. Since the ``start`` level is 0 and toggles
with each number, the bitstream is ``0101`` with durations of [100ns, 2000ns,
100ns, 4000ns].
For more details see Espressif's `ESP-IDF RMT documentation.
<https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/rmt.html>`_.
.. Warning::
The current MicroPython RMT implementation lacks some features, most notably
receiving pulses. RMT should be considered a
*beta feature* and the interface may change in the future.
.. class:: RMT(channel, *, pin=None, clock_div=8, idle_level=False, tx_carrier=None)
This class provides access to one of the eight RMT channels. *channel* is
required and identifies which RMT channel (0-7) will be configured. *pin*,
also required, configures which Pin is bound to the RMT channel. *clock_div*
is an 8-bit clock divider that divides the source clock (80MHz) to the RMT
channel allowing the resolution to be specified. *idle_level* specifies
what level the output will be when no transmission is in progress and can
be any value that converts to a boolean, with ``True`` representing high
voltage and ``False`` representing low.
To enable the transmission carrier feature, *tx_carrier* should be a tuple
of three positive integers: carrier frequency, duty percent (``0`` to
``100``) and the output level to apply the carrier to (a boolean as per
*idle_level*).
.. method:: RMT.source_freq()
Returns the source clock frequency. Currently the source clock is not
configurable so this will always return 80MHz.
.. method:: RMT.clock_div()
Return the clock divider. Note that the channel resolution is
``1 / (source_freq / clock_div)``.
.. method:: RMT.wait_done(*, timeout=0)
Returns ``True`` if the channel is idle or ``False`` if a sequence of
pulses started with `RMT.write_pulses` is being transmitted. If the
*timeout* keyword argument is given then block for up to this many
milliseconds for transmission to complete.
.. method:: RMT.loop(enable_loop)
Configure looping on the channel. *enable_loop* is bool, set to ``True`` to
enable looping on the *next* call to `RMT.write_pulses`. If called with
``False`` while a looping sequence is currently being transmitted then the
current loop iteration will be completed and then transmission will stop.
.. method:: RMT.write_pulses(duration, data=True)
Begin transmitting a sequence. There are three ways to specify this:
**Mode 1:** *duration* is a list or tuple of durations. The optional *data*
argument specifies the initial output level. The output level will toggle
after each duration.
**Mode 2:** *duration* is a positive integer and *data* is a list or tuple
of output levels. *duration* specifies a fixed duration for each.
**Mode 3:** *duration* and *data* are lists or tuples of equal length,
specifying individual durations and the output level for each.
Durations are in integer units of the channel resolution (as described
above), between 1 and 32767 units. Output levels are any value that can
be converted to a boolean, with ``True`` representing high voltage and
``False`` representing low.
If transmission of an earlier sequence is in progress then this method will
block until that transmission is complete before beginning the new sequence.
If looping has been enabled with `RMT.loop`, the sequence will be
repeated indefinitely. Further calls to this method will block until the
end of the current loop iteration before immediately beginning to loop the
new sequence of pulses. Looping sequences longer than 126 pulses is not
supported by the hardware.
.. staticmethod:: RMT.bitstream_channel([value])
Select which RMT channel is used by the `machine.bitstream` implementation.
*value* can be ``None`` or a valid RMT channel number. The default RMT
channel is the highest numbered one.
Passing in ``None`` disables the use of RMT and instead selects a bit-banging
implementation for `machine.bitstream`.
Passing in no argument will not change the channel. This function returns
the current channel number.
Ultra-Low-Power co-processor
----------------------------
.. class:: ULP()
This class provides access to the Ultra-Low-Power co-processor.
.. method:: ULP.set_wakeup_period(period_index, period_us)
Set the wake-up period.
.. method:: ULP.load_binary(load_addr, program_binary)
Load a *program_binary* into the ULP at the given *load_addr*.
.. method:: ULP.run(entry_point)
Start the ULP running at the given *entry_point*.
Constants
---------
.. data:: esp32.WAKEUP_ALL_LOW
esp32.WAKEUP_ANY_HIGH
Selects the wake level for pins.
Non-Volatile Storage
--------------------
This class gives access to the Non-Volatile storage managed by ESP-IDF. The NVS is partitioned
into namespaces and each namespace contains typed key-value pairs. The keys are strings and the
values may be various integer types, strings, and binary blobs. The driver currently only
supports 32-bit signed integers and blobs.
.. warning::
Changes to NVS need to be committed to flash by calling the commit method. Failure
to call commit results in changes being lost at the next reset.
.. class:: NVS(namespace)
Create an object providing access to a namespace (which is automatically created if not
present).
.. method:: NVS.set_i32(key, value)
Sets a 32-bit signed integer value for the specified key. Remember to call *commit*!
.. method:: NVS.get_i32(key)
Returns the signed integer value for the specified key. Raises an OSError if the key does not
exist or has a different type.
.. method:: NVS.set_blob(key, value)
Sets a binary blob value for the specified key. The value passed in must support the buffer
protocol, e.g. bytes, bytearray, str. (Note that esp-idf distinguishes blobs and strings, this
method always writes a blob even if a string is passed in as value.)
Remember to call *commit*!
.. method:: NVS.get_blob(key, buffer)
Reads the value of the blob for the specified key into the buffer, which must be a bytearray.
Returns the actual length read. Raises an OSError if the key does not exist, has a different
type, or if the buffer is too small.
.. method:: NVS.erase_key(key)
Erases a key-value pair.
.. method:: NVS.commit()
Commits changes made by *set_xxx* methods to flash.
:mod:`framebuf` --- frame buffer manipulation
=============================================
.. module:: framebuf
:synopsis: Frame buffer manipulation
This module provides a general frame buffer which can be used to create
bitmap images, which can then be sent to a display.
class FrameBuffer
-----------------
The FrameBuffer class provides a pixel buffer which can be drawn upon with
pixels, lines, rectangles, ellipses, polygons, text and even other
FrameBuffers. It is useful when generating output for displays.
For example::
import framebuf
# FrameBuffer needs 2 bytes for every RGB565 pixel
fbuf = framebuf.FrameBuffer(bytearray(100 * 10 * 2), 100, 10, framebuf.RGB565)
fbuf.fill(0)
fbuf.text('MicroPython!', 0, 0, 0xffff)
fbuf.hline(0, 9, 96, 0xffff)
Constructors
------------
.. class:: FrameBuffer(buffer, width, height, format, stride=width, /)
Construct a FrameBuffer object. The parameters are:
- *buffer* is an object with a buffer protocol which must be large
enough to contain every pixel defined by the width, height and
format of the FrameBuffer.
- *width* is the width of the FrameBuffer in pixels
- *height* is the height of the FrameBuffer in pixels
- *format* specifies the type of pixel used in the FrameBuffer;
permissible values are listed under Constants below. These set the
number of bits used to encode a color value and the layout of these
bits in *buffer*.
Where a color value c is passed to a method, c is a small integer
with an encoding that is dependent on the format of the FrameBuffer.
- *stride* is the number of pixels between each horizontal line
of pixels in the FrameBuffer. This defaults to *width* but may
need adjustments when implementing a FrameBuffer within another
larger FrameBuffer or screen. The *buffer* size must accommodate
an increased step size.
One must specify valid *buffer*, *width*, *height*, *format* and
optionally *stride*. Invalid *buffer* size or dimensions may lead to
unexpected errors.
Drawing primitive shapes
------------------------
The following methods draw shapes onto the FrameBuffer.
.. method:: FrameBuffer.fill(c)
Fill the entire FrameBuffer with the specified color.
.. method:: FrameBuffer.pixel(x, y[, c])
If *c* is not given, get the color value of the specified pixel.
If *c* is given, set the specified pixel to the given color.
.. method:: FrameBuffer.hline(x, y, w, c)
.. method:: FrameBuffer.vline(x, y, h, c)
.. method:: FrameBuffer.line(x1, y1, x2, y2, c)
Draw a line from a set of coordinates using the given color and
a thickness of 1 pixel. The `line` method draws the line up to
a second set of coordinates whereas the `hline` and `vline`
methods draw horizontal and vertical lines respectively up to
a given length.
.. method:: FrameBuffer.rect(x, y, w, h, c[, f])
Draw a rectangle at the given location, size and color.
The optional *f* parameter can be set to ``True`` to fill the rectangle.
Otherwise just a one pixel outline is drawn.
.. method:: FrameBuffer.ellipse(x, y, xr, yr, c[, f, m])
Draw an ellipse at the given location. Radii *xr* and *yr* define the
geometry; equal values cause a circle to be drawn. The *c* parameter
defines the color.
The optional *f* parameter can be set to ``True`` to fill the ellipse.
Otherwise just a one pixel outline is drawn.
The optional *m* parameter enables drawing to be restricted to certain
quadrants of the ellipse. The LS four bits determine which quadrants are
to be drawn, with bit 0 specifying Q1, b1 Q2, b2 Q3 and b3 Q4. Quadrants
are numbered counterclockwise with Q1 being top right.
.. method:: FrameBuffer.poly(x, y, coords, c[, f])
Given a list of coordinates, draw an arbitrary (convex or concave) closed
polygon at the given x, y location using the given color.
The *coords* must be specified as a :mod:`array` of integers, e.g.
``array('h', [x0, y0, x1, y1, ... xn, yn])``.
The optional *f* parameter can be set to ``True`` to fill the polygon.
Otherwise just a one pixel outline is drawn.
Drawing text
------------
.. method:: FrameBuffer.text(s, x, y[, c])
Write text to the FrameBuffer using the the coordinates as the upper-left
corner of the text. The color of the text can be defined by the optional
argument but is otherwise a default value of 1. All characters have
dimensions of 8x8 pixels and there is currently no way to change the font.
Other methods
-------------
.. method:: FrameBuffer.scroll(xstep, ystep)
Shift the contents of the FrameBuffer by the given vector. This may
leave a footprint of the previous colors in the FrameBuffer.
.. method:: FrameBuffer.blit(fbuf, x, y, key=-1, palette=None)
Draw another FrameBuffer on top of the current one at the given coordinates.
If *key* is specified then it should be a color integer and the
corresponding color will be considered transparent: all pixels with that
color value will not be drawn. (If the *palette* is specified then the *key*
is compared to the value from *palette*, not to the value directly from
*fbuf*.)
The *palette* argument enables blitting between FrameBuffers with differing
formats. Typical usage is to render a monochrome or grayscale glyph/icon to
a color display. The *palette* is a FrameBuffer instance whose format is
that of the current FrameBuffer. The *palette* height is one pixel and its
pixel width is the number of colors in the source FrameBuffer. The *palette*
for an N-bit source needs 2**N pixels; the *palette* for a monochrome source
would have 2 pixels representing background and foreground colors. The
application assigns a color to each pixel in the *palette*. The color of the
current pixel will be that of that *palette* pixel whose x position is the
color of the corresponding source pixel.
Constants
---------
.. data:: framebuf.MONO_VLSB
Monochrome (1-bit) color format
This defines a mapping where the bits in a byte are vertically mapped with
bit 0 being nearest the top of the screen. Consequently each byte occupies
8 vertical pixels. Subsequent bytes appear at successive horizontal
locations until the rightmost edge is reached. Further bytes are rendered
at locations starting at the leftmost edge, 8 pixels lower.
.. data:: framebuf.MONO_HLSB
Monochrome (1-bit) color format
This defines a mapping where the bits in a byte are horizontally mapped.
Each byte occupies 8 horizontal pixels with bit 7 being the leftmost.
Subsequent bytes appear at successive horizontal locations until the
rightmost edge is reached. Further bytes are rendered on the next row, one
pixel lower.
.. data:: framebuf.MONO_HMSB
Monochrome (1-bit) color format
This defines a mapping where the bits in a byte are horizontally mapped.
Each byte occupies 8 horizontal pixels with bit 0 being the leftmost.
Subsequent bytes appear at successive horizontal locations until the
rightmost edge is reached. Further bytes are rendered on the next row, one
pixel lower.
.. data:: framebuf.RGB565
Red Green Blue (16-bit, 5+6+5) color format
.. data:: framebuf.GS2_HMSB
Grayscale (2-bit) color format
.. data:: framebuf.GS4_HMSB
Grayscale (4-bit) color format
.. data:: framebuf.GS8
Grayscale (8-bit) color format
:mod:`gc` -- control the garbage collector
==========================================
.. module:: gc
:synopsis: control the garbage collector
|see_cpython_module| :mod:`python:gc`.
Functions
---------
.. function:: enable()
Enable automatic garbage collection.
.. function:: disable()
Disable automatic garbage collection. Heap memory can still be allocated,
and garbage collection can still be initiated manually using :meth:`gc.collect`.
.. function:: collect()
Run a garbage collection.
.. function:: mem_alloc()
Return the number of bytes of heap RAM that are allocated.
.. admonition:: Difference to CPython
:class: attention
This function is MicroPython extension.
.. function:: mem_free()
Return the number of bytes of available heap RAM, or -1 if this amount
is not known.
.. admonition:: Difference to CPython
:class: attention
This function is MicroPython extension.
.. function:: threshold([amount])
Set or query the additional GC allocation threshold. Normally, a collection
is triggered only when a new allocation cannot be satisfied, i.e. on an
out-of-memory (OOM) condition. If this function is called, in addition to
OOM, a collection will be triggered each time after *amount* bytes have been
allocated (in total, since the previous time such an amount of bytes
have been allocated). *amount* is usually specified as less than the
full heap size, with the intention to trigger a collection earlier than when the
heap becomes exhausted, and in the hope that an early collection will prevent
excessive memory fragmentation. This is a heuristic measure, the effect
of which will vary from application to application, as well as
the optimal value of the *amount* parameter.
Calling the function without argument will return the current value of
the threshold. A value of -1 means a disabled allocation threshold.
.. admonition:: Difference to CPython
:class: attention
This function is a MicroPython extension. CPython has a similar
function - ``set_threshold()``, but due to different GC
implementations, its signature and semantics are different.