MicroPython Documentation 1.4 PDF
MicroPython Documentation 1.4 PDF
MicroPython Documentation 1.4 PDF
Release 1.4
Damien P. George
i
5 The pyboard hardware 79
ii
CHAPTER 1
See pyb.
import pyb
1.2 LEDs
See pyb.LED.
from pyb import LED
See pyb.Pin.
from pyb import Pin
1
Micro Python Documentation, Release 1.4
See pyb.Servo.
from pyb import Servo
See pyb.ExtInt.
from pyb import Pin, ExtInt
1.6 Timers
See pyb.Timer.
from pyb import Timer
adc = ADC(Pin(’X19’))
adc.read() # read value, 0-4095
dac = DAC(Pin(’X5’))
dac.write(120) # output between 0 and 255
See pyb.UART.
from pyb import UART
See pyb.SPI.
from pyb import SPI
See pyb.I2C.
from pyb import I2C
There is a small internal filesystem (a drive) on the pyboard, called /flash, which is stored within the microcon-
troller’s flash memory. If a micro SD card is inserted into the slot, it is available as /sd.
When the pyboard boots up, it needs to choose a filesystem to boot from. If there is no SD card, then it uses the internal
filesystem /flash as the boot filesystem, otherwise, it uses the SD card /sd.
(Note that on older versions of the board, /flash is called 0:/ and /sd is called 1:/).
The boot filesystem is used for 2 things: it is the filesystem from which the boot.py and main.py files are searched
for, and it is the filesystem which is made available on your PC over the USB cable.
The filesystem will be available as a USB flash drive on your PC. You can save files to the drive, and edit boot.py
and main.py.
Remember to eject (on Linux, unmount) the USB drive before you reset your pyboard.
If you power up normally, or press the reset button, the pyboard will boot into standard mode: the boot.py file will
be executed first, then the USB will be configured, then main.py will run.
You can override this boot sequence by holding down the user switch as the board is booting up. Hold down user
switch and press reset, and then as you continue to hold the user switch, the LEDs will count in binary. When the
LEDs have reached the mode you want, let go of the user switch, the LEDs for the selected mode will flash quickly,
and the board will boot.
The modes are:
1. Green LED only, standard boot: run boot.py then main.py.
2. Orange LED only, safe boot: don’t run any scripts on boot-up.
3. Green and orange LED together, filesystem reset: resets the flash filesystem to its factory state, then boots in
safe mode.
If your filesystem becomes corrupt, boot into mode 3 to fix it. If resetting the filesystem while plugged into your
compute doesn’t work, you can try doing the same procedure while the board is plugged into a USB charger, or other
USB power supply without data connection.
5
Micro Python Documentation, Release 1.4
This tutorial is intended to get you started with your pyboard. All you need is a pyboard and a micro-USB cable to
connect it to your PC. If it is your first time, it is recommended to follow the tutorial through in the order below.
To get the most out of your pyboard, there are a few basic things to understand about how it works.
Because the pyboard does not have a housing it needs a bit of care:
• Be gentle when plugging/unplugging the USB cable. Whilst the USB connector is soldered through the board
and is relatively strong, if it breaks off it can be very difficult to fix.
• Static electricity can shock the components on the pyboard and destroy them. If you experience a lot of static
electricity in your area (eg dry and cold climates), take extra care not to shock the pyboard. If your pyboard
came in a black plastic box, then this box is the best way to store and carry the pyboard as it is an anti-static box
(it is made of a conductive plastic, with conductive foam inside).
As long as you take care of the hardware, you should be okay. It’s almost impossible to break the software on the
pyboard, so feel free to play around with writing code as much as you like. If the filesystem gets corrupt, see below on
how to reset it. In the worst case you might need to reflash the Micro Python software, but that can be done over USB.
The micro USB connector is on the top right, the micro SD card slot on the top left of the board. There are 4 LEDs
between the SD slot and USB connector. The colours are: red on the bottom, then green, orange, and blue on the top.
There are 2 switches: the right one is the reset switch, the left is the user switch.
The pyboard can be powered via USB. Connect it to your PC via a micro USB cable. There is only one way that the
cable will fit. Once connected, the green LED on the board should flash quickly.
7
Micro Python Documentation, Release 1.4
Let’s jump right in and get a Python script running on the pyboard. After all, that’s what it’s all about!
Connect your pyboard to your PC (Windows, Mac or Linux) with a micro USB cable. There is only one way that the
cable will connect, so you can’t get it wrong.
When the pyboard is connected to your PC it will power on and enter the start up process (the boot process). The
green LED should light up for half a second or less, and when it turns off it means the boot process has completed.
Your PC should now recognise the pyboard. It depends on the type of PC you have as to what happens next:
• Windows: Your pyboard will appear as a removable USB flash drive. Windows may automatically pop-up a
Now we are going to write our Python program, so open the main.py file in a text editor. On Windows you can
use notepad, or any other editor. On Mac and Linux, use your favourite text editor. With the file open you will see it
contains 1 line:
# main.py -- put your code here!
This line starts with a # character, which means that it is a comment. Such lines will not do anything, and are there for
you to write notes about your program.
Let’s add 2 lines to this main.py file, to make it look like this:
# main.py -- put your code here!
import pyb
pyb.LED(4).on()
The first line we wrote says that we want to use the pyb module. This module contains all the functions and classes
to control the features of the pyboard.
The second line that we wrote turns the blue LED on: it first gets the LED class from the pyb module, creates LED
number 4 (the blue LED), and then turns it on.
To run this little script, you need to first save and close the main.py file, and then eject (or unmount) the pyboard
USB drive. Do this like you would a normal USB flash drive.
When the drive is safely ejected/unmounted you can get to the fun part: press the RST switch on the pyboard to reset
and run your script. The RST switch is the small black button just below the USB connector on the board, on the right
edge.
When you press RST the green LED will flash quickly, and then the blue LED should turn on and stay on.
Congratulations! You have written and run your very first Micro Python program!
REPL stands for Read Evaluate Print Loop, and is the name given to the interactive Micro Python prompt that you can
access on the pyboard. Using the REPL is by far the easiest way to test out your code and run commands. You can use
the REPL in addition to writing scripts in main.py.
To use the REPL, you must connect to the serial USB device on the pyboard. How you do this depends on your
operating system.
3.3.1 Windows
You need to install the pyboard driver to use the serial USB device. The driver is on the pyboard’s USB flash drive,
and is called pybcdc.inf.
To install this driver you need to go to Device Manager for your computer, find the pyboard in the list of devices (it
should have a warning sign next to it because it’s not working yet), right click on the pyboard device, select Properties,
then Install Driver. You need to then select the option to find the driver manually (don’t use Windows auto update),
navigate to the pyboard’s USB drive, and select that. It should then install. After installing, go back to the Device
Manager to find the installed pyboard, and see which COM port it is (eg COM4). More comprehensive instructions can
be found in the Guide for pyboard on Windows (PDF). Please consult this guide if you are having problems installing
the driver.
You now need to run your terminal program. You can use HyperTerminal if you have it installed, or download the
free program PuTTY: putty.exe. Using your serial program you must connect to the COM port that you found in the
previous step. With PuTTY, click on “Session” in the left-hand panel, then click the “Serial” radio button on the right,
then enter you COM port (eg COM4) in the “Serial Line” box. Finally, click the “Open” button.
3.3.2 Mac OS X
When you are finished and want to exit screen, type CTRL-A CTRL-\.
3.3.3 Linux
You can also try picocom or minicom instead of screen. You may have to use /dev/ttyACM1 or a higher number
for ttyACM. And, you may need to give yourself the correct permissions to access this devices (eg group uucp or
dialout, or use sudo).
Now let’s try running some Micro Python code directly on the pyboard.
With your serial program open (PuTTY, screen, picocom, etc) you may see a blank screen with a flashing cursor. Press
Enter and you should be presented with a Micro Python prompt, i.e. >>>. Let’s make sure it is working with the
obligatory test:
>>> print("hello pyboard!")
hello pyboard!
In the above, you should not type in the >>> characters. They are there to indicate that you should type the text after
it at the prompt. In the end, once you have entered the text print("hello pyboard!") and pressed Enter, the
output on your screen should look like it does above.
If you already know some python you can now try some basic commands here.
If any of this is not working you can try either a hard reset or a soft reset; see below.
Go ahead and try typing in some other commands. For example:
>>> pyb.LED(1).on()
>>> pyb.LED(2).on()
>>> 1 + 2
3
>>> 1 / 2
0.5
>>> 20 * ’py’
’pypypypypypypypypypypypypypypypypypypypy’
If something goes wrong, you can reset the board in two ways. The first is to press CTRL-D at the Micro Python
prompt, which performs a soft reset. You will see a message something like
>>>
PYB: sync filesystems
PYB: soft reboot
Micro Python v1.0 on 2014-05-03; PYBv1.0 with STM32F405RG
Type "help()" for more information.
>>>
If that isn’t working you can perform a hard reset (turn-it-off-and-on-again) by pressing the RST switch (the small
black button closest to the micro-USB socket on the board). This will end your session, disconnecting whatever
program (PuTTY, screen, etc) that you used to connect to the pyboard.
If you are going to do a hard-reset, it’s recommended to first close your serial program and eject/unmount the pyboard
drive.
The easiest thing to do on the pyboard is to turn on the LEDs attached to the board. Connect the board, and log in as
described in tutorial 1. We will start by turning and LED on in the interpreter, type the following
>>> myled = pyb.LED(1)
>>> myled.on()
>>> myled.off()
When you save, the red light on the pyboard should turn on for about a second. To run the script, do a soft reset
(CTRL-D). The pyboard will then restart and you should see a green light continuously flashing on and off. Success,
the first step on your path to building an army of evil robots! When you are bored of the annoying flashing light then
press CTRL-C at your terminal to stop it running.
So what does this code do? First we need some terminology. Python is an object-oriented language, almost everything
in python is a class and when you create an instance of a class you get an object. Classes have methods associated to
them. A method (also called a member function) is used to interact with or control the object.
The first line of code creates an LED object which we have then called led. When we create the object, it takes a single
parameter which must be between 1 and 4, corresponding to the 4 LEDs on the board. The pyb.LED class has three
important member functions that we will use: on(), off() and toggle(). The other function that we use is pyb.delay()
this simply waits for a given time in miliseconds. Once we have created the LED object, the statement while True:
creates an infinite loop which toggles the led between on and off and waits for 1 second.
Exercise: Try changing the time between toggling the led and turning on a different LED.
Exercise: Connect to the pyboard directly, create a pyb.LED object and turn it on using the on() method.
So far we have only used a single LED but the pyboard has 4 available. Let’s start by creating an object for each LED
so we can control each of them. We do that by creating a list of LEDS with a list comprehension.
leds = [pyb.LED(i) for i in range(1,5)]
If you call pyb.LED() with a number that isn’t 1,2,3,4 you will get an error message. Next we will set up an infinite
loop that cycles through each of the LEDs turning them on and off.
n = 0
while True:
n = (n + 1) % 4
leds[n].toggle()
pyb.delay(50)
Here, n keeps track of the current LED and every time the loop is executed we cycle to the next n (the % sign is a
modulus operator that keeps n between 0 and 3.) Then we access the nth LED and toggle it. If you run this you should
see each of the LEDs turning on then all turning off again in sequence.
One problem you might find is that if you stop the script and then start it again that the LEDs are stuck on from the
previous run, ruining our carefully choreographed disco. We can fix this by turning all the LEDs off when we initialise
the script and then using a try/finally block. When you press CTRL-C, Micro Python generates a VCPInterrupt
exception. Exceptions normally mean something has gone wrong and you can use a try: command to “catch” an
exception. In this case it is just the user interrupting the script, so we don’t need to catch the error but just tell Micro
Python what to do when we exit. The finally block does this, and we use it to make sure all the LEDs are off. The full
code is:
n = 0
try:
while True:
n = (n + 1) % 4
leds[n].toggle()
pyb.delay(50)
finally:
for l in leds:
l.off()
The blue LED is special. As well as turning it on and off, you can control the intensity using the intensity() method.
This takes a number between 0 and 255 that determines how bright it is. The following script makes the blue LED
gradually brighter then turns it off again.
led = pyb.LED(4)
intensity = 0
while True:
intensity = (intensity + 1) % 255
led.intensity(intensity)
pyb.delay(20)
You can call intensity() on the other LEDs but they can only be off or on. 0 sets them off and any other number up to
255 turns them on.
The pyboard has 2 small switches, labelled USR and RST. The RST switch is a hard-reset switch, and if you press it
then it restarts the pyboard from scratch, equivalent to turning the power off then back on.
The USR switch is for general use, and is controlled via a Switch object. To make a switch object do:
>>> sw = pyb.Switch()
Remember that you may need to type import pyb if you get an error that the name pyb does not exist.
With the switch object you can get its status:
>>> sw()
False
This will print False if the switch is not held, or True if it is held. Try holding the USR switch down while running
the above command.
The switch is a very simple object, but it does have one advanced feature: the sw.callback() function. The
callback function sets up something to run when the switch is pressed, and uses an interrupt. It’s probably best to start
with an example before understanding how interrupts work. Try running the following at the prompt:
>>> sw.callback(lambda:print(’press!’))
This tells the switch to print press! each time the switch is pressed down. Go ahead and try it: press the USR switch
and watch the output on your PC. Note that this print will interrupt anything you are typing, and is an example of an
interrupt routine running asynchronously.
As another example try:
>>> sw.callback(lambda:pyb.LED(1).toggle())
This will toggle the red LED each time the switch is pressed. And it will even work while other code is running.
To disable the switch callback, pass None to the callback function:
>>> sw.callback(None)
You can pass any function (that takes zero arguments) to the switch callback. Above we used the lambda feature of
Python to create an anonymous function on the fly. But we could equally do:
>>> def f():
... pyb.LED(1).toggle()
...
>>> sw.callback(f)
This creates a function called f and assigns it to the switch callback. You can do things this way when your function
is more complicated than a lambda will allow.
Note that your callback functions must not allocate any memory (for example they cannot create a tuple or list).
Callback functions should be relatively simple. If you need to make a list, make it beforehand and store it in a global
variable (or make it local and close over it). If you need to do a long, complicated calculation, then use the callback to
set a flag which some other code then responds to.
Let’s step through the details of what is happening with the switch callback. When you register a function with
sw.callback(), the switch sets up an external interrupt trigger (falling edge) on the pin that the switch is connected
to. This means that the microcontroller will listen on the pin for any changes, and the following will occur:
1. When the switch is pressed a change occurs on the pin (the pin goes from low to high), and the microcontroller
registers this change.
2. The microcontroller finishes executing the current machine instruction, stops execution, and saves its current
state (pushes the registers on the stack). This has the effect of pausing any code, for example your running
Python script.
3. The microcontroller starts executing the special interrupt handler associated with the switch’s external trigger.
This interrupt handler get the function that you registered with sw.callback() and executes it.
4. Your callback function is executed until it finishes, returning control to the switch interrupt handler.
5. The switch interrupt handler returns, and the microcontroller is notified that the interrupt has been dealt with.
6. The microcontroller restores the state that it saved in step 2.
7. Execution continues of the code that was running at the beginning. Apart from the pause, this code does not
notice that it was interrupted.
The above sequence of events gets a bit more complicated when multiple interrupts occur at the same time. In that
case, the interrupt with the highest priority goes first, then the others in order of their priority. The switch interrupt is
set at the lowest priority.
Here you will learn how to read the accelerometer and signal using LEDs states like tilt left and tilt right.
The pyboard has an accelerometer (a tiny mass on a tiny spring) that can be used to detect the angle of the board and
motion. There is a different sensor for each of the x, y, z directions. To get the value of the accelerometer, create a
pyb.Accel() object and then call the x() method.
>>> accel = pyb.Accel()
>>> accel.x()
7
This returns a signed integer with a value between around -30 and 30. Note that the measurement is very noisy, this
means that even if you keep the board perfectly still there will be some variation in the number that you measure.
Because of this, you shouldn’t use the exact value of the x() method but see if it is in a certain range.
We will start by using the accelerometer to turn on a light if it is not flat.
accel = pyb.Accel()
light = pyb.LED(3)
SENSITIVITY = 3
while True:
x = accel.x()
if abs(x) > SENSITIVITY:
light.on()
else:
light.off()
pyb.delay(100)
We create Accel and LED objects, then get the value of the x direction of the accelerometer. If the magnitude of x
is bigger than a certain value SENSITIVITY, then the LED turns on, otherwise it turns off. The loop has a small
pyb.delay() otherwise the LED flashes annoyingly when the value of x is close to SENSITIVITY. Try running
this on the pyboard and tilt the board left and right to make the LED turn on and off.
Exercise: Change the above script so that the blue LED gets brighter the more you tilt the pyboard. HINT: You
will need to rescale the values, intensity goes from 0-255.
The example above is only sensitive to the angle in the x direction but if we use the y() value and more LEDs we can
turn the pyboard into a spirit level.
xlights = (pyb.LED(2), pyb.LED(3))
ylights = (pyb.LED(1), pyb.LED(4))
accel = pyb.Accel()
SENSITIVITY = 3
while True:
x = accel.x()
if x > SENSITIVITY:
xlights[0].on()
xlights[1].off()
elif x < -SENSITIVITY:
xlights[1].on()
xlights[0].off()
else:
xlights[0].off()
xlights[1].off()
y = accel.y()
if y > SENSITIVITY:
ylights[0].on()
ylights[1].off()
elif y < -SENSITIVITY:
ylights[1].on()
ylights[0].off()
else:
ylights[0].off()
ylights[1].off()
pyb.delay(100)
We start by creating a tuple of LED objects for the x and y directions. Tuples are immutable objects in python which
means they can’t be modified once they are created. We then proceed as before but turn on a different LED for positive
and negative x values. We then do the same for the y direction. This isn’t particularly sophisticated but it does the job.
Run this on your pyboard and you should see different LEDs turning on depending on how you tilt the board.
If something goes wrong with your pyboard, don’t panic! It is almost impossible for you to break the pyboard by
programming the wrong thing.
The first thing to try is to enter safe mode: this temporarily skips execution of boot.py and main.py and gives
default USB settings.
If you have problems with the filesystem you can do a factory reset, which restores the filesystem to its original state.
Entering safe mode is temporary, and does not make any changes to the files on the pyboard.
If you pyboard’s filesystem gets corrupted (for example, you forgot to eject/unmount it), or you have some code in
boot.py or main.py which you can’t escape from, then you can reset the filesystem.
Resetting the filesystem deletes all files on the internal pyboard storage (not the SD card), and restores the files
boot.py, main.py, README.txt and pybcdc.inf back to their original state.
To do a factory reset of the filesystem you follow a similar procedure as you did to enter safe mode, but release USR
on green+orange:
1. Connect the pyboard to USB so it powers up.
2. Hold down the USR switch.
3. While still holding down USR, press and release the RST switch.
4. The LEDs will then cycle green to orange to green+orange and back again.
5. Keep holding down USR until both the green and orange LEDs are lit, and then let go of the USR switch.
6. The green and orange LEDs should flash quickly 4 times.
7. The red LED will turn on (so red, green and orange are now on).
8. The pyboard is now resetting the filesystem (this takes a few seconds).
9. The LEDs all turn off.
10. You now have a reset filesystem, and are in safe mode.
11. Press and release the RST switch to boot normally.
The pyboard is a USB device, and can configured to act as a mouse instead of the default USB flash drive.
To do this we must first edit the boot.py file to change the USB configuration. If you have not yet touched your
boot.py file then it will look something like this:
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal
import pyb
#pyb.main(’main.py’) # main script to run after this one
#pyb.usb_mode(’CDC+MSC’) # act as a serial and a storage device
#pyb.usb_mode(’CDC+HID’) # act as a serial device and a mouse
To enable the mouse mode, uncomment the last line of the file, to make it look like:
pyb.usb_mode(’CDC+HID’) # act as a serial device and a mouse
If you already changed your boot.py file, then the minimum code it needs to work is:
import pyb
pyb.usb_mode(’CDC+HID’)
This tells the pyboard to configure itself as a CDC (serial) and HID (human interface device, in our case a mouse)
USB device when it boots up.
Eject/unmount the pyboard drive and reset it using the RST switch. Your PC should now detect the pyboard as a
mouse!
To get the py-mouse to do anything we need to send mouse events to the PC. We will first do this manually using the
REPL prompt. Connect to your pyboard using your serial program and type the following:
>>> pyb.hid((0, 10, 0, 0))
Your mouse should move 10 pixels to the right! In the command above you are sending 4 pieces of information: button
status, x, y and scroll. The number 10 is telling the PC that the mouse moved 10 pixels in the x direction.
Let’s make the mouse oscillate left and right:
>>> import math
>>> def osc(n, d):
... for i in range(n):
... pyb.hid((0, int(20 * math.sin(i / 10)), 0, 0))
... pyb.delay(d)
...
>>> osc(100, 50)
The first argument to the function osc is the number of mouse events to send, and the second argument is the delay
(in milliseconds) between events. Try playing around with different numbers.
Excercise: make the mouse go around in a circle.
Now lets make the mouse move based on the angle of the pyboard, using the accelerometer. The following code can
be typed directly at the REPL prompt, or put in the main.py file. Here, we’ll put in in main.py because to do that
we will learn how to go into safe mode.
At the moment the pyboard is acting as a serial USB device and an HID (a mouse). So you cannot access the filesystem
to edit your main.py file.
You also can’t edit your boot.py to get out of HID-mode and back to normal mode with a USB drive...
To get around this we need to go into safe mode. This was described in the [safe mode tutorial](tut-reset), but we
repeat the instructions here:
1. Hold down the USR switch.
2. While still holding down USR, press and release the RST switch.
3. The LEDs will then cycle green to orange to green+orange and back again.
4. Keep holding down USR until only the orange LED is lit, and then let go of the USR switch.
5. The orange LED should flash quickly 4 times, and then turn off.
6. You are now in safe mode.
In safe mode, the boot.py and main.py files are not executed, and so the pyboard boots up with default settings.
This means you now have access to the filesystem (the USB drive should appear), and you can edit main.py. (Leave
boot.py as-is, because we still want to go back to HID-mode after we finish editting main.py.)
switch = pyb.Switch()
accel = pyb.Accel()
Save your file, eject/unmount your pyboard drive, and reset it using the RST switch. It should now act as a mouse, and
the angle of the board will move the mouse around. Try it out, and see if you can make the mouse stand still!
Press the USR switch to stop the mouse motion.
You’ll note that the y-axis is inverted. That’s easy to fix: just put a minus sign in front of the y-coordinate in the
pyb.hid() line above.
If you leave your pyboard as-is, it’ll behave as a mouse everytime you plug it in. You probably want to change it back
to normal. To do this you need to first enter safe mode (see above), and then edit the boot.py file. In the boot.py
file, comment out (put a # in front of) the line with the CDC+HID setting, so it looks like:
#pyb.usb_mode(’CDC+HID’) # act as a serial device and a mouse
Save your file, eject/unmount the drive, and reset the pyboard. It is now back to normal operating mode.
The pyboard has 14 timers which each consist of an independent counter running at a user-defined frequency. They
can be set up to run a function at specific intervals. The 14 timers are numbered 1 through 14, but 3 is reserved for
internal use, and 5 and 6 are used for servo and ADC/DAC control. Avoid using these timers if possible.
Let’s create a timer object:
>>> tim = pyb.Timer(4)
The pyboard is telling us that tim is attached to timer number 4, but it’s not yet initialised. So let’s initialise it to
trigger at 10 Hz (that’s 10 times per second):
>>> tim.init(freq=10)
Now that it’s initialised, we can see some information about the timer:
>>> tim
Timer(4, prescaler=624, period=13439, mode=UP, div=1)
The information means that this timer is set to run at the peripheral clock speed divided by 624+1, and it will count
from 0 up to 13439, at which point it triggers an interrupt, and then starts counting again from 0. These num-
bers are set to make the timer trigger at 10 Hz: the source frequency of the timer is 84MHz (found by running
tim.source_freq()) so we get 84MHz / 625 / 13440 = 10Hz.
So what can we do with our timer? The most basic thing is to get the current value of its counter:
>>> tim.counter()
21504
The next thing we can do is register a callback function for the timer to execute when it triggers (see the [switch
tutorial](tut-switch) for an introduction to callback functions):
>>> tim.callback(lambda t:pyb.LED(1).toggle())
This should start the red LED flashing right away. It will be flashing at 5 Hz (2 toggle’s are needed for 1 flash, so
toggling at 10 Hz makes it flash at 5 Hz). You can change the frequency by re-initialising the timer:
>>> tim.init(freq=20)
The function that you pass to callback must take 1 argument, which is the timer object that triggered. This allows you
to control the timer from within the callback function.
We can create 2 timers and run them independently:
>>> tim4 = pyb.Timer(4, freq=10)
>>> tim7 = pyb.Timer(7, freq=20)
>>> tim4.callback(lambda t: pyb.LED(1).toggle())
>>> tim7.callback(lambda t: pyb.LED(2).toggle())
Because the callbacks are proper hardware interrupts, we can continue to use the pyboard for other things while these
timers are running.
You can use a timer to create a microsecond counter, which might be useful when you are doing something which
requires accurate timing. We will use timer 2 for this, since timer 2 has a 32-bit counter (so does timer 5, but if you
use timer 5 then you can’t use the Servo driver at the same time).
We set up timer 2 as follows:
>>> micros = pyb.Timer(2, prescaler=83, period=0x3fffffff)
The prescaler is set at 83, which makes this timer count at 1 MHz. This is because the CPU clock, running at 168
MHz, is divided by 2 and then by prescaler+1, giving a freqency of 168 MHz/2/(83+1)=1 MHz for timer 2. The period
is set to a large number so that the timer can count up to a large number before wrapping back around to zero. In this
case it will take about 17 minutes before it cycles back to zero.
To use this timer, it’s best to first reset it to 0:
>>> micros.counter(0)
Here you will learn how to write inline assembler in Micro Python.
Note: this is an advanced tutorial, intended for those who already know a bit about microcontrollers and assembly
language.
Micro Python includes an inline assembler. It allows you to write assembly routines as a Python function, and you can
call them as you would a normal Python function.
Inline assembler functions are denoted by a special function decorator. Let’s start with the simplest example:
@micropython.asm_thumb
def fun():
movw(r0, 42)
You can enter this in a script or at the REPL. This function takes no arguments and returns the number 42. r0 is a
register, and the value in this register when the function returns is the value that is returned. Micro Python always
interprets the r0 as an integer, and converts it to an integer object for the caller.
If you run print(fun()) you will see it print out 42.
Inline assembler functions can accept up to 3 arguments. If they are used, they must be named r0, r1 and r2 to
reflect the registers and the calling conventions.
Here is a function that adds its arguments:
@micropython.asm_thumb
def asm_add(r0, r1):
add(r0, r0, r1)
This performs the computation r0 = r0 + r1. Since the result is put in r0, that is what is returned. Try
asm_add(1, 2), it should return 3.
3.10.4 Loops
We can assign labels with label(my_label), and branch to them using b(my_label), or a conditional branch
like bgt(my_label).
The following example flashes the green LED. It flashes it r0 times.
@micropython.asm_thumb
def flash_led(r0):
# get the GPIOA address in r1
movwt(r1, stm.GPIOA)
# get the bit mask for PA14 (the pin LED #2 is on)
movw(r2, 1 << 14)
b(loop_entry)
label(loop1)
# turn LED on
strh(r2, [r1, stm.GPIO_BSRRL])
# loop r0 times
sub(r0, r0, 1)
label(loop_entry)
cmp(r0, 0)
bgt(loop1)
pyb.wfi() is used to reduce power consumption while waiting for an event such as an interrupt. You would use it
in the following situation:
while True:
do_some_processing()
pyb.wfi()
There are 4 dedicated connection points on the pyboard for connecting up hobby servo motors (see eg
[Wikipedia](http://en.wikipedia.org/wiki/Servo_%28radio_control%29)). These motors have 3 wires: ground, power
and signal. On the pyboard you can connect them in the bottom right corner, with the signal pin on the far right. Pins
X1, X2, X3 and X4 are the 4 dedicated servo signal pins.
In this picture there are male-male double adaptors to connect the servos to the header pins on the pyboard.
The ground wire on a servo is usually the darkest coloured one, either black or dark brown. The power wire will most
likely be red.
The power pin for the servos (labelled VIN) is connected directly to the input power source of the pyboard. When
powered via USB, VIN is powered through a diode by the 5V USB power line. Connect to USB, the pyboard can
power at least 4 small to medium sized servo motors.
If using a battery to power the pyboard and run servo motors, make sure it is not greater than 6V, since this is the
maximum voltage most servo motors can take. (Some motors take only up to 4.8V, so check what type you are using.)
Plug in a servo to position 1 (the one with pin X1) and create a servo object using:
>>> servo1 = pyb.Servo(1)
The angle here is measured in degrees, and ranges from about -90 to +90, depending on the motor. Calling angle
without parameters will return the current angle:
>>> servo1.angle()
-60
Note that for some angles, the returned angle is not exactly the same as the angle you set, due to rounding errors in
setting the pulse width.
You can pass a second parameter to the angle method, which specifies how long to take (in milliseconds) to reach
the desired angle. For example, to take 1 second (1000 milliseconds) to go from the current position to 50 degrees, use
>>> servo1.angle(50, 1000)
This command will return straight away and the servo will continue to move to the desired angle, and stop when it
gets there. You can use this feature as a speed control, or to synchronise 2 or more servo motors. If we have another
servo motor (servo2 = pyb.Servo(2)) then we can do
>>> servo1.angle(-45, 2000); servo2.angle(60, 2000)
This will move the servos together, making them both take 2 seconds to reach their final angles.
Note: the semicolon between the 2 expressions above is used so that they are executed one after the other when you
press enter at the REPL prompt. In a script you don’t need to do this, you can just write them one line after the other.
So far we have been using standard servos that move to a specific angle and stay at that angle. These servo motors
are useful to create joints of a robot, or things like pan-tilt mechanisms. Internally, the motor has a variable resistor
(potentiometer) which measures the current angle and applies power to the motor proportional to how far it is from the
desired angle. The desired angle is set by the width of a high-pulse on the servo signal wire. A pulse width of 1500
microsecond corresponds to the centre position (0 degrees). The pulses are sent at 50 Hz, ie 50 pulses per second.
You can also get continuous rotation servo motors which turn continuously clockwise or counterclockwise. The
direction and speed of rotation is set by the pulse width on the signal wire. A pulse width of 1500 microseconds
corresponds to a stopped motor. A pulse width smaller or larger than this means rotate one way or the other, at a given
speed.
On the pyboard, the servo object for a continuous rotation motor is the same as before. In fact, using angle you can
set the speed. But to make it easier to understand what is intended, there is another method called speed which sets
the speed:
>>> servo1.speed(30)
speed has the same functionality as angle: you can get the speed, set it, and set it with a time to reach the final
speed.
>>> servo1.speed()
30
>>> servo1.speed(-20)
>>> servo1.speed(0, 2000)
The final command above will set the motor to stop, but take 2 seconds to do it. This is essentially a control over the
acceleration of the continuous servo.
A servo speed of 100 (or -100) is considered maximum speed, but actually you can go a bit faster than that, depending
on the particular motor.
The only difference between the angle and speed methods (apart from the name) is the way the input numbers
(angle or speed) are converted to a pulse width.
Calibration
The conversion from angle or speed to pulse width is done by the servo object using its calibration values. To get the
current calibration, use
>>> servo1.calibration()
(640, 2420, 1500, 2470, 2200)
Of course, you would change the above values to suit your particular servo motor.
In addition to turning LEDs on and off, it is also possible to control the brightness of an LED using Pulse-Width
Modulation (PWM), a common technique for obtaining variable output from a digital pin. This allows us to fade an
LED:
Components
• Wires
• Breadboard (optional, but makes things easier)
Connecting Things Up
For this tutorial, we will use the X1 pin. Connect one end of the resistor to X1, and the other end to the anode of the
LED, which is the longer leg. Connect the cathode of the LED to ground.
Code
By examining the Quick reference for the pyboard, we see that X1 is connected to channel 1 of timer 5 (TIM5 CH1).
Therefore we will first create a Timer object for timer 5, then create a TimerChannel object for channel 1:
from pyb import Timer
from time import sleep
Brightness of the LED in PWM is controlled by controlling the pulse-width, that is the amount of time the LED is on
every cycle. With a timer frequency of 100 Hz, each cycle takes 0.01 second, or 10 ms.
To achieve the fading effect shown at the beginning of this tutorial, we want to set the pulse-width to a small value,
then slowly increase the pulse-width to brighten the LED, and start over when we reach some maximum brightness:
# maximum and minimum pulse-width, which corresponds to maximum
# and minimum brightness
max_width = 200000
min_width = 20000
while True:
tchannel.pulse_width(cur_width)
cur_width += wstep
Breathing Effect
If we want to have a breathing effect, where the LED fades from dim to bright then bright to dim, then we simply need
to reverse the sign of wstep when we reach maximum brightness, and reverse it again at minimum brightness. To do
this we modify the while loop to be:
while True:
tchannel.pulse_width(cur_width)
sleep(0.01)
cur_width += wstep
Advanced Exercise
You may have noticed that the LED brightness seems to fade slowly, but increases quickly. This is because our eyes
interprets brightness logarithmically (Weber’s Law ), while the LED’s brightness changes linearly, that is by the same
amount each time. How do you solve this problem? (Hint: what is the opposite of the logarithmic function?)
Addendum
We could have also used the digital-to-analog converter (DAC) to achieve the same effect. The PWM method has the
advantage that it drives the LED with the same current each time, but for different lengths of time. This allows better
control over the brightness, because LEDs do not necessarily exhibit a linear relationship between the driving current
and brightness.
The following video shows how to solder the headers onto the LCD skin. At the end of the video, it shows you how to
correctly connect the LCD skin to the pyboard.
For circuit schematics and datasheets for the components on the skin see The pyboard hardware.
To get started using the LCD, try the following at the Micro Python prompt. Make sure the LCD skin is attached to
the pyboard as pictured at the top of this page.
>>> import pyb
>>> lcd = pyb.LCD(’X’)
>>> lcd.light(True)
>>> lcd.write(’Hello uPy!\n’)
To read the touch-sensor data you need to use the I2C bus. The MPR121 capacitive touch sensor has address 90.
The first line above makes an I2C object, and the second line enables the 4 touch sensors. The third line reads the
touch status and the touch variable holds the state of the 4 touch buttons (A, B, X, Y).
There is a simple driver here which allows you to set the threshold and debounce parameters, and easily read the touch
status and electrode voltage levels. Copy this script to your pyboard (either flash or SD card, in the top directory or
lib/ directory) and then try:
>>> import pyb
>>> import mpr121
>>> m = mpr121.MPR121(pyb.I2C(1, pyb.I2C.MASTER))
>>> for i in range(100):
... print(m.touch_status())
... pyb.delay(100)
...
This will continuously print out the touch status of all electrodes. Try touching each one in turn.
Note that if you put the LCD skin in the Y-position, then you need to initialise the I2C bus using:
>>> m = mpr121.MPR121(pyb.I2C(2, pyb.I2C.MASTER))
There is also a demo which uses the LCD and the touch sensors together, and can be found here.
The following video shows how to solder the headers, microphone and speaker onto the AMP skin.
For circuit schematics and datasheets for the components on the skin see The pyboard hardware.
Example code
The AMP skin has a speaker which is connected to DAC(1) via a small power amplifier. The volume of the amplifier
is controlled by a digital potentiometer, which is an I2C device with address 46 on the IC2(1) bus.
To set the volume, define the following function:
import pyb
def volume(val):
pyb.I2C(1, pyb.I2C.MASTER).mem_write(val, 46, 0)
To play a sound, use the write_timed method of the DAC object. For example:
import math
from pyb import DAC
You can also play WAV files using the Python wave module. You can get the wave module here and you will also
need the chunk module available here. Put these on your pyboard (either on the flash or the SD card in the top-level
directory). You will need an 8-bit WAV file to play, such as this one, or to convert any file you have with the command:
avconv -i original.wav -ar 22050 -codec pcm_u8 test.wav
A pin used as input from a switch or other mechanical device can have a lot of noise on it, rapidly changing from
low to high when the switch is first pressed or released. This noise can be eliminated using a capacitor (a debouncing
circuit). It can also be eliminated using a simple function that makes sure the value on the pin is stable.
The following function does just this. It gets the current value of the given pin, and then waits for the value to change.
The new pin value must be stable for a continuous 20ms for it to register the change. You can adjust this time (to say
50ms) if you still have noise.
import pyb
def wait_pin_change(pin):
# wait for pin to change value
# it needs to be stable for a continuous 20ms
cur_value = pin.value()
active = 0
while active < 20:
if pin.value() != cur_value:
active += 1
else:
active = 0
pyb.delay(1)
The cmath module provides some basic mathematical funtions for working with complex numbers.
Functions
cmath.cos(z)
Return the cosine of z.
cmath.exp(z)
Return the exponential of z.
cmath.log(z)
Return the natural logarithm of z. The branch cut is along the negative real axis.
cmath.log10(z)
Return the base-10 logarithm of z. The branch cut is along the negative real axis.
cmath.phase(z)
Returns the phase of the number z, in the range (-pi, +pi].
cmath.polar(z)
Returns, as a tuple, the polar form of z.
cmath.rect(r, phi)
Returns the complex number with modulus r and phase phi.
cmath.sin(z)
Return the sine of z.
cmath.sqrt(z)
Return the square-root of z.
37
Micro Python Documentation, Release 1.4
Constants
cmath.e
base of the natural logarithm
cmath.pi
the ratio of a circle’s circumference to its diameter
Functions
gc.enable()
Enable automatic garbage collection.
gc.disable()
Disable automatic garbage collection. Heap memory can still be allocated, and garbage collection can still be
initiated manually using gc.collect().
gc.collect()
Run a garbage collection.
gc.mem_alloc()
Return the number of bytes of heap RAM that are allocated.
gc.mem_free()
Return the number of bytes of available heap RAM.
The math module provides some basic mathematical funtions for working with floating-point numbers.
Note: On the pyboard, floating-point numbers have 32-bit precision.
Functions
math.acos(x)
Return the inverse cosine of x.
math.acosh(x)
Return the inverse hyperbolic cosine of x.
math.asin(x)
Return the inverse sine of x.
math.asinh(x)
Return the inverse hyperbolic sine of x.
math.atan(x)
Return the inverse tangent of x.
math.atan2(y, x)
Return the principal value of the inverse tangent of y/x.
math.atanh(x)
Return the inverse hyperbolic tangent of x.
math.ceil(x)
Return an integer, being x rounded towards positive infinity.
math.copysign(x, y)
Return x with the sign of y.
math.cos(x)
Return the cosine of x.
math.cosh(x)
Return the hyperbolic cosine of x.
math.degrees(x)
Return radians x converted to degrees.
math.erf(x)
Return the error function of x.
math.erfc(x)
Return the complementary error function of x.
math.exp(x)
Return the exponential of x.
math.expm1(x)
Return exp(x) - 1.
math.fabs(x)
Return the absolute value of x.
math.floor(x)
Return an integer, being x rounded towards negative infinity.
math.fmod(x, y)
Return the remainder of x/y.
math.frexp(x)
Decomposes a floating-point number into its mantissa and exponent. The returned value is the tuple (m, e)
such that x == m * 2**e exactly. If x == 0 then the function returns (0.0, 0), otherwise the relation
0.5 <= abs(m) < 1 holds.
math.gamma(x)
Return the gamma function of x.
math.isfinite(x)
Return True if x is finite.
math.isinf(x)
Return True if x is infinite.
math.isnan(x)
Return True if x is not-a-number
math.ldexp(x, exp)
Return x * (2**exp).
math.lgamma(x)
Return the natural logarithm of the gamma function of x.
math.log(x)
Return the natural logarithm of x.
math.log10(x)
Return the base-10 logarithm of x.
math.log2(x)
Return the base-2 logarithm of x.
math.modf(x)
Return a tuple of two floats, being the fractional and integral parts of x. Both return values have the same sign
as x.
math.pow(x, y)
Returns x to the power of y.
math.radians(x)
Return degrees x converted to radians.
math.sin(x)
Return the sine of x.
math.sinh(x)
Return the hyperbolic sine of x.
math.sqrt(x)
Return the square root of x.
math.tan(x)
Return the tangent of x.
math.tanh(x)
Return the hyperbolic tangent of x.
math.trunc(x)
Return an integer, being x rounded towards 0.
Constants
math.e
base of the natural logarithm
math.pi
the ratio of a circle’s circumference to its diameter
Pyboard specifics
The filesystem on the pyboard has / as the root directory and the available physical drives are accessible from here.
They are currently:
/flash – the internal flash filesystem
/sd – the SD card (if it exists)
On boot up, the current directory is /flash if no SD card is inserted, otherwise it is /sd.
Functions
os.chdir(path)
Change current directory.
os.getcwd()
Get the current directory.
os.listdir([dir ])
With no argument, list the current directory. Otherwise list the given directory.
os.mkdir(path)
Create a new directory.
os.remove(path)
Remove a file.
os.rmdir(path)
Remove a directory.
os.stat(path)
Get the status of a file or directory.
os.sync()
Sync all filesystems.
os.urandom(n)
Return a bytes object with n random bytes, generated by the hardware random number generator.
Constants
os.sep
separation character used in paths
This module provides functions to wait for events on streams (select streams which are ready for operations).
Pyboard specifics
Polling is an efficient way of waiting for read/write activity on multiple objects. Current objects that support polling
are: pyb.UART, pyb.USB_VCP.
Functions
select.poll()
Create an instance of the Poll class.
select.select(rlist, wlist, xlist[, timeout ])
Wait for activity on a set of objects.
This function is provided for compatibility and is not efficient. Usage of Poll is recommended instead.
class Poll
Methods
poll.register(obj[, eventmask ])
Register obj for polling. eventmask is 1 for read, 2 for write, 3 for read-write.
poll.unregister(obj)
Unregister obj from polling.
poll.modify(obj, eventmask)
Modify the eventmask for obj.
poll.poll([timeout ])
Wait for at least one of the registered objects to become ready. Returns list of ready objects, or empty list on
timeout.
Timeout is in milliseconds.
Functions
struct.calcsize(fmt)
Return the number of bytes needed to store the given fmt.
struct.pack(fmt, v1, v2, ...)
Pack the values v1, v2, ... according to the format string fmt. The return value is a bytes object encoding the
values.
struct.unpack(fmt, data)
Unpack from the data according to the format string fmt. The return value is a tuple of the unpacked values.
Functions
sys.exit([retval ])
Raise a SystemExit exception. If an argument is given, it is the value given to SystemExit.
sys.print_exception(exc[, file ])
Print exception with a traceback to a file-like object file (or sys.stdout by default).
Difference to CPython
This function appears in the traceback module in CPython.
Constants
sys.argv
a mutable list of arguments this program started with
sys.byteorder
the byte order of the system (“little” or “big”)
sys.path
a mutable list of directories to search for imported modules
sys.platform
The platform that Micro Python is running on. This is “pyboard” on the pyboard and provides a robust way of
determining if a script is running on the pyboard or not.
sys.stderr
standard error (connected to USB VCP, and optional UART object)
sys.stdin
standard input (connected to USB VCP, and optional UART object)
sys.stdout
standard output (connected to USB VCP, and optional UART object)
sys.version
Python language version that this implementation conforms to, as a string
sys.version_info
Python language version that this implementation conforms to, as a tuple of ints
The time module provides functions for getting the current time and date, and for sleeping.
Functions
time.localtime([secs ])
Convert a time expressed in seconds since Jan 1, 2000 into an 8-tuple which contains: (year, month, mday, hour,
minute, second, weekday, yearday) If secs is not provided or None, then the current time from the RTC is used.
year includes the century (for example 2014).
•month is 1-12
•mday is 1-31
•hour is 0-23
•minute is 0-59
•second is 0-59
•weekday is 0-6 for Mon-Sun
•yearday is 1-366
time.mktime()
This is inverse function of localtime. It’s argument is a full 8-tuple which expresses a time as per localtime. It
returns an integer which is the number of seconds since Jan 1, 2000.
time.sleep(seconds)
Sleep for the given number of seconds. Seconds can be a floating-point number to sleep for a fractional number
of seconds.
time.time()
Returns the number of seconds, as an integer, since 1/1/2000.
The following standard Python libraries have been “micro-ified” to fit in with the philosophy of Micro Python. They
provide the core functionality of that module and are intended to be a drop-in replacement for the standard Python
library.
The modules are available by their u-name, and also by their non-u-name. The non-u-name can be overridden by a
file of that name in your package path. For example, import json will first search for a file json.py or directory
json and load that package if it is found. If nothing is found, it will fallback to loading the built-in ujson module.
This module implements conversions between binary data and various encodings of it in ASCII form (in both direc-
tions).
Functions
ubinascii.hexlify(data)
Convert binary data to hexadecimal representation. Return bytes string.
This module implements “foreign data interface” for MicroPython. The idea behind it is similar to CPython’s ctypes
modules, but actual API is different, steamlined and optimized for small size.
Structure layout is defined by a “descriptor” - a Python dictionary which encodes field names as keys and other
properties required to access them as an associated values. Currently, uctypes requires explicit specification of offsets
for each field. Offset are given in bytes from structure start.
Following are encoding examples for various field types:
Scalar types:
"field_name": uctypes.UINT32 | 0
in other words, value is scalar type identifier ORed with field offset (in bytes) from the start of the struc-
ture.
Recursive structures:
"sub": (2, {
"b0": uctypes.UINT8 | 0,
"b1": uctypes.UINT8 | 1,
})
i.e. value is a 2-tuple, first element of which is offset, and second is a structure descriptor dictionary (note:
offsets in recursive descriptors are relative to a structure it defines).
Arrays of primitive types:
"arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2),
i.e. value is a 2-tuple, first element of which is ARRAY flag ORed with offset, and second is scalar
element type ORed number of elements in array.
Arrays of aggregate types:
"arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}),
i.e. value is a 3-tuple, first element of which is ARRAY flag ORed with offset, second is a number of
elements in array, and third is descriptor of element type.
Pointer to a primitive type:
"ptr": (uctypes.PTR | 0, uctypes.UINT8),
i.e. value is a 2-tuple, first element of which is PTR flag ORed with offset, and second is scalar element
type.
Pointer to aggregate type:
"ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}),
i.e. value is a 2-tuple, first element of which is PTR flag ORed with offset, second is descriptor of type
pointed to.
Bitfields:
"bitf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 8 << uctypes.BF_LEN,
i.e. value is type of scalar value containing given bitfield (typenames are similar to scalar types, but
prefixes with “BF”), ORed with offset for scalar value containing the bitfield, and further ORed with
values for bit offset and bit length of the bitfield within scalar value, shifted by BF_POS and BF_LEN
positions, respectively. Bitfield position is counted from the least significant bit, and is the number of
right-most bit of a field (in other words, it’s a number of bits a scalar needs to be shifted right to extra the
bitfield).
In the example above, first UINT16 value will be extracted at offset 0 (this detail may be important
when accessing hardware registers, where particular access size and alignment are required), and then
bitfield whose rightmost bit is least-significant bit of this UINT16, and length is 8 bits, will be extracted -
effectively, this will access least-significant byte of UINT16.
Note that bitfield operations are independent of target byte endianness, in particular, example above will
access least-significant byte of UINT16 in both little- and big-endian structures. But it depends on the
least significant bit being numbered 0. Some targets may use different numbering in their native ABI, but
uctypes always uses normalized numbering described above.
Module contents
uctypes.sizeof(struct)
Return size of data structure in bytes. Argument can be either structure class or specific instantiated structure
object (or its field).
uctypes.addressof(obj)
Return address of an object. Argument should be bytes, bytearray or other object supporting buffer protocol
(and address of this buffer is what actually returned).
uctypes.bytes_at(addr, size)
Capture memory at the given address and size as bytes object. As bytes object is immutable, memory is actually
duplicated and copied into bytes object, so if memory contents change later, created object retains original value.
uctypes.bytearray_at(addr, size)
Capture memory at the given address and size as bytearray object. Unlike bytes_at() function above, memory
is captured by reference, so it can be both written too, and you will access current value at the given memory
address.
Structure objects
Structure objects allow accessing individual fields using standard dot notation: my_struct.field1. If a field is
of scalar type, getting it will produce primitive value (Python integer or float) corresponding to value contained in a
field. Scalar field can also be assigned to.
If a field is an array, its individual elements can be accessed with standard subscript operator - both read and assigned
to.
If a field is a pointer, it can be dereferenced using [0] syntax (corresponding to C * operator, though [0] works in C
too). Subscripting pointer with other integer values but 0 are supported too, with the same semantics as in C.
Summing up, accessing structure fields generally follows C syntax, except for pointer derefence, you need to use [0]
operator instead of *.
This module implements binary data hashing algorithms. Currently, it implements SHA256 algorithm. Choosing
SHA256 was a deliberate choice, as a modern, cryptographically secure algorithm. This means that a single algorithm
can cover both usecases of “any hash algorithm” and security-related usage, and thus save space omitting legacy
algorithms like MD5 or SHA1.
Constructors
class uhashlib.sha256([data ])
Create a hasher object and optionally feed data into it.
Methods
sha256.update(data)
Feed more binary data into hash.
sha256.digest()
Return hash for all data passed thru hash, as a bytes object. After this method is called, more data cannot be fed
into hash any longer.
sha256.hexdigest()
This method is NOT implemented. Use ubinascii.hexlify(sha256.digest()) to achieve similar
effect.
Functions
uheapq.heappush(heap, item)
Push the item onto the heap.
uheapq.heappop(heap)
Pop the first item from the heap, and return it. Raises IndexError if heap is empty.
uheapq.heapify(x)
Convert the list x into a heap. This is an in-place operation.
This modules allows to convert between Python objects and the JSON data format.
Functions
ujson.dumps(obj)
Return obj represented as a JSON string.
ujson.loads(str)
Parse the JSON str and return an object. Raises ValueError if the string is not correctly formed.
This module implements regular expression operations. Regular expression syntax supported is a subset of CPython
re module (and actually is a subset of POSIX extended regular expressions).
Supported operators are:
’.’ Match any character.
’[]’ Match set of characters. Individual characters and ranges are supported.
’^’
’$’
’?’
’*’
’+’
’??’
’*?’
’+?’
Counted repetitions ({m,n}), more advanced assertions, names groups, etc. are not supported.
Functions
ure.compile(regex)
Compile regular expression, return regex object.
ure.match(regex, string)
Match regex against string. Match always happens from starting position in a string.
ure.search(regex, string)
Search regex in a string. Unlike match, this will search string for first position which matches regex
(which still may be 0 if regex is anchored).
ure.DEBUG
Flag value, display debug information about compiled expression.
Regex objects
Compiled regular expression. Instances of this class are created using ure.compile().
regex.match(string)
regex.search(string)
regex.split(string, max_split=-1)
Match objects
Socket functionality.
Functions
usocket.getaddrinfo(host, port)
usocket.socket(family=AF_INET, type=SOCK_STREAM, fileno=-1)
Create a socket.
This modules allows to decompress binary data compressed with DEFLATE algorithm (commonly used in zlib library
and gzip archiver). Compression is not yet implemented.
Functions
uzlib.decompress(data)
Return decompressed data as bytes.
pyb.delay(ms)
Delay for the given number of milliseconds.
pyb.udelay(us)
Delay for the given number of microseconds.
pyb.millis()
Returns the number of milliseconds since the board was last reset.
The result is always a micropython smallint (31-bit signed number), so after 2^30 milliseconds (about 12.4 days)
this will start to return negative numbers.
pyb.micros()
Returns the number of microseconds since the board was last reset.
The result is always a micropython smallint (31-bit signed number), so after 2^30 microseconds (about 17.8
minutes) this will start to return negative numbers.
pyb.elapsed_millis(start)
Returns the number of milliseconds which have elapsed since start.
This function takes care of counter wrap, and always returns a positive number. This means it can be used to
measure periods upto about 12.4 days.
Example:
start = pyb.millis()
while pyb.elapsed_millis(start) < 1000:
# Perform some operation
pyb.elapsed_micros(start)
Returns the number of microseconds which have elapsed since start.
This function takes care of counter wrap, and always returns a positive number. This means it can be used to
measure periods upto about 17.8 minutes.
Example:
start = pyb.micros()
while pyb.elapsed_micros(start) < 1000:
# Perform some operation
pass
pyb.hard_reset()
Resets the pyboard in a manner similar to pushing the external RESET button.
pyb.bootloader()
Activate the bootloader without BOOT* pins.
pyb.disable_irq()
Disable interrupt requests. Returns the previous IRQ state: False/True for disabled/enabled IRQs respec-
tively. This return value can be passed to enable_irq to restore the IRQ to its original state.
pyb.enable_irq(state=True)
Enable interrupt requests. If state is True (the default value) then IRQs are enabled. If state is False
then IRQs are disabled. The most common use of this function is to pass it the value returned by disable_irq
to exit a critical section.
pyb.standby()
pyb.stop()
Miscellaneous functions
pyb.have_cdc()
Return True if USB is connected as a serial device, False otherwise.
pyb.hid((buttons, x, y, z))
Takes a 4-tuple (or list) and sends it to the USB host (the PC) to signal a HID mouse-motion event.
pyb.info([dump_alloc_table ])
Print out lots of information about the board.
pyb.mount(device, mountpoint, *, readonly=False, mkfs=False)
Mount a block device and make it available as part of the filesystem. device must be an object that provides
the block protocol:
•readblocks(self, blocknum, buf)
•writeblocks(self, blocknum, buf) (optional)
•count(self)
•sync(self) (optional)
readblocks and writeblocks should copy data between buf and the block device, starting from block
number blocknum on the device. buf will be a bytearray with length a multiple of 512. If writeblocks is
not defined then the device is mounted read-only. The return value of these two functions is ignored.
count should return the number of blocks available on the device. sync, if implemented, should sync the data
on the device.
The parameter mountpoint is the location in the root of the filesystem to mount the device. It must begin
with a forward-slash.
If readonly is True, then the device is mounted read-only, otherwise it is mounted read-write.
If mkfs is True, then a new filesystem is created if one does not already exist.
To unmount a device, pass None as the device and the mount location as mountpoint.
pyb.repl_uart(uart)
Get or set the UART object that the REPL is repeated on.
pyb.rng()
Return a 30-bit hardware generated random number.
pyb.sync()
Sync all file systems.
pyb.unique_id()
Returns a string of 12 bytes (96 bits), which is the unique ID for the MCU.
Classes
Constructors
class pyb.Accel
Create and return an accelerometer object.
Note: if you read accelerometer values immediately after creating this object you will get 0. It takes around
20ms for the first sample to be ready, so, unless you have some other code between creating this object and
reading its values, you should put a pyb.delay(20) after creating it. For example:
accel = pyb.Accel()
pyb.delay(20)
print(accel.x())
Methods
accel.filtered_xyz()
Get a 3-tuple of filtered x, y and z values.
accel.tilt()
Get the tilt register.
accel.x()
Get the x-axis value.
accel.y()
Get the y-axis value.
accel.z()
Get the z-axis value.
Usage:
import pyb
Constructors
class pyb.ADC(pin)
Create an ADC object associated with the given pin. This allows you to then read analog values on that pin.
Methods
adc.read()
Read the value on the analog pin and return it. The returned value will be between 0 and 4095.
adc.read_timed(buf, freq)
Read analog values into the given buffer at the given frequency. Buffer can be bytearray or array.array for
example. If a buffer with 8-bit elements is used, sample resolution will be reduced to 8 bits.
Example:
adc = pyb.ADC(pyb.Pin.board.X19) # create an ADC on pin X19
buf = bytearray(100) # create a buffer of 100 bytes
adc.read_timed(buf, 10) # read analog values into buf at 10Hz
# this will take 10 seconds to finish
for val in buf: # loop over all values
print(val) # print the value out
CAN implements the standard CAN communications protocol. At the physical level it consists of 2 lines: RX and
TX. Note that to connect the pyboard to a CAN bus you must use a CAN transceiver to convert the CAN logic signals
from the pyboard to the correct voltage levels on the bus.
Example usage (works without anything connected):
from pyb import CAN
can = CAN(1, CAN.LOOPBACK)
can.setfilter(0, CAN.LIST16, 0, (123, 124, 125, 126)) # set a filter to receive messages with id=123
can.send(’message!’, 123) # send a message with id 123
can.recv(0) # receive message on FIFO 0
Constructors
class pyb.CAN(bus, ...)
Construct a CAN object on the given bus. bus can be 1-2, or ‘YA’ or ‘YB’. With no additional parameters, the
CAN object is created but not initialised (it has the settings from the last initialisation of the bus, if any). If extra
arguments are given, the bus is initialised. See init for parameters of initialisation.
The physical pins of the CAN busses are:
•CAN(1) is on YA: (RX, TX) = (Y3, Y4) = (PB8, PB9)
•CAN(2) is on YB: (RX, TX) = (Y5, Y6) = (PB12, PB13)
Class Methods
CAN.initfilterbanks(nr)
Reset and disable all filter banks and assign how many banks should be available for CAN(1).
STM32F405 has 28 filter banks that are shared between the two available CAN bus controllers. This function
configures how many filter banks should be assigned to each. nr is the number of banks that will be assigned
to CAN(1), the rest of the 28 are assigned to CAN(2). At boot, 14 banks are assigned to each controller.
Methods
can.init(mode, extframe=False, prescaler=100, *, sjw=1, bs1=6, bs2=8)
Initialise the CAN bus with the given parameters:
•mode is one of: NORMAL, LOOPBACK, SILENT, SILENT_LOOPBACK
•if extframe is True then the bus uses extended identifiers in the frames (29 bits); otherwise it uses
standard 11 bit identifiers
•prescaler is used to set the duration of 1 time quanta; the time quanta will be the input clock (PCLK1,
see pyb.freq()) divided by the prescaler
•sjw is the resynchronisation jump width in units of the time quanta; it can be 1, 2, 3, 4
•bs1 defines the location of the sample point in units of the time quanta; it can be between 1 and 1024
inclusive
•bs2 defines the location of the transmit point in units of the time quanta; it can be between 1 and 16
inclusive
The time quanta tq is the basic unit of time for the CAN bus. tq is the CAN prescaler value divided by PCLK1
(the frequency of internal peripheral bus 1); see pyb.freq() to determine PCLK1.
A single bit is made up of the synchronisation segment, which is always 1 tq. Then follows bit segment 1, then
bit segment 2. The sample point is after bit segment 1 finishes. The transmit point is after bit segment 2 finishes.
The baud rate will be 1/bittime, where the bittime is 1 + BS1 + BS2 multiplied by the time quanta tq.
For example, with PCLK1=42MHz, prescaler=100, sjw=1, bs1=6, bs2=8, the value of tq is 2.38 microseconds.
The bittime is 35.7 microseconds, and the baudrate is 28kHz.
See page 680 of the STM32F405 datasheet for more details.
can.deinit()
Turn off the CAN bus.
can.setfilter(bank, mode, fifo, params)
Configure a filter bank:
•bank is the filter bank that is to be configured.
•mode is the mode the filter should operate in.
•fifo is which fifo (0 or 1) a message should be stored in, if it is accepted by this filter.
•params is an array of values the defines the filter. The contents of the array depends on the mode
argument.
mode contents of parameter array
CAN.LIST16 Four 16 bit ids that will be accepted
CAN.LIST32 Two 32 bit ids that will be accepted
CAN.MASK16
Two 16 bit id/mask pairs. E.g. (1, 3, 4, 4)
The first pair, 1 and 3 will accept all ids
that have bit 0 = 1 and bit 1 = 0.
The second pair, 4 and 4, will accept all ids
that have bit 2 = 1.
Constants
CAN.NORMAL
CAN.LOOPBACK
CAN.SILENT
CAN.SILENT_LOOPBACK
the mode of the CAN bus
CAN.LIST16
CAN.MASK16
CAN.LIST32
CAN.MASK32
the operation mode of a filter
The DAC is used to output analog values (a specific voltage) on pin X5 or pin X6. The voltage will be between 0 and
3.3V.
This module will undergo changes to the API.
Example usage:
from pyb import DAC
Constructors
class pyb.DAC(port)
Construct a new DAC object.
port can be a pin object, or an integer (1 or 2). DAC(1) is on pin X5 and DAC(2) is on pin X6.
Methods
dac.noise(freq)
Generate a pseudo-random noise signal. A new random sample is written to the DAC output at the given
frequency.
dac.triangle(freq)
Generate a triangle wave. The value on the DAC output changes at the given frequency, and the frequence of
the repeating triangle wave itself is 2048 times smaller.
dac.write(value)
Direct access to the DAC output (8 bit only at the moment).
dac.write_timed(data, freq, *, mode=DAC.NORMAL)
Initiates a burst of RAM to DAC using a DMA transfer. The input data is treated as an array of bytes (8 bit data).
mode can be DAC.NORMAL or DAC.CIRCULAR.
TIM6 is used to control the frequency of the transfer.
There are a total of 22 interrupt lines. 16 of these can come from GPIO pins and the remaining 6 are from internal
sources.
For lines 0 thru 15, a given line can map to the corresponding line from an arbitrary port. So line 0 can map to Px0
where x is A, B, C, ... and line 1 can map to Px1 where x is A, B, C, ...
def callback(line):
print("line =", line)
Now every time a falling edge is seen on the X1 pin, the callback will be called. Caution: mechani-
cal pushbuttons have “bounce” and pushing or releasing a switch will often generate multiple edges. See:
http://www.eng.utah.edu/~cs5780/debouncing.pdf for a detailed explanation, along with various techniques for de-
bouncing.
Trying to register 2 callbacks onto the same pin will throw an exception.
If pin is passed as an integer, then it is assumed to map to one of the internal interrupt sources, and must be in the
range 16 thru 22.
All other pin objects go through the pin mapper to come up with one of the gpio pins.
extint = pyb.ExtInt(pin, mode, pull, callback)
Constructors
class pyb.ExtInt(pin, mode, pull, callback)
Create an ExtInt object:
•pin is the pin on which to enable the interrupt (can be a pin object or any valid pin name).
•mode can be one of: - ExtInt.IRQ_RISING - trigger on a rising edge; - ExtInt.IRQ_FALLING -
trigger on a falling edge; - ExtInt.IRQ_RISING_FALLING - trigger on a rising or falling edge.
•pull can be one of: - pyb.Pin.PULL_NONE - no pull up or down resistors; - pyb.Pin.PULL_UP -
enable the pull-up resistor; - pyb.Pin.PULL_DOWN - enable the pull-down resistor.
•callback is the function to call when the interrupt triggers. The callback function must accept exactly
1 argument, which is the line that triggered the interrupt.
Class methods
ExtInt.regs()
Dump the values of the EXTI registers.
Methods
extint.disable()
Disable the interrupt associated with the ExtInt object. This could be useful for debouncing.
extint.enable()
Enable a disabled interrupt.
extint.line()
Return the line number that the pin is mapped to.
extint.swint()
Trigger the callback from software.
Constants
ExtInt.IRQ_FALLING
interrupt on a falling edge
ExtInt.IRQ_RISING
interrupt on a rising edge
ExtInt.IRQ_RISING_FALLING
interrupt on a rising or falling edge
I2C is a two-wire protocol for communicating between devices. At the physical level it consists of 2 wires: SCL and
SDA, the clock and data lines respectively.
I2C objects are created attached to a specific bus. They can be initialised when created, or initialised later on:
from pyb import I2C
Printing the i2c object gives you information about its configuration.
Basic methods for slave are send and recv:
i2c.send(’abc’) # send 3 bytes
i2c.send(0x42) # send a single byte, given by the number
data = i2c.recv(3) # receive 3 bytes
Constructors
class pyb.I2C(bus, ...)
Construct an I2C object on the given bus. bus can be 1 or 2. With no additional parameters, the I2C object is
created but not initialised (it has the settings from the last initialisation of the bus, if any). If extra arguments are
given, the bus is initialised. See init for parameters of initialisation.
The physical pins of the I2C busses are:
•I2C(1) is on the X position: (SCL, SDA) = (X9, X10) = (PB6, PB7)
•I2C(2) is on the Y position: (SCL, SDA) = (Y9, Y10) = (PB10, PB11)
Methods
i2c.deinit()
Turn off the I2C bus.
i2c.init(mode, *, addr=0x12, baudrate=400000, gencall=False)
Initialise the I2C bus with the given parameters:
•mode must be either I2C.MASTER or I2C.SLAVE
•addr is the 7-bit address (only sensible for a slave)
•baudrate is the SCL clock rate (only sensible for a master)
•gencall is whether to support general call mode
i2c.is_ready(addr)
Check if an I2C device responds to the given address. Only valid when in master mode.
i2c.mem_read(data, addr, memaddr, timeout=5000, addr_size=8)
Read from the memory of an I2C device:
•data can be an integer (number of bytes to read) or a buffer to read into
•addr is the I2C device address
•memaddr is the memory location within the I2C device
•timeout is the timeout in milliseconds to wait for the read
•addr_size selects width of memaddr: 8 or 16 bits
Returns the read data. This is only valid in master mode.
i2c.mem_write(data, addr, memaddr, timeout=5000, addr_size=8)
Write to the memory of an I2C device:
•data can be an integer or a buffer to write from
•addr is the I2C device address
•memaddr is the memory location within the I2C device
•timeout is the timeout in milliseconds to wait for the write
Constants
I2C.MASTER
for initialising the bus to master mode
I2C.SLAVE
for initialising the bus to slave mode
The LCD class is used to control the LCD on the LCD touch-sensor pyskin, LCD32MKv1.0. The LCD is a 128x32
pixel monochrome screen, part NHD-C12832A1Z.
The pyskin must be connected in either the X or Y positions, and then an LCD object is made using:
lcd = pyb.LCD(’X’) # if pyskin is in the X position
lcd = pyb.LCD(’Y’) # if pyskin is in the Y position
This driver implements a double buffer for setting/getting pixels. For example, to make a bouncing dot, try:
x = y = 0
dx = dy = 1
while True:
# update the dot’s position
x += dx
y += dy
Constructors
class pyb.LCD(skin_position)
Construct an LCD object in the given skin position. skin_position can be ‘X’ or ‘Y’, and should match
the position where the LCD pyskin is plugged in.
Methods
lcd.command(instr_data, buf )
Send an arbitrary command to the LCD. Pass 0 for instr_data to send an instruction, otherwise pass 1 to
send data. buf is a buffer with the instructions/data to send.
lcd.contrast(value)
Set the contrast of the LCD. Valid values are between 0 and 47.
lcd.fill(colour)
Fill the screen with the given colour (0 or 1 for white or black).
This method writes to the hidden buffer. Use show() to show the buffer.
lcd.get(x, y)
Get the pixel at the position (x, y). Returns 0 or 1.
This method reads from the visible buffer.
lcd.light(value)
Turn the backlight on/off. True or 1 turns it on, False or 0 turns it off.
lcd.pixel(x, y, colour)
Set the pixel at (x, y) to the given colour (0 or 1).
This method writes to the hidden buffer. Use show() to show the buffer.
lcd.show()
Show the hidden buffer on the screen.
lcd.text(str, x, y, colour)
Draw the given text to the position (x, y) using the given colour (0 or 1).
This method writes to the hidden buffer. Use show() to show the buffer.
lcd.write(str)
Write the string str to the screen. It will appear immediately.
Constructors
class pyb.LED(id)
Create an LED object associated with the given LED:
•id is the LED number, 1-4.
Methods
led.intensity([value ])
Get or set the LED intensity. Intensity ranges between 0 (off) and 255 (full on). If no argument is given, return
the LED intensity. If an argument is given, set the LED intensity and return None.
led.off()
Turn the LED off.
led.on()
Turn the LED on, to maximum intensity.
led.toggle()
Toggle the LED between on (maximum intensity) and off. If the LED is at non-zero intensity then it is considered
“on” and toggle will turn it off.
A pin is the basic object to control I/O pins. It has methods to set the mode of the pin (input, output, etc) and methods
to get and set the digital logic level. For analog control of a pin, see the ADC class.
Usage Model:
All Board Pins are predefined as pyb.Pin.board.Name
x1_pin = pyb.Pin.board.X1
g = pyb.Pin(pyb.Pin.board.X1, pyb.Pin.IN)
CPU pins which correspond to the board pins are available as pyb.cpu.Name. For the CPU pins, the names are the
port letter followed by the pin number. On the PYBv1.0, pyb.Pin.board.X1 and pyb.Pin.cpu.B6 are the
same pin.
You can also use strings:
g = pyb.Pin(’X1’, pyb.Pin.OUT_PP)
pyb.Pin.mapper(MyMapper)
Constructors
class pyb.Pin(id, ...)
Create a new Pin object associated with the id. If additional arguments are given, they are used to initialise the
pin. See pin.init().
Class methods
Pin.af_list()
Returns an array of alternate functions available for this pin.
Pin.debug([state ])
Get or set the debugging state (True or False for on or off).
Pin.dict([dict ])
Get or set the pin mapper dictionary.
Pin.mapper([fun ])
Get or set the pin mapper function.
Methods
pin.init(mode, pull=Pin.PULL_NONE, af=-1)
Initialise the pin:
•mode can be one of: - Pin.IN - configure the pin for input; - Pin.OUT_PP - configure the pin for
output, with push-pull control; - Pin.OUT_OD - configure the pin for output, with open-drain control; -
Pin.AF_PP - configure the pin for alternate function, pull-pull; - Pin.AF_OD - configure the pin for
alternate function, open-drain; - Pin.ANALOG - configure the pin for analog.
•pull can be one of: - Pin.PULL_NONE - no pull up or down resistors; - Pin.PULL_UP - enable the
pull-up resistor; - Pin.PULL_DOWN - enable the pull-down resistor.
•when mode is Pin.AF_PP or Pin.AF_OD, then af can be the index or name of one of the alternate functions
associated with a pin.
Returns: None.
pin.high()
Set the pin to a high logic level.
pin.low()
Set the pin to a low logic level.
pin.value([value ])
Get or set the digital logic level of the pin:
•With no argument, return 0 or 1 depending on the logic level of the pin.
•With value given, set the logic level of the pin. value can be anything that converts to a boolean. If it
converts to True, the pin is set high, otherwise it is set low.
pin.__str__()
Return a string describing the pin object.
pin.af()
Returns the currently configured alternate-function of the pin. The integer returned will match one of the allowed
constants for the af argument to the init function.
pin.gpio()
Returns the base address of the GPIO block associated with this pin.
pin.mode()
Returns the currently configured mode of the pin. The integer returned will match one of the allowed constants
for the mode argument to the init function.
pin.name()
Get the pin name.
pin.names()
Returns the cpu and board names for this pin.
pin.pin()
Get the pin number.
pin.port()
Get the pin port.
pin.pull()
Returns the currently configured pull of the pin. The integer returned will match one of the allowed constants
for the pull argument to the init function.
Constants
Pin.AF_OD
initialise the pin to alternate-function mode with an open-drain drive
Pin.AF_PP
initialise the pin to alternate-function mode with a push-pull drive
Pin.ANALOG
initialise the pin to analog mode
Pin.IN
initialise the pin to input mode
Pin.OUT_OD
initialise the pin to output mode with an open-drain drive
Pin.OUT_PP
initialise the pin to output mode with a push-pull drive
Pin.PULL_DOWN
enable the pull-down resistor on the pin
Pin.PULL_NONE
don’t enable any pull up or down resistors on the pin
Pin.PULL_UP
enable the pull-up resistor on the pin
A Pin represents a physical pin on the microcprocessor. Each pin can have a variety of functions (GPIO, I2C SDA,
etc). Each PinAF object represents a particular function for a pin.
Usage Model:
x3 = pyb.Pin.board.X3
x3_af = x3.af_list()
x3_af will now contain an array of PinAF objects which are availble on pin X3.
For the pyboard, x3_af would contain: [Pin.AF1_TIM2, Pin.AF2_TIM5, Pin.AF3_TIM9, Pin.AF7_USART2]
Normally, each peripheral would configure the af automatically, but sometimes the same function is available on
multiple pins, and having more control is desired.
To configure X3 to expose TIM2_CH3, you could use:
pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=pyb.Pin.AF1_TIM2)
or:
pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=1)
Methods
pinaf.__str__()
Return a string describing the alternate function.
pinaf.index()
Return the alternate function index.
pinaf.name()
Return the name of the alternate function.
pinaf.reg()
Return the base register associated with the peripheral assigned to this alternate function. For example, if the
alternate function were TIM2_CH3 this would return stm.TIM2
The RTC is and independent clock that keeps track of the date and time.
Example usage:
rtc = pyb.RTC()
rtc.datetime((2014, 5, 1, 4, 13, 0, 0, 0))
print(rtc.datetime())
Constructors
class pyb.RTC
Create an RTC object.
Methods
rtc.datetime([datetimetuple ])
Get or set the date and time of the RTC.
With no arguments, this method returns an 8-tuple with the current date and time. With 1 argument (being an
8-tuple) it sets the date and time.
The 8-tuple has the following format:
(year, month, day, weekday, hours, minutes, seconds, subseconds)
weekday is 1-7 for Monday through Sunday.
subseconds counts down from 255 to 0
rtc.info()
Get information about the startup time and reset source.
•The lower 0xffff are the number of milliseconds the RTC took to start up.
•Bit 0x10000 is set if a power-on reset occurred.
•Bit 0x20000 is set if an external reset occurred
Servo objects control standard hobby servo motors with 3-wires (ground, power, signal). There are 4 positions on the
pyboard where these motors can be plugged in: pins X1 through X4 are the signal pins, and next to them are 4 sets of
power and ground pins.
Example usage:
import pyb
Note: The Servo objects use Timer(5) to produce the PWM output. You can use Timer(5) for Servo control, or your
own purposes, but not both at the same time.
Constructors
class pyb.Servo(id)
Create a servo object. id is 1-4, and corresponds to pins X1 through X4.
Methods
servo.angle([angle, time=0 ])
If no arguments are given, this function returns the current angle.
If arguments are given, this function sets the angle of the servo:
•angle is the angle to move to in degrees.
•time is the number of milliseconds to take to get to the specified angle. If omitted, then the servo moves
as quickly as possible to its new position.
servo.speed([speed, time=0 ])
If no arguments are given, this function returns the current speed.
If arguments are given, this function sets the speed of the servo:
•speed is the speed to change to, between -100 and 100.
•time is the number of milliseconds to take to get to the specified speed. If omitted, then the servo
accelerates as quickly as possible.
servo.pulse_width([value ])
If no arguments are given, this function returns the current raw pulse-width value.
If an argument is given, this function sets the raw pulse-width value.
servo.calibration([pulse_min, pulse_max, pulse_centre[, pulse_angle_90, pulse_speed_100 ]])
If no arguments are given, this function returns the current calibration data, as a 5-tuple.
If arguments are given, this function sets the timing calibration:
•pulse_min is the minimum allowed pulse width.
•pulse_max is the maximum allowed pulse width.
•pulse_centre is the pulse width corresponding to the centre/zero position.
•pulse_angle_90 is the pulse width corresponding to 90 degrees.
•pulse_speed_100 is the pulse width corresponding to a speed of 100.
SPI is a serial protocol that is driven by a master. At the physical level there are 3 lines: SCK, MOSI, MISO.
See usage model of I2C; SPI is very similar. Main difference is parameters to init the SPI bus:
from pyb import SPI
spi = SPI(1, SPI.MASTER, baudrate=600000, polarity=1, phase=0, crc=0x7)
Only required parameter is mode, SPI.MASTER or SPI.SLAVE. Polarity can be 0 or 1, and is the level the idle clock
line sits at. Phase can be 0 or 1 to sample data on the first or second clock edge respectively. Crc can be None for no
CRC, or a polynomial specifier.
Additional method for SPI:
data = spi.send_recv(b’1234’) # send 4 bytes and receive 4 bytes
buf = bytearray(4)
spi.send_recv(b’1234’, buf) # send 4 bytes and receive 4 into buf
spi.send_recv(buf, buf) # send/recv 4 bytes from/to buf
Constructors
class pyb.SPI(bus, ...)
Construct an SPI object on the given bus. bus can be 1 or 2. With no additional parameters, the SPI object is
created but not initialised (it has the settings from the last initialisation of the bus, if any). If extra arguments are
given, the bus is initialised. See init for parameters of initialisation.
The physical pins of the SPI busses are:
•SPI(1) is on the X position: (NSS, SCK, MISO, MOSI) = (X5, X6, X7, X8) = (PA4,
PA5, PA6, PA7)
•SPI(2) is on the Y position: (NSS, SCK, MISO, MOSI) = (Y5, Y6, Y7, Y8) = (PB12,
PB13, PB14, PB15)
At the moment, the NSS pin is not used by the SPI driver and is free for other use.
Methods
spi.deinit()
Turn off the SPI bus.
spi.init(mode, baudrate=328125, *, prescaler, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False,
crc=None)
Initialise the SPI bus with the given parameters:
•mode must be either SPI.MASTER or SPI.SLAVE.
•baudrate is the SCK clock rate (only sensible for a master).
•prescaler is the prescaler to use to derive SCK from the APB bus frequency; use of prescaler
overrides baudrate.
•polarity can be 0 or 1, and is the level the idle clock line sits at.
•phase can be 0 or 1 to sample data on the first or second clock edge respectively.
•firstbit can be SPI.MSB or SPI.LSB.
•crc can be None for no CRC, or a polynomial specifier.
Note that the SPI clock frequency will not always be the requested baudrate. The hardware only supports
baudrates that are the APB bus frequency (see pyb.freq()) divided by a prescaler, which can be 2, 4, 8,
16, 32, 64, 128 or 256. SPI(1) is on AHB2, and SPI(2) is on AHB1. For precise control over the SPI clock
frequency, specify prescaler instead of baudrate.
Printing the SPI object will show you the computed baudrate and the chosen prescaler.
spi.recv(recv, *, timeout=5000)
Receive data on the bus:
•recv can be an integer, which is the number of bytes to receive, or a mutable buffer, which will be filled
with received bytes.
•timeout is the timeout in milliseconds to wait for the receive.
Return value: if recv is an integer then a new buffer of the bytes received, otherwise the same buffer that was
passed in to recv.
spi.send(send, *, timeout=5000)
Send data on the bus:
•send is the data to send (an integer to send, or a buffer object).
•timeout is the timeout in milliseconds to wait for the send.
Return value: None.
spi.send_recv(send, recv=None, *, timeout=5000)
Send and receive data on the bus at the same time:
•send is the data to send (an integer to send, or a buffer object).
•recv is a mutable buffer which will be filled with received bytes. It can be the same as send, or omitted.
If omitted, a new buffer will be created.
Constants
SPI.MASTER
SPI.SLAVE
for initialising the SPI bus to master or slave mode
SPI.LSB
SPI.MSB
set the first bit to be the least or most significant bit
Example:
pyb.Switch().callback(lambda: pyb.LED(1).toggle())
Constructors
class pyb.Switch
Create and return a switch object.
Methods
switch()
Return the switch state: True if pressed down, False otherwise.
switch.callback(fun)
Register the given function to be called when the switch is pressed down. If fun is None, then it disables the
callback.
Timers can be used for a great variety of tasks. At the moment, only the simplest case is implemented: that of calling
a function periodically.
Each timer consists of a counter that counts up at a certain rate. The rate at which it counts is the peripheral clock
frequency (in Hz) divided by the timer prescaler. When the counter reaches the timer period it triggers an event, and
the counter resets back to zero. By using the callback method, the timer event can call a Python function.
Example usage to toggle an LED at a fixed frequency:
tim = pyb.Timer(4) # create a timer object using timer 4
tim.init(freq=2) # trigger at 2Hz
tim.callback(lambda t:pyb.LED(1).toggle())
Further examples:
tim = pyb.Timer(4, freq=100) # freq in Hz
tim = pyb.Timer(4, prescaler=0, period=99)
tim.counter() # get counter (can also set)
tim.prescaler(2) # set prescaler (can also get)
tim.period(199) # set period (can also get)
tim.callback(lambda t: ...) # set callback for update interrupt (t=tim instance)
tim.callback(None) # clear callback
Note: Timer 3 is reserved for internal use. Timer 5 controls the servo driver, and Timer 6 is used for timed ADC/DAC
reading/writing. It is recommended to use the other timers in your programs.
Constructors
class pyb.Timer(id, ...)
Construct a new timer object of the given id. If additional arguments are given, then the timer is initialised by
init(...). id can be 1 to 14, excluding 3.
Methods
timer.callback(fun)
Set the function to be called when the timer triggers. fun is passed 1 argument, the timer object. If fun is
None then the callback will be disabled.
timer.channel(channel, mode, ...)
If only a channel number is passed, then a previously initialized channel object is returned (or None if there is
no previous channel).
Othwerwise, a TimerChannel object is initialized and returned.
Each channel can be configured to perform pwm, output compare, or input capture. All channels share the same
underlying timer, which means that they share the same timer clock.
Keyword arguments:
•mode can be one of:
–Timer.PWM — configure the timer in PWM mode (active high).
–Timer.PWM_INVERTED — configure the timer in PWM mode (active low).
–Timer.OC_TIMING — indicates that no pin is driven.
–Timer.OC_ACTIVE — the pin will be made active when a compare match occurs (active is deter-
mined by polarity)
–Timer.OC_INACTIVE — the pin will be made inactive when a compare match occurs.
–Timer.OC_TOGGLE — the pin will be toggled when an compare match occurs.
–Timer.OC_FORCED_ACTIVE — the pin is forced active (compare match is ignored).
–Timer.OC_FORCED_INACTIVE — the pin is forced inactive (compare match is ignored).
–Timer.IC — configure the timer in Input Capture mode.
–Timer.ENC_A — configure the timer in Encoder mode. The counter only changes when CH1
changes.
–Timer.ENC_B — configure the timer in Encoder mode. The counter only changes when CH2
changes.
–Timer.ENC_AB — configure the timer in Encoder mode. The counter changes when CH1 or CH2
changes.
timer.counter([value ])
Get or set the timer counter.
timer.deinit()
Deinitialises the timer.
Disables the callback (and the associated irq). Disables any channel callbacks (and the associated irq). Stops
the timer, and disables the timer peripheral.
timer.freq([value ])
Get or set the frequency for the timer (changes prescaler and period if set).
timer.init(*, freq, prescaler, period)
Initialise the timer. Initialisation must be either by frequency (in Hz) or by prescaler and period:
Keyword arguments:
•freq — specifies the periodic frequency of the timer. You migh also view this as the frequency
with which the timer goes through one complete cycle.
•prescaler [0-0xffff] - specifies the value to be loaded into the timer’s Prescaler Register
(PSC). The timer clock source is divided by (prescaler + 1) to arrive at the timer clock.
Timers 2-7 and 12-14 have a clock source of 84 MHz (pyb.freq()[2] * 2), and Timers 1, and 8-11
have a clock source of 168 MHz (pyb.freq()[3] * 2).
•period [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5. Specifies the
value to be loaded into the timer’s AutoReload Register (ARR). This determines the period of
the timer (i.e. when the counter cycles). The timer counter will roll-over after period + 1
timer clock cycles.
•mode can be one of:
–Timer.UP - configures the timer to count from 0 to ARR (default)
–Timer.DOWN - configures the timer to count from ARR down to 0.
–Timer.CENTER - confgures the timer to count from 0 to ARR and then back down to 0.
•div can be one of 1, 2, or 4. Divides the timer clock to determine the sampling clock used by
the digital filters.
•callback - as per Timer.callback()
•deadtime - specifies the amount of “dead” or inactive time between transitions on compli-
mentary channels (both channels will be inactive) for this time). deadtime may be an integer
between 0 and 1008, with the following restrictions: 0-128 in steps of 1. 128-256 in steps of 2,
256-512 in steps of 8, and 512-1008 in steps of 16. deadime measures ticks of source_freq
divided by div clock ticks. deadtime is only available on timers 1 and 8.
You must either specify freq or both of period and prescaler.
timer.period([value ])
Get or set the period of the timer.
timer.prescaler([value ])
Get or set the prescaler for the timer.
timer.source_freq()
Get the frequency of the source of the timer.
Methods
timerchannel.callback(fun)
Set the function to be called when the timer channel triggers. fun is passed 1 argument, the timer object. If
fun is None then the callback will be disabled.
timerchannel.capture([value ])
Get or set the capture value associated with a channel. capture, compare, and pulse_width are all aliases for the
same function. capture is the logical name to use when the channel is in input capture mode.
timerchannel.compare([value ])
Get or set the compare value associated with a channel. capture, compare, and pulse_width are all aliases for
the same function. compare is the logical name to use when the channel is in output compare mode.
timerchannel.pulse_width([value ])
Get or set the pulse width value associated with a channel. capture, compare, and pulse_width are all aliases for
the same function. pulse_width is the logical name to use when the channel is in PWM mode.
In edge aligned mode, a pulse_width of period + 1 corresponds to a duty cycle of 100% In center aligned
mode, a pulse width of period corresponds to a duty cycle of 100%
timerchannel.pulse_width_percent([value ])
Get or set the pulse width percentage associated with a channel. The value is a number between 0 and 100 and
sets the percentage of the timer period for which the pulse is active. The value can be an integer or floating-point
number for more accuracy. For example, a value of 25 gives a duty cycle of 25%.
UART implements the standard UART/USART duplex serial communications protocol. At the physical level it con-
sists of 2 lines: RX and TX. The unit of communication is a character (not to be confused with a string character)
which can be 8 or 9 bits wide.
UART objects can be created and initialised using:
from pyb import UART
Note: The stream functions read, write, etc. are new in Micro Python v1.3.4. Earlier versions use uart.send
and uart.recv.
Constructors
Methods
uart.init(baudrate, bits=8, parity=None, stop=1, *, timeout=1000, timeout_char=0, read_buf_len=64)
Initialise the UART bus with the given parameters:
•baudrate is the clock rate.
•bits is the number of bits per character, 7, 8 or 9.
•parity is the parity, None, 0 (even) or 1 (odd).
•stop is the number of stop bits, 1 or 2.
•timeout is the timeout in milliseconds to wait for the first character.
•timeout_char is the timeout in milliseconds to wait between characters.
•read_buf_len is the character length of the read buffer (0 to disable).
This method will raise an exception if the baudrate could not be set within 5% of the desired value. The minimum
baudrate is dictated by the frequency of the bus that the UART is on; UART(1) and UART(6) are APB2, the rest
are on APB1. The default bus frequencies give a minimum baudrate of 1300 for UART(1) and UART(6) and
650 for the others. Use pyb.freq to reduce the bus frequencies to get lower baudrates.
Note: with parity=None, only 8 and 9 bits are supported. With parity enabled, only 7 and 8 bits are supported.
uart.deinit()
Turn off the UART bus.
uart.any()
Return True if any characters waiting, else False.
uart.read([nbytes ])
Read characters. If nbytes is specified then read at most that many bytes.
Note: for 9 bit characters each character takes two bytes, nbytes must be even, and the number of characters
is nbytes/2.
Return value: a bytes object containing the bytes read in. Returns b’’ on timeout.
uart.readall()
Read as much data as possible.
Return value: a bytes object.
uart.readchar()
Receive a single character on the bus.
Return value: The character read, as an integer. Returns -1 on timeout.
uart.readinto(buf [, nbytes ])
Read bytes into the buf. If nbytes is specified then read at most that many bytes. Otherwise, read at most
len(buf) bytes.
Return value: number of bytes read and stored into buf.
uart.readline()
Read a line, ending in a newline character.
Return value: the line read.
uart.write(buf )
Write the buffer of bytes to the bus. If characters are 7 or 8 bits wide then each byte is one character. If characters
are 9 bits wide then two bytes are used for each character (little endian), and buf must contain an even number
of bytes.
Return value: number of bytes written.
uart.writechar(char)
Write a single character on the bus. char is an integer to write. Return value: None.
uart.sendbreak()
Send a break condition on the bus. This drives the bus low for a duration of 13 bits. Return value: None.
The USB_VCP class allows creation of an object representing the USB virtual comm port. It can be used to read and
write data over USB to the connected host.
Constructors
class pyb.USB_VCP
Create a new USB_VCP object.
Methods
usb_vcp.setinterrupt(chr)
Set the character which interrupts running Python code. This is set to 3 (CTRL-C) by default, and when a
CTRL-C character is received over the USB VCP port, a KeyboardInterrupt exception is raised.
Set to -1 to disable this interrupt feature. This is useful when you want to send raw bytes over the USB VCP
port.
usb_vcp.isconnected()
Return True if USB is connected as a serial device, else False.
usb_vcp.any()
Return True if any characters waiting, else False.
usb_vcp.close()
usb_vcp.read([nbytes ])
usb_vcp.readall()
usb_vcp.readline()
usb_vcp.recv(data, *, timeout=5000)
Receive data on the bus:
•data can be an integer, which is the number of bytes to receive, or a mutable buffer, which will be filled
with received bytes.
This module provides network drivers and routing configuration. Network drivers for specific hardware are available
within this module and are used to configure a hardware network interface. Configured interfaces are then available
for use via the socket module.
For example:
# configure a specific network interface
# see below for examples of specific drivers
import network
nic = network.Driver(...)
print(nic.ifconfig())
class CC3K
This class provides a driver for CC3000 wifi modules. Example usage:
import network
nic = network.CC3K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4, pyb.Pin.board.Y3)
nic.connect(’your-ssid’, ’your-password’)
while not nic.isconnected():
pyb.delay(50)
print(nic.ifconfig())
For this example to work the CC3000 module must have the following connections:
• MOSI connected to Y8
• MISO connected to Y7
• CLK connected to Y6
• CS connected to Y5
• VBEN connected to Y4
• IRQ connected to Y3
It is possible to use other SPI busses and other pins for CS, VBEN and IRQ.
Constructors
Methods
Constants
CC3K.WEP
CC3K.WPA
CC3K.WPA2
security type to use
class WIZNET5K
This class allows you to control WIZnet5x00 Ethernet adaptors based on the W5200 and W5500 chipsets (only W5200
tested).
Example usage:
import network
nic = network.WIZNET5K(pyb.SPI(1), pyb.Pin.board.X5, pyb.Pin.board.X4)
print(nic.ifconfig())
For this example to work the WIZnet5x00 module must have the following connections:
• MOSI connected to X8
• MISO connected to X7
• SCLK connected to X6
• nSS connected to X5
• nRESET connected to X4
It is possible to use other SPI busses and other pins for nSS and nRESET.
Constructors
Methods
wiznet5k.regs()
Dump the WIZnet5x00 registers. Useful for debugging.
79
Micro Python Documentation, Release 1.4
81
Micro Python Documentation, Release 1.4
• The LCD display on the LCD touch-sensor skin: Newhaven Display NHD-C12832A1Z-FSW-FBW-3V3
(460KiB PDF)
• The touch sensor chip on the LCD touch-sensor skin: Freescale MPR121 (280KiB PDF)
• The digital potentiometer on the audio skin: Microchip MCP4541 (2.7MiB PDF)
83
Micro Python Documentation, Release 1.4
85
Micro Python Documentation, Release 1.4
See pyb.
import pyb
9.1.2 LEDs
See pyb.LED.
from pyb import LED
See pyb.Pin.
from pyb import Pin
87
Micro Python Documentation, Release 1.4
See pyb.Servo.
from pyb import Servo
See pyb.ExtInt.
from pyb import Pin, ExtInt
9.1.6 Timers
See pyb.Timer.
from pyb import Timer
adc = ADC(Pin(’X19’))
adc.read() # read value, 0-4095
dac = DAC(Pin(’X5’))
dac.write(120) # output between 0 and 255
See pyb.UART.
from pyb import UART
See pyb.SPI.
from pyb import SPI
See pyb.I2C.
from pyb import I2C
There is a small internal filesystem (a drive) on the pyboard, called /flash, which is stored within the microcon-
troller’s flash memory. If a micro SD card is inserted into the slot, it is available as /sd.
When the pyboard boots up, it needs to choose a filesystem to boot from. If there is no SD card, then it uses the internal
filesystem /flash as the boot filesystem, otherwise, it uses the SD card /sd.
(Note that on older versions of the board, /flash is called 0:/ and /sd is called 1:/).
The boot filesystem is used for 2 things: it is the filesystem from which the boot.py and main.py files are searched
for, and it is the filesystem which is made available on your PC over the USB cable.
The filesystem will be available as a USB flash drive on your PC. You can save files to the drive, and edit boot.py
and main.py.
Remember to eject (on Linux, unmount) the USB drive before you reset your pyboard.
If you power up normally, or press the reset button, the pyboard will boot into standard mode: the boot.py file will
be executed first, then the USB will be configured, then main.py will run.
You can override this boot sequence by holding down the user switch as the board is booting up. Hold down user
switch and press reset, and then as you continue to hold the user switch, the LEDs will count in binary. When the
LEDs have reached the mode you want, let go of the user switch, the LEDs for the selected mode will flash quickly,
and the board will boot.
The modes are:
1. Green LED only, standard boot: run boot.py then main.py.
2. Orange LED only, safe boot: don’t run any scripts on boot-up.
3. Green and orange LED together, filesystem reset: resets the flash filesystem to its factory state, then boots in
safe mode.
If your filesystem becomes corrupt, boot into mode 3 to fix it. If resetting the filesystem while plugged into your
compute doesn’t work, you can try doing the same procedure while the board is plugged into a USB charger, or other
USB power supply without data connection.
This tutorial is intended to get you started with your pyboard. All you need is a pyboard and a micro-USB cable to
connect it to your PC. If it is your first time, it is recommended to follow the tutorial through in the order below.
To get the most out of your pyboard, there are a few basic things to understand about how it works.
Because the pyboard does not have a housing it needs a bit of care:
• Be gentle when plugging/unplugging the USB cable. Whilst the USB connector is soldered through the board
and is relatively strong, if it breaks off it can be very difficult to fix.
• Static electricity can shock the components on the pyboard and destroy them. If you experience a lot of static
electricity in your area (eg dry and cold climates), take extra care not to shock the pyboard. If your pyboard
came in a black plastic box, then this box is the best way to store and carry the pyboard as it is an anti-static box
(it is made of a conductive plastic, with conductive foam inside).
As long as you take care of the hardware, you should be okay. It’s almost impossible to break the software on the
pyboard, so feel free to play around with writing code as much as you like. If the filesystem gets corrupt, see below on
how to reset it. In the worst case you might need to reflash the Micro Python software, but that can be done over USB.
The micro USB connector is on the top right, the micro SD card slot on the top left of the board. There are 4 LEDs
between the SD slot and USB connector. The colours are: red on the bottom, then green, orange, and blue on the top.
There are 2 switches: the right one is the reset switch, the left is the user switch.
The pyboard can be powered via USB. Connect it to your PC via a micro USB cable. There is only one way that the
cable will fit. Once connected, the green LED on the board should flash quickly.
Let’s jump right in and get a Python script running on the pyboard. After all, that’s what it’s all about!
Connect your pyboard to your PC (Windows, Mac or Linux) with a micro USB cable. There is only one way that the
cable will connect, so you can’t get it wrong.
When the pyboard is connected to your PC it will power on and enter the start up process (the boot process). The
green LED should light up for half a second or less, and when it turns off it means the boot process has completed.
Your PC should now recognise the pyboard. It depends on the type of PC you have as to what happens next:
• Windows: Your pyboard will appear as a removable USB flash drive. Windows may automatically pop-up a
Editing main.py
Now we are going to write our Python program, so open the main.py file in a text editor. On Windows you can
use notepad, or any other editor. On Mac and Linux, use your favourite text editor. With the file open you will see it
contains 1 line:
# main.py -- put your code here!
This line starts with a # character, which means that it is a comment. Such lines will not do anything, and are there for
you to write notes about your program.
Let’s add 2 lines to this main.py file, to make it look like this:
# main.py -- put your code here!
import pyb
pyb.LED(4).on()
The first line we wrote says that we want to use the pyb module. This module contains all the functions and classes
to control the features of the pyboard.
The second line that we wrote turns the blue LED on: it first gets the LED class from the pyb module, creates LED
number 4 (the blue LED), and then turns it on.
To run this little script, you need to first save and close the main.py file, and then eject (or unmount) the pyboard
USB drive. Do this like you would a normal USB flash drive.
When the drive is safely ejected/unmounted you can get to the fun part: press the RST switch on the pyboard to reset
and run your script. The RST switch is the small black button just below the USB connector on the board, on the right
edge.
When you press RST the green LED will flash quickly, and then the blue LED should turn on and stay on.
Congratulations! You have written and run your very first Micro Python program!
REPL stands for Read Evaluate Print Loop, and is the name given to the interactive Micro Python prompt that you can
access on the pyboard. Using the REPL is by far the easiest way to test out your code and run commands. You can use
the REPL in addition to writing scripts in main.py.
To use the REPL, you must connect to the serial USB device on the pyboard. How you do this depends on your
operating system.
Windows
You need to install the pyboard driver to use the serial USB device. The driver is on the pyboard’s USB flash drive,
and is called pybcdc.inf.
To install this driver you need to go to Device Manager for your computer, find the pyboard in the list of devices (it
should have a warning sign next to it because it’s not working yet), right click on the pyboard device, select Properties,
then Install Driver. You need to then select the option to find the driver manually (don’t use Windows auto update),
navigate to the pyboard’s USB drive, and select that. It should then install. After installing, go back to the Device
Manager to find the installed pyboard, and see which COM port it is (eg COM4). More comprehensive instructions can
be found in the Guide for pyboard on Windows (PDF). Please consult this guide if you are having problems installing
the driver.
You now need to run your terminal program. You can use HyperTerminal if you have it installed, or download the
free program PuTTY: putty.exe. Using your serial program you must connect to the COM port that you found in the
previous step. With PuTTY, click on “Session” in the left-hand panel, then click the “Serial” radio button on the right,
then enter you COM port (eg COM4) in the “Serial Line” box. Finally, click the “Open” button.
Mac OS X
When you are finished and want to exit screen, type CTRL-A CTRL-\.
Linux
You can also try picocom or minicom instead of screen. You may have to use /dev/ttyACM1 or a higher number
for ttyACM. And, you may need to give yourself the correct permissions to access this devices (eg group uucp or
dialout, or use sudo).
Now let’s try running some Micro Python code directly on the pyboard.
With your serial program open (PuTTY, screen, picocom, etc) you may see a blank screen with a flashing cursor. Press
Enter and you should be presented with a Micro Python prompt, i.e. >>>. Let’s make sure it is working with the
obligatory test:
>>> print("hello pyboard!")
hello pyboard!
In the above, you should not type in the >>> characters. They are there to indicate that you should type the text after
it at the prompt. In the end, once you have entered the text print("hello pyboard!") and pressed Enter, the
output on your screen should look like it does above.
If you already know some python you can now try some basic commands here.
If any of this is not working you can try either a hard reset or a soft reset; see below.
Go ahead and try typing in some other commands. For example:
>>> pyb.LED(1).on()
>>> pyb.LED(2).on()
>>> 1 + 2
3
>>> 1 / 2
0.5
>>> 20 * ’py’
’pypypypypypypypypypypypypypypypypypypypy’
If something goes wrong, you can reset the board in two ways. The first is to press CTRL-D at the Micro Python
prompt, which performs a soft reset. You will see a message something like
>>>
PYB: sync filesystems
PYB: soft reboot
Micro Python v1.0 on 2014-05-03; PYBv1.0 with STM32F405RG
Type "help()" for more information.
>>>
If that isn’t working you can perform a hard reset (turn-it-off-and-on-again) by pressing the RST switch (the small
black button closest to the micro-USB socket on the board). This will end your session, disconnecting whatever
program (PuTTY, screen, etc) that you used to connect to the pyboard.
If you are going to do a hard-reset, it’s recommended to first close your serial program and eject/unmount the pyboard
drive.
The easiest thing to do on the pyboard is to turn on the LEDs attached to the board. Connect the board, and log in as
described in tutorial 1. We will start by turning and LED on in the interpreter, type the following
>>> myled = pyb.LED(1)
>>> myled.on()
>>> myled.off()
led = pyb.LED(2)
while True:
led.toggle()
pyb.delay(1000)
When you save, the red light on the pyboard should turn on for about a second. To run the script, do a soft reset
(CTRL-D). The pyboard will then restart and you should see a green light continuously flashing on and off. Success,
the first step on your path to building an army of evil robots! When you are bored of the annoying flashing light then
press CTRL-C at your terminal to stop it running.
So what does this code do? First we need some terminology. Python is an object-oriented language, almost everything
in python is a class and when you create an instance of a class you get an object. Classes have methods associated to
them. A method (also called a member function) is used to interact with or control the object.
The first line of code creates an LED object which we have then called led. When we create the object, it takes a single
parameter which must be between 1 and 4, corresponding to the 4 LEDs on the board. The pyb.LED class has three
important member functions that we will use: on(), off() and toggle(). The other function that we use is pyb.delay()
this simply waits for a given time in miliseconds. Once we have created the LED object, the statement while True:
creates an infinite loop which toggles the led between on and off and waits for 1 second.
Exercise: Try changing the time between toggling the led and turning on a different LED.
Exercise: Connect to the pyboard directly, create a pyb.LED object and turn it on using the on() method.
So far we have only used a single LED but the pyboard has 4 available. Let’s start by creating an object for each LED
so we can control each of them. We do that by creating a list of LEDS with a list comprehension.
leds = [pyb.LED(i) for i in range(1,5)]
If you call pyb.LED() with a number that isn’t 1,2,3,4 you will get an error message. Next we will set up an infinite
loop that cycles through each of the LEDs turning them on and off.
n = 0
while True:
n = (n + 1) % 4
leds[n].toggle()
pyb.delay(50)
Here, n keeps track of the current LED and every time the loop is executed we cycle to the next n (the % sign is a
modulus operator that keeps n between 0 and 3.) Then we access the nth LED and toggle it. If you run this you should
see each of the LEDs turning on then all turning off again in sequence.
One problem you might find is that if you stop the script and then start it again that the LEDs are stuck on from the
previous run, ruining our carefully choreographed disco. We can fix this by turning all the LEDs off when we initialise
the script and then using a try/finally block. When you press CTRL-C, Micro Python generates a VCPInterrupt
exception. Exceptions normally mean something has gone wrong and you can use a try: command to “catch” an
exception. In this case it is just the user interrupting the script, so we don’t need to catch the error but just tell Micro
Python what to do when we exit. The finally block does this, and we use it to make sure all the LEDs are off. The full
code is:
leds = [pyb.LED(i) for i in range(1,5)]
for l in leds:
l.off()
n = 0
try:
while True:
n = (n + 1) % 4
leds[n].toggle()
pyb.delay(50)
finally:
for l in leds:
l.off()
The blue LED is special. As well as turning it on and off, you can control the intensity using the intensity() method.
This takes a number between 0 and 255 that determines how bright it is. The following script makes the blue LED
gradually brighter then turns it off again.
led = pyb.LED(4)
intensity = 0
while True:
intensity = (intensity + 1) % 255
led.intensity(intensity)
pyb.delay(20)
You can call intensity() on the other LEDs but they can only be off or on. 0 sets them off and any other number up to
255 turns them on.
The pyboard has 2 small switches, labelled USR and RST. The RST switch is a hard-reset switch, and if you press it
then it restarts the pyboard from scratch, equivalent to turning the power off then back on.
The USR switch is for general use, and is controlled via a Switch object. To make a switch object do:
>>> sw = pyb.Switch()
Remember that you may need to type import pyb if you get an error that the name pyb does not exist.
With the switch object you can get its status:
>>> sw()
False
This will print False if the switch is not held, or True if it is held. Try holding the USR switch down while running
the above command.
Switch callbacks
The switch is a very simple object, but it does have one advanced feature: the sw.callback() function. The
callback function sets up something to run when the switch is pressed, and uses an interrupt. It’s probably best to start
with an example before understanding how interrupts work. Try running the following at the prompt:
>>> sw.callback(lambda:print(’press!’))
This tells the switch to print press! each time the switch is pressed down. Go ahead and try it: press the USR switch
and watch the output on your PC. Note that this print will interrupt anything you are typing, and is an example of an
interrupt routine running asynchronously.
As another example try:
>>> sw.callback(lambda:pyb.LED(1).toggle())
This will toggle the red LED each time the switch is pressed. And it will even work while other code is running.
To disable the switch callback, pass None to the callback function:
>>> sw.callback(None)
You can pass any function (that takes zero arguments) to the switch callback. Above we used the lambda feature of
Python to create an anonymous function on the fly. But we could equally do:
>>> def f():
... pyb.LED(1).toggle()
...
>>> sw.callback(f)
This creates a function called f and assigns it to the switch callback. You can do things this way when your function
is more complicated than a lambda will allow.
Note that your callback functions must not allocate any memory (for example they cannot create a tuple or list).
Callback functions should be relatively simple. If you need to make a list, make it beforehand and store it in a global
variable (or make it local and close over it). If you need to do a long, complicated calculation, then use the callback to
set a flag which some other code then responds to.
Let’s step through the details of what is happening with the switch callback. When you register a function with
sw.callback(), the switch sets up an external interrupt trigger (falling edge) on the pin that the switch is connected
to. This means that the microcontroller will listen on the pin for any changes, and the following will occur:
1. When the switch is pressed a change occurs on the pin (the pin goes from low to high), and the microcontroller
registers this change.
2. The microcontroller finishes executing the current machine instruction, stops execution, and saves its current
state (pushes the registers on the stack). This has the effect of pausing any code, for example your running
Python script.
3. The microcontroller starts executing the special interrupt handler associated with the switch’s external trigger.
This interrupt handler get the function that you registered with sw.callback() and executes it.
4. Your callback function is executed until it finishes, returning control to the switch interrupt handler.
5. The switch interrupt handler returns, and the microcontroller is notified that the interrupt has been dealt with.
6. The microcontroller restores the state that it saved in step 2.
7. Execution continues of the code that was running at the beginning. Apart from the pause, this code does not
notice that it was interrupted.
The above sequence of events gets a bit more complicated when multiple interrupts occur at the same time. In that
case, the interrupt with the highest priority goes first, then the others in order of their priority. The switch interrupt is
set at the lowest priority.
Here you will learn how to read the accelerometer and signal using LEDs states like tilt left and tilt right.
The pyboard has an accelerometer (a tiny mass on a tiny spring) that can be used to detect the angle of the board and
motion. There is a different sensor for each of the x, y, z directions. To get the value of the accelerometer, create a
pyb.Accel() object and then call the x() method.
>>> accel = pyb.Accel()
>>> accel.x()
7
This returns a signed integer with a value between around -30 and 30. Note that the measurement is very noisy, this
means that even if you keep the board perfectly still there will be some variation in the number that you measure.
Because of this, you shouldn’t use the exact value of the x() method but see if it is in a certain range.
We will start by using the accelerometer to turn on a light if it is not flat.
accel = pyb.Accel()
light = pyb.LED(3)
SENSITIVITY = 3
while True:
x = accel.x()
if abs(x) > SENSITIVITY:
light.on()
else:
light.off()
pyb.delay(100)
We create Accel and LED objects, then get the value of the x direction of the accelerometer. If the magnitude of x
is bigger than a certain value SENSITIVITY, then the LED turns on, otherwise it turns off. The loop has a small
pyb.delay() otherwise the LED flashes annoyingly when the value of x is close to SENSITIVITY. Try running
this on the pyboard and tilt the board left and right to make the LED turn on and off.
Exercise: Change the above script so that the blue LED gets brighter the more you tilt the pyboard. HINT: You
will need to rescale the values, intensity goes from 0-255.
The example above is only sensitive to the angle in the x direction but if we use the y() value and more LEDs we can
turn the pyboard into a spirit level.
xlights = (pyb.LED(2), pyb.LED(3))
ylights = (pyb.LED(1), pyb.LED(4))
accel = pyb.Accel()
SENSITIVITY = 3
while True:
x = accel.x()
if x > SENSITIVITY:
xlights[0].on()
xlights[1].off()
elif x < -SENSITIVITY:
xlights[1].on()
xlights[0].off()
else:
xlights[0].off()
xlights[1].off()
y = accel.y()
if y > SENSITIVITY:
ylights[0].on()
ylights[1].off()
elif y < -SENSITIVITY:
ylights[1].on()
ylights[0].off()
else:
ylights[0].off()
ylights[1].off()
pyb.delay(100)
We start by creating a tuple of LED objects for the x and y directions. Tuples are immutable objects in python which
means they can’t be modified once they are created. We then proceed as before but turn on a different LED for positive
and negative x values. We then do the same for the y direction. This isn’t particularly sophisticated but it does the job.
Run this on your pyboard and you should see different LEDs turning on depending on how you tilt the board.
If something goes wrong with your pyboard, don’t panic! It is almost impossible for you to break the pyboard by
programming the wrong thing.
The first thing to try is to enter safe mode: this temporarily skips execution of boot.py and main.py and gives
default USB settings.
If you have problems with the filesystem you can do a factory reset, which restores the filesystem to its original state.
Safe mode
If you pyboard’s filesystem gets corrupted (for example, you forgot to eject/unmount it), or you have some code in
boot.py or main.py which you can’t escape from, then you can reset the filesystem.
Resetting the filesystem deletes all files on the internal pyboard storage (not the SD card), and restores the files
boot.py, main.py, README.txt and pybcdc.inf back to their original state.
To do a factory reset of the filesystem you follow a similar procedure as you did to enter safe mode, but release USR
on green+orange:
1. Connect the pyboard to USB so it powers up.
2. Hold down the USR switch.
3. While still holding down USR, press and release the RST switch.
4. The LEDs will then cycle green to orange to green+orange and back again.
5. Keep holding down USR until both the green and orange LEDs are lit, and then let go of the USR switch.
6. The green and orange LEDs should flash quickly 4 times.
7. The red LED will turn on (so red, green and orange are now on).
8. The pyboard is now resetting the filesystem (this takes a few seconds).
9. The LEDs all turn off.
10. You now have a reset filesystem, and are in safe mode.
11. Press and release the RST switch to boot normally.
The pyboard is a USB device, and can configured to act as a mouse instead of the default USB flash drive.
To do this we must first edit the boot.py file to change the USB configuration. If you have not yet touched your
boot.py file then it will look something like this:
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal
import pyb
#pyb.main(’main.py’) # main script to run after this one
#pyb.usb_mode(’CDC+MSC’) # act as a serial and a storage device
#pyb.usb_mode(’CDC+HID’) # act as a serial device and a mouse
To enable the mouse mode, uncomment the last line of the file, to make it look like:
pyb.usb_mode(’CDC+HID’) # act as a serial device and a mouse
If you already changed your boot.py file, then the minimum code it needs to work is:
import pyb
pyb.usb_mode(’CDC+HID’)
This tells the pyboard to configure itself as a CDC (serial) and HID (human interface device, in our case a mouse)
USB device when it boots up.
Eject/unmount the pyboard drive and reset it using the RST switch. Your PC should now detect the pyboard as a
mouse!
To get the py-mouse to do anything we need to send mouse events to the PC. We will first do this manually using the
REPL prompt. Connect to your pyboard using your serial program and type the following:
Your mouse should move 10 pixels to the right! In the command above you are sending 4 pieces of information: button
status, x, y and scroll. The number 10 is telling the PC that the mouse moved 10 pixels in the x direction.
Let’s make the mouse oscillate left and right:
>>> import math
>>> def osc(n, d):
... for i in range(n):
... pyb.hid((0, int(20 * math.sin(i / 10)), 0, 0))
... pyb.delay(d)
...
>>> osc(100, 50)
The first argument to the function osc is the number of mouse events to send, and the second argument is the delay
(in milliseconds) between events. Try playing around with different numbers.
Excercise: make the mouse go around in a circle.
Now lets make the mouse move based on the angle of the pyboard, using the accelerometer. The following code can
be typed directly at the REPL prompt, or put in the main.py file. Here, we’ll put in in main.py because to do that
we will learn how to go into safe mode.
At the moment the pyboard is acting as a serial USB device and an HID (a mouse). So you cannot access the filesystem
to edit your main.py file.
You also can’t edit your boot.py to get out of HID-mode and back to normal mode with a USB drive...
To get around this we need to go into safe mode. This was described in the [safe mode tutorial](tut-reset), but we
repeat the instructions here:
1. Hold down the USR switch.
2. While still holding down USR, press and release the RST switch.
3. The LEDs will then cycle green to orange to green+orange and back again.
4. Keep holding down USR until only the orange LED is lit, and then let go of the USR switch.
5. The orange LED should flash quickly 4 times, and then turn off.
6. You are now in safe mode.
In safe mode, the boot.py and main.py files are not executed, and so the pyboard boots up with default settings.
This means you now have access to the filesystem (the USB drive should appear), and you can edit main.py. (Leave
boot.py as-is, because we still want to go back to HID-mode after we finish editting main.py.)
In main.py put the following code:
import pyb
switch = pyb.Switch()
accel = pyb.Accel()
Save your file, eject/unmount your pyboard drive, and reset it using the RST switch. It should now act as a mouse, and
the angle of the board will move the mouse around. Try it out, and see if you can make the mouse stand still!
Press the USR switch to stop the mouse motion.
You’ll note that the y-axis is inverted. That’s easy to fix: just put a minus sign in front of the y-coordinate in the
pyb.hid() line above.
If you leave your pyboard as-is, it’ll behave as a mouse everytime you plug it in. You probably want to change it back
to normal. To do this you need to first enter safe mode (see above), and then edit the boot.py file. In the boot.py
file, comment out (put a # in front of) the line with the CDC+HID setting, so it looks like:
#pyb.usb_mode(’CDC+HID’) # act as a serial device and a mouse
Save your file, eject/unmount the drive, and reset the pyboard. It is now back to normal operating mode.
The pyboard has 14 timers which each consist of an independent counter running at a user-defined frequency. They
can be set up to run a function at specific intervals. The 14 timers are numbered 1 through 14, but 3 is reserved for
internal use, and 5 and 6 are used for servo and ADC/DAC control. Avoid using these timers if possible.
Let’s create a timer object:
>>> tim = pyb.Timer(4)
The pyboard is telling us that tim is attached to timer number 4, but it’s not yet initialised. So let’s initialise it to
trigger at 10 Hz (that’s 10 times per second):
>>> tim.init(freq=10)
Now that it’s initialised, we can see some information about the timer:
>>> tim
Timer(4, prescaler=624, period=13439, mode=UP, div=1)
The information means that this timer is set to run at the peripheral clock speed divided by 624+1, and it will count
from 0 up to 13439, at which point it triggers an interrupt, and then starts counting again from 0. These num-
bers are set to make the timer trigger at 10 Hz: the source frequency of the timer is 84MHz (found by running
tim.source_freq()) so we get 84MHz / 625 / 13440 = 10Hz.
Timer counter
So what can we do with our timer? The most basic thing is to get the current value of its counter:
>>> tim.counter()
21504
Timer callbacks
The next thing we can do is register a callback function for the timer to execute when it triggers (see the [switch
tutorial](tut-switch) for an introduction to callback functions):
>>> tim.callback(lambda t:pyb.LED(1).toggle())
This should start the red LED flashing right away. It will be flashing at 5 Hz (2 toggle’s are needed for 1 flash, so
toggling at 10 Hz makes it flash at 5 Hz). You can change the frequency by re-initialising the timer:
>>> tim.init(freq=20)
The function that you pass to callback must take 1 argument, which is the timer object that triggered. This allows you
to control the timer from within the callback function.
We can create 2 timers and run them independently:
>>> tim4 = pyb.Timer(4, freq=10)
>>> tim7 = pyb.Timer(7, freq=20)
>>> tim4.callback(lambda t: pyb.LED(1).toggle())
>>> tim7.callback(lambda t: pyb.LED(2).toggle())
Because the callbacks are proper hardware interrupts, we can continue to use the pyboard for other things while these
timers are running.
You can use a timer to create a microsecond counter, which might be useful when you are doing something which
requires accurate timing. We will use timer 2 for this, since timer 2 has a 32-bit counter (so does timer 5, but if you
use timer 5 then you can’t use the Servo driver at the same time).
We set up timer 2 as follows:
>>> micros = pyb.Timer(2, prescaler=83, period=0x3fffffff)
The prescaler is set at 83, which makes this timer count at 1 MHz. This is because the CPU clock, running at 168
MHz, is divided by 2 and then by prescaler+1, giving a freqency of 168 MHz/2/(83+1)=1 MHz for timer 2. The period
is set to a large number so that the timer can count up to a large number before wrapping back around to zero. In this
case it will take about 17 minutes before it cycles back to zero.
To use this timer, it’s best to first reset it to 0:
>>> micros.counter(0)
Here you will learn how to write inline assembler in Micro Python.
Note: this is an advanced tutorial, intended for those who already know a bit about microcontrollers and assembly
language.
Micro Python includes an inline assembler. It allows you to write assembly routines as a Python function, and you can
call them as you would a normal Python function.
Returning a value
Inline assembler functions are denoted by a special function decorator. Let’s start with the simplest example:
@micropython.asm_thumb
def fun():
movw(r0, 42)
You can enter this in a script or at the REPL. This function takes no arguments and returns the number 42. r0 is a
register, and the value in this register when the function returns is the value that is returned. Micro Python always
interprets the r0 as an integer, and converts it to an integer object for the caller.
If you run print(fun()) you will see it print out 42.
Accessing peripherals
Accepting arguments
Inline assembler functions can accept up to 3 arguments. If they are used, they must be named r0, r1 and r2 to
reflect the registers and the calling conventions.
Here is a function that adds its arguments:
@micropython.asm_thumb
def asm_add(r0, r1):
add(r0, r0, r1)
This performs the computation r0 = r0 + r1. Since the result is put in r0, that is what is returned. Try
asm_add(1, 2), it should return 3.
Loops
We can assign labels with label(my_label), and branch to them using b(my_label), or a conditional branch
like bgt(my_label).
The following example flashes the green LED. It flashes it r0 times.
@micropython.asm_thumb
def flash_led(r0):
# get the GPIOA address in r1
movwt(r1, stm.GPIOA)
# get the bit mask for PA14 (the pin LED #2 is on)
movw(r2, 1 << 14)
b(loop_entry)
label(loop1)
# turn LED on
strh(r2, [r1, stm.GPIO_BSRRL])
# loop r0 times
sub(r0, r0, 1)
label(loop_entry)
cmp(r0, 0)
bgt(loop1)
pyb.wfi() is used to reduce power consumption while waiting for an event such as an interrupt. You would use it
in the following situation:
while True:
do_some_processing()
pyb.wfi()
There are 4 dedicated connection points on the pyboard for connecting up hobby servo motors (see eg
[Wikipedia](http://en.wikipedia.org/wiki/Servo_%28radio_control%29)). These motors have 3 wires: ground, power
and signal. On the pyboard you can connect them in the bottom right corner, with the signal pin on the far right. Pins
X1, X2, X3 and X4 are the 4 dedicated servo signal pins.
In this picture there are male-male double adaptors to connect the servos to the header pins on the pyboard.
The ground wire on a servo is usually the darkest coloured one, either black or dark brown. The power wire will most
likely be red.
The power pin for the servos (labelled VIN) is connected directly to the input power source of the pyboard. When
powered via USB, VIN is powered through a diode by the 5V USB power line. Connect to USB, the pyboard can
power at least 4 small to medium sized servo motors.
If using a battery to power the pyboard and run servo motors, make sure it is not greater than 6V, since this is the
maximum voltage most servo motors can take. (Some motors take only up to 4.8V, so check what type you are using.)
Plug in a servo to position 1 (the one with pin X1) and create a servo object using:
>>> servo1 = pyb.Servo(1)
The angle here is measured in degrees, and ranges from about -90 to +90, depending on the motor. Calling angle
without parameters will return the current angle:
>>> servo1.angle()
-60
Note that for some angles, the returned angle is not exactly the same as the angle you set, due to rounding errors in
setting the pulse width.
You can pass a second parameter to the angle method, which specifies how long to take (in milliseconds) to reach
the desired angle. For example, to take 1 second (1000 milliseconds) to go from the current position to 50 degrees, use
>>> servo1.angle(50, 1000)
This command will return straight away and the servo will continue to move to the desired angle, and stop when it
gets there. You can use this feature as a speed control, or to synchronise 2 or more servo motors. If we have another
servo motor (servo2 = pyb.Servo(2)) then we can do
>>> servo1.angle(-45, 2000); servo2.angle(60, 2000)
This will move the servos together, making them both take 2 seconds to reach their final angles.
Note: the semicolon between the 2 expressions above is used so that they are executed one after the other when you
press enter at the REPL prompt. In a script you don’t need to do this, you can just write them one line after the other.
So far we have been using standard servos that move to a specific angle and stay at that angle. These servo motors
are useful to create joints of a robot, or things like pan-tilt mechanisms. Internally, the motor has a variable resistor
(potentiometer) which measures the current angle and applies power to the motor proportional to how far it is from the
desired angle. The desired angle is set by the width of a high-pulse on the servo signal wire. A pulse width of 1500
microsecond corresponds to the centre position (0 degrees). The pulses are sent at 50 Hz, ie 50 pulses per second.
You can also get continuous rotation servo motors which turn continuously clockwise or counterclockwise. The
direction and speed of rotation is set by the pulse width on the signal wire. A pulse width of 1500 microseconds
corresponds to a stopped motor. A pulse width smaller or larger than this means rotate one way or the other, at a given
speed.
On the pyboard, the servo object for a continuous rotation motor is the same as before. In fact, using angle you can
set the speed. But to make it easier to understand what is intended, there is another method called speed which sets
the speed:
>>> servo1.speed(30)
speed has the same functionality as angle: you can get the speed, set it, and set it with a time to reach the final
speed.
>>> servo1.speed()
30
>>> servo1.speed(-20)
>>> servo1.speed(0, 2000)
The final command above will set the motor to stop, but take 2 seconds to do it. This is essentially a control over the
acceleration of the continuous servo.
A servo speed of 100 (or -100) is considered maximum speed, but actually you can go a bit faster than that, depending
on the particular motor.
The only difference between the angle and speed methods (apart from the name) is the way the input numbers
(angle or speed) are converted to a pulse width.
Calibration
The conversion from angle or speed to pulse width is done by the servo object using its calibration values. To get the
current calibration, use
>>> servo1.calibration()
(640, 2420, 1500, 2470, 2200)
Of course, you would change the above values to suit your particular servo motor.
Fading LEDs
In addition to turning LEDs on and off, it is also possible to control the brightness of an LED using Pulse-Width
Modulation (PWM), a common technique for obtaining variable output from a digital pin. This allows us to fade an
LED:
Components
Connecting Things Up
For this tutorial, we will use the X1 pin. Connect one end of the resistor to X1, and the other end to the anode of the
LED, which is the longer leg. Connect the cathode of the LED to ground.
Code
By examining the Quick reference for the pyboard, we see that X1 is connected to channel 1 of timer 5 (TIM5 CH1).
Therefore we will first create a Timer object for timer 5, then create a TimerChannel object for channel 1:
from pyb import Timer
from time import sleep
Brightness of the LED in PWM is controlled by controlling the pulse-width, that is the amount of time the LED is on
every cycle. With a timer frequency of 100 Hz, each cycle takes 0.01 second, or 10 ms.
To achieve the fading effect shown at the beginning of this tutorial, we want to set the pulse-width to a small value,
then slowly increase the pulse-width to brighten the LED, and start over when we reach some maximum brightness:
while True:
tchannel.pulse_width(cur_width)
cur_width += wstep
Breathing Effect
If we want to have a breathing effect, where the LED fades from dim to bright then bright to dim, then we simply need
to reverse the sign of wstep when we reach maximum brightness, and reverse it again at minimum brightness. To do
this we modify the while loop to be:
while True:
tchannel.pulse_width(cur_width)
sleep(0.01)
cur_width += wstep
Advanced Exercise
You may have noticed that the LED brightness seems to fade slowly, but increases quickly. This is because our eyes
interprets brightness logarithmically (Weber’s Law ), while the LED’s brightness changes linearly, that is by the same
amount each time. How do you solve this problem? (Hint: what is the opposite of the logarithmic function?)
Addendum
We could have also used the digital-to-analog converter (DAC) to achieve the same effect. The PWM method has the
advantage that it drives the LED with the same current each time, but for different lengths of time. This allows better
control over the brightness, because LEDs do not necessarily exhibit a linear relationship between the driving current
and brightness.
The following video shows how to solder the headers onto the LCD skin. At the end of the video, it shows you how to
correctly connect the LCD skin to the pyboard.
For circuit schematics and datasheets for the components on the skin see The pyboard hardware.
To get started using the LCD, try the following at the Micro Python prompt. Make sure the LCD skin is attached to
the pyboard as pictured at the top of this page.
>>> import pyb
>>> lcd = pyb.LCD(’X’)
>>> lcd.light(True)
>>> lcd.write(’Hello uPy!\n’)
To read the touch-sensor data you need to use the I2C bus. The MPR121 capacitive touch sensor has address 90.
To get started, try:
>>> import pyb
>>> i2c = pyb.I2C(1, pyb.I2C.MASTER)
>>> i2c.mem_write(4, 90, 0x5e)
>>> touch = i2c.mem_read(1, 90, 0)[0]
The first line above makes an I2C object, and the second line enables the 4 touch sensors. The third line reads the
touch status and the touch variable holds the state of the 4 touch buttons (A, B, X, Y).
There is a simple driver here which allows you to set the threshold and debounce parameters, and easily read the touch
status and electrode voltage levels. Copy this script to your pyboard (either flash or SD card, in the top directory or
lib/ directory) and then try:
>>> import pyb
>>> import mpr121
>>> m = mpr121.MPR121(pyb.I2C(1, pyb.I2C.MASTER))
>>> for i in range(100):
... print(m.touch_status())
... pyb.delay(100)
...
This will continuously print out the touch status of all electrodes. Try touching each one in turn.
Note that if you put the LCD skin in the Y-position, then you need to initialise the I2C bus using:
>>> m = mpr121.MPR121(pyb.I2C(2, pyb.I2C.MASTER))
There is also a demo which uses the LCD and the touch sensors together, and can be found here.
The following video shows how to solder the headers, microphone and speaker onto the AMP skin.
For circuit schematics and datasheets for the components on the skin see The pyboard hardware.
Example code
The AMP skin has a speaker which is connected to DAC(1) via a small power amplifier. The volume of the amplifier
is controlled by a digital potentiometer, which is an I2C device with address 46 on the IC2(1) bus.
To set the volume, define the following function:
import pyb
def volume(val):
pyb.I2C(1, pyb.I2C.MASTER).mem_write(val, 46, 0)
To play a sound, use the write_timed method of the DAC object. For example:
import math
from pyb import DAC
You can also play WAV files using the Python wave module. You can get the wave module here and you will also
need the chunk module available here. Put these on your pyboard (either on the flash or the SD card in the top-level
directory). You will need an 8-bit WAV file to play, such as this one, or to convert any file you have with the command:
avconv -i original.wav -ar 22050 -codec pcm_u8 test.wav
A pin used as input from a switch or other mechanical device can have a lot of noise on it, rapidly changing from
low to high when the switch is first pressed or released. This noise can be eliminated using a capacitor (a debouncing
circuit). It can also be eliminated using a simple function that makes sure the value on the pin is stable.
The following function does just this. It gets the current value of the given pin, and then waits for the value to change.
The new pin value must be stable for a continuous 20ms for it to register the change. You can adjust this time (to say
50ms) if you still have noise.
import pyb
def wait_pin_change(pin):
# wait for pin to change value
# it needs to be stable for a continuous 20ms
cur_value = pin.value()
active = 0
while active < 20:
if pin.value() != cur_value:
active += 1
else:
active = 0
pyb.delay(1)
The cmath module provides some basic mathematical funtions for working with complex numbers.
Functions
cmath.cos(z)
Return the cosine of z.
cmath.exp(z)
Return the exponential of z.
cmath.log(z)
Return the natural logarithm of z. The branch cut is along the negative real axis.
cmath.log10(z)
Return the base-10 logarithm of z. The branch cut is along the negative real axis.
cmath.phase(z)
Returns the phase of the number z, in the range (-pi, +pi].
cmath.polar(z)
Returns, as a tuple, the polar form of z.
cmath.rect(r, phi)
Returns the complex number with modulus r and phase phi.
cmath.sin(z)
Return the sine of z.
cmath.sqrt(z)
Return the square-root of z.
Constants
cmath.e
base of the natural logarithm
cmath.pi
the ratio of a circle’s circumference to its diameter
Functions
gc.enable()
Enable automatic garbage collection.
gc.disable()
Disable automatic garbage collection. Heap memory can still be allocated, and garbage collection can still be
initiated manually using gc.collect().
gc.collect()
Run a garbage collection.
gc.mem_alloc()
Return the number of bytes of heap RAM that are allocated.
gc.mem_free()
Return the number of bytes of available heap RAM.
The math module provides some basic mathematical funtions for working with floating-point numbers.
Note: On the pyboard, floating-point numbers have 32-bit precision.
Functions
math.acos(x)
Return the inverse cosine of x.
math.acosh(x)
Return the inverse hyperbolic cosine of x.
math.asin(x)
Return the inverse sine of x.
math.asinh(x)
Return the inverse hyperbolic sine of x.
math.atan(x)
Return the inverse tangent of x.
math.atan2(y, x)
Return the principal value of the inverse tangent of y/x.
math.atanh(x)
Return the inverse hyperbolic tangent of x.
math.ceil(x)
Return an integer, being x rounded towards positive infinity.
math.copysign(x, y)
Return x with the sign of y.
math.cos(x)
Return the cosine of x.
math.cosh(x)
Return the hyperbolic cosine of x.
math.degrees(x)
Return radians x converted to degrees.
math.erf(x)
Return the error function of x.
math.erfc(x)
Return the complementary error function of x.
math.exp(x)
Return the exponential of x.
math.expm1(x)
Return exp(x) - 1.
math.fabs(x)
Return the absolute value of x.
math.floor(x)
Return an integer, being x rounded towards negative infinity.
math.fmod(x, y)
Return the remainder of x/y.
math.frexp(x)
Decomposes a floating-point number into its mantissa and exponent. The returned value is the tuple (m, e)
such that x == m * 2**e exactly. If x == 0 then the function returns (0.0, 0), otherwise the relation
0.5 <= abs(m) < 1 holds.
math.gamma(x)
Return the gamma function of x.
math.isfinite(x)
Return True if x is finite.
math.isinf(x)
Return True if x is infinite.
math.isnan(x)
Return True if x is not-a-number
math.ldexp(x, exp)
Return x * (2**exp).
math.lgamma(x)
Return the natural logarithm of the gamma function of x.
math.log(x)
Return the natural logarithm of x.
math.log10(x)
Return the base-10 logarithm of x.
math.log2(x)
Return the base-2 logarithm of x.
math.modf(x)
Return a tuple of two floats, being the fractional and integral parts of x. Both return values have the same sign
as x.
math.pow(x, y)
Returns x to the power of y.
math.radians(x)
Return degrees x converted to radians.
math.sin(x)
Return the sine of x.
math.sinh(x)
Return the hyperbolic sine of x.
math.sqrt(x)
Return the square root of x.
math.tan(x)
Return the tangent of x.
math.tanh(x)
Return the hyperbolic tangent of x.
math.trunc(x)
Return an integer, being x rounded towards 0.
Constants
math.e
base of the natural logarithm
math.pi
the ratio of a circle’s circumference to its diameter
Pyboard specifics
The filesystem on the pyboard has / as the root directory and the available physical drives are accessible from here.
They are currently:
/flash – the internal flash filesystem
/sd – the SD card (if it exists)
On boot up, the current directory is /flash if no SD card is inserted, otherwise it is /sd.
Functions
os.chdir(path)
Change current directory.
os.getcwd()
Get the current directory.
os.listdir([dir ])
With no argument, list the current directory. Otherwise list the given directory.
os.mkdir(path)
Create a new directory.
os.remove(path)
Remove a file.
os.rmdir(path)
Remove a directory.
os.stat(path)
Get the status of a file or directory.
os.sync()
Sync all filesystems.
os.urandom(n)
Return a bytes object with n random bytes, generated by the hardware random number generator.
Constants
os.sep
separation character used in paths
This module provides functions to wait for events on streams (select streams which are ready for operations).
Pyboard specifics
Polling is an efficient way of waiting for read/write activity on multiple objects. Current objects that support polling
are: pyb.UART, pyb.USB_VCP.
Functions
select.poll()
Create an instance of the Poll class.
select.select(rlist, wlist, xlist[, timeout ])
Wait for activity on a set of objects.
This function is provided for compatibility and is not efficient. Usage of Poll is recommended instead.
class Poll
Methods
poll.register(obj[, eventmask ])
Register obj for polling. eventmask is 1 for read, 2 for write, 3 for read-write.
poll.unregister(obj)
Unregister obj from polling.
poll.modify(obj, eventmask)
Modify the eventmask for obj.
poll.poll([timeout ])
Wait for at least one of the registered objects to become ready. Returns list of ready objects, or empty list on
timeout.
Timeout is in milliseconds.
Functions
struct.calcsize(fmt)
Return the number of bytes needed to store the given fmt.
struct.pack(fmt, v1, v2, ...)
Pack the values v1, v2, ... according to the format string fmt. The return value is a bytes object encoding the
values.
struct.unpack(fmt, data)
Unpack from the data according to the format string fmt. The return value is a tuple of the unpacked values.
Functions
sys.exit([retval ])
Raise a SystemExit exception. If an argument is given, it is the value given to SystemExit.
sys.print_exception(exc[, file ])
Print exception with a traceback to a file-like object file (or sys.stdout by default).
Difference to CPython
This function appears in the traceback module in CPython.
Constants
sys.argv
a mutable list of arguments this program started with
sys.byteorder
the byte order of the system (“little” or “big”)
sys.path
a mutable list of directories to search for imported modules
sys.platform
The platform that Micro Python is running on. This is “pyboard” on the pyboard and provides a robust way of
determining if a script is running on the pyboard or not.
sys.stderr
standard error (connected to USB VCP, and optional UART object)
sys.stdin
standard input (connected to USB VCP, and optional UART object)
sys.stdout
standard output (connected to USB VCP, and optional UART object)
sys.version
Python language version that this implementation conforms to, as a string
sys.version_info
Python language version that this implementation conforms to, as a tuple of ints
The time module provides functions for getting the current time and date, and for sleeping.
Functions
time.localtime([secs ])
Convert a time expressed in seconds since Jan 1, 2000 into an 8-tuple which contains: (year, month, mday, hour,
minute, second, weekday, yearday) If secs is not provided or None, then the current time from the RTC is used.
year includes the century (for example 2014).
•month is 1-12
•mday is 1-31
•hour is 0-23
•minute is 0-59
•second is 0-59
•weekday is 0-6 for Mon-Sun
•yearday is 1-366
time.mktime()
This is inverse function of localtime. It’s argument is a full 8-tuple which expresses a time as per localtime. It
returns an integer which is the number of seconds since Jan 1, 2000.
time.sleep(seconds)
Sleep for the given number of seconds. Seconds can be a floating-point number to sleep for a fractional number
of seconds.
time.time()
Returns the number of seconds, as an integer, since 1/1/2000.
The following standard Python libraries have been “micro-ified” to fit in with the philosophy of Micro Python. They
provide the core functionality of that module and are intended to be a drop-in replacement for the standard Python
library.
The modules are available by their u-name, and also by their non-u-name. The non-u-name can be overridden by a
file of that name in your package path. For example, import json will first search for a file json.py or directory
json and load that package if it is found. If nothing is found, it will fallback to loading the built-in ujson module.
This module implements conversions between binary data and various encodings of it in ASCII form (in both direc-
tions).
Functions
ubinascii.hexlify(data)
Convert binary data to hexadecimal representation. Return bytes string.
This module implements “foreign data interface” for MicroPython. The idea behind it is similar to CPython’s ctypes
modules, but actual API is different, steamlined and optimized for small size.
Structure layout is defined by a “descriptor” - a Python dictionary which encodes field names as keys and other
properties required to access them as an associated values. Currently, uctypes requires explicit specification of offsets
for each field. Offset are given in bytes from structure start.
Following are encoding examples for various field types:
Scalar types:
"field_name": uctypes.UINT32 | 0
in other words, value is scalar type identifier ORed with field offset (in bytes) from the start of the struc-
ture.
Recursive structures:
"sub": (2, {
"b0": uctypes.UINT8 | 0,
"b1": uctypes.UINT8 | 1,
})
i.e. value is a 2-tuple, first element of which is offset, and second is a structure descriptor dictionary (note:
offsets in recursive descriptors are relative to a structure it defines).
Arrays of primitive types:
"arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2),
i.e. value is a 2-tuple, first element of which is ARRAY flag ORed with offset, and second is scalar
element type ORed number of elements in array.
Arrays of aggregate types:
"arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}),
i.e. value is a 3-tuple, first element of which is ARRAY flag ORed with offset, second is a number of
elements in array, and third is descriptor of element type.
Pointer to a primitive type:
"ptr": (uctypes.PTR | 0, uctypes.UINT8),
i.e. value is a 2-tuple, first element of which is PTR flag ORed with offset, and second is scalar element
type.
Pointer to aggregate type:
"ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}),
i.e. value is a 2-tuple, first element of which is PTR flag ORed with offset, second is descriptor of type
pointed to.
Bitfields:
"bitf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 8 << uctypes.BF_LEN,
i.e. value is type of scalar value containing given bitfield (typenames are similar to scalar types, but
prefixes with “BF”), ORed with offset for scalar value containing the bitfield, and further ORed with
values for bit offset and bit length of the bitfield within scalar value, shifted by BF_POS and BF_LEN
positions, respectively. Bitfield position is counted from the least significant bit, and is the number of
right-most bit of a field (in other words, it’s a number of bits a scalar needs to be shifted right to extra the
bitfield).
In the example above, first UINT16 value will be extracted at offset 0 (this detail may be important
when accessing hardware registers, where particular access size and alignment are required), and then
bitfield whose rightmost bit is least-significant bit of this UINT16, and length is 8 bits, will be extracted -
effectively, this will access least-significant byte of UINT16.
Note that bitfield operations are independent of target byte endianness, in particular, example above will
access least-significant byte of UINT16 in both little- and big-endian structures. But it depends on the
least significant bit being numbered 0. Some targets may use different numbering in their native ABI, but
uctypes always uses normalized numbering described above.
Module contents
Structure objects
Structure objects allow accessing individual fields using standard dot notation: my_struct.field1. If a field is
of scalar type, getting it will produce primitive value (Python integer or float) corresponding to value contained in a
field. Scalar field can also be assigned to.
If a field is an array, its individual elements can be accessed with standard subscript operator - both read and assigned
to.
If a field is a pointer, it can be dereferenced using [0] syntax (corresponding to C * operator, though [0] works in C
too). Subscripting pointer with other integer values but 0 are supported too, with the same semantics as in C.
Summing up, accessing structure fields generally follows C syntax, except for pointer derefence, you need to use [0]
operator instead of *.
This module implements binary data hashing algorithms. Currently, it implements SHA256 algorithm. Choosing
SHA256 was a deliberate choice, as a modern, cryptographically secure algorithm. This means that a single algorithm
can cover both usecases of “any hash algorithm” and security-related usage, and thus save space omitting legacy
algorithms like MD5 or SHA1.
Constructors
class uhashlib.sha256([data ])
Create a hasher object and optionally feed data into it.
Methods
sha256.update(data)
Feed more binary data into hash.
sha256.digest()
Return hash for all data passed thru hash, as a bytes object. After this method is called, more data cannot be fed
into hash any longer.
sha256.hexdigest()
This method is NOT implemented. Use ubinascii.hexlify(sha256.digest()) to achieve similar
effect.
Functions
uheapq.heappush(heap, item)
Push the item onto the heap.
uheapq.heappop(heap)
Pop the first item from the heap, and return it. Raises IndexError if heap is empty.
uheapq.heapify(x)
Convert the list x into a heap. This is an in-place operation.
This modules allows to convert between Python objects and the JSON data format.
Functions
ujson.dumps(obj)
Return obj represented as a JSON string.
ujson.loads(str)
Parse the JSON str and return an object. Raises ValueError if the string is not correctly formed.
This module implements regular expression operations. Regular expression syntax supported is a subset of CPython
re module (and actually is a subset of POSIX extended regular expressions).
Supported operators are:
’.’ Match any character.
’[]’ Match set of characters. Individual characters and ranges are supported.
’^’
’$’
’?’
’*’
’+’
’??’
’*?’
’+?’
Counted repetitions ({m,n}), more advanced assertions, names groups, etc. are not supported.
Functions
ure.compile(regex)
Compile regular expression, return regex object.
ure.match(regex, string)
Match regex against string. Match always happens from starting position in a string.
ure.search(regex, string)
Search regex in a string. Unlike match, this will search string for first position which matches regex
(which still may be 0 if regex is anchored).
ure.DEBUG
Flag value, display debug information about compiled expression.
Regex objects
Compiled regular expression. Instances of this class are created using ure.compile().
regex.match(string)
regex.search(string)
regex.split(string, max_split=-1)
Match objects
Socket functionality.
Functions
usocket.getaddrinfo(host, port)
usocket.socket(family=AF_INET, type=SOCK_STREAM, fileno=-1)
Create a socket.
This modules allows to decompress binary data compressed with DEFLATE algorithm (commonly used in zlib library
and gzip archiver). Compression is not yet implemented.
Functions
uzlib.decompress(data)
Return decompressed data as bytes.
pyb.delay(ms)
Delay for the given number of milliseconds.
pyb.udelay(us)
Delay for the given number of microseconds.
pyb.millis()
Returns the number of milliseconds since the board was last reset.
The result is always a micropython smallint (31-bit signed number), so after 2^30 milliseconds (about 12.4 days)
this will start to return negative numbers.
pyb.micros()
Returns the number of microseconds since the board was last reset.
The result is always a micropython smallint (31-bit signed number), so after 2^30 microseconds (about 17.8
minutes) this will start to return negative numbers.
pyb.elapsed_millis(start)
Returns the number of milliseconds which have elapsed since start.
This function takes care of counter wrap, and always returns a positive number. This means it can be used to
measure periods upto about 12.4 days.
Example:
start = pyb.millis()
while pyb.elapsed_millis(start) < 1000:
# Perform some operation
pyb.elapsed_micros(start)
Returns the number of microseconds which have elapsed since start.
This function takes care of counter wrap, and always returns a positive number. This means it can be used to
measure periods upto about 17.8 minutes.
Example:
start = pyb.micros()
while pyb.elapsed_micros(start) < 1000:
# Perform some operation
pass
pyb.hard_reset()
Resets the pyboard in a manner similar to pushing the external RESET button.
pyb.bootloader()
Activate the bootloader without BOOT* pins.
pyb.disable_irq()
Disable interrupt requests. Returns the previous IRQ state: False/True for disabled/enabled IRQs respec-
tively. This return value can be passed to enable_irq to restore the IRQ to its original state.
pyb.enable_irq(state=True)
Enable interrupt requests. If state is True (the default value) then IRQs are enabled. If state is False
then IRQs are disabled. The most common use of this function is to pass it the value returned by disable_irq
to exit a critical section.
If given any arguments then the function sets the frequency of the CPU, and the busses if additional arguments
are given. Frequencies are given in Hz. Eg freq(120000000) sets sysclk (the CPU frequency) to 120MHz. Note
that not all values are supported and the largest supported frequency not greater than the given value will be
selected.
Supported sysclk frequencies are (in MHz): 8, 16, 24, 30, 32, 36, 40, 42, 48, 54, 56, 60, 64, 72, 84, 96, 108,
120, 144, 168.
The maximum frequency of hclk is 168MHz, of pclk1 is 42MHz, and of pclk2 is 84MHz. Be sure not to set
frequencies above these values.
The hclk, pclk1 and pclk2 frequencies are derived from the sysclk frequency using a prescaler (divider). Sup-
ported prescalers for hclk are: 1, 2, 4, 8, 16, 64, 128, 256, 512. Supported prescalers for pclk1 and pclk2 are: 1,
2, 4, 8. A prescaler will be chosen to best match the requested frequency.
A sysclk frequency of 8MHz uses the HSE (external crystal) directly and 16MHz uses the HSI (internal oscilla-
tor) directly. The higher frequencies use the HSE to drive the PLL (phase locked loop), and then use the output
of the PLL.
Note that if you change the frequency while the USB is enabled then the USB may become unreliable. It is
best to change the frequency in boot.py, before the USB peripheral is started. Also note that sysclk frequencies
below 36MHz do not allow the USB to function correctly.
pyb.wfi()
Wait for an interrupt. This executies a wfi instruction which reduces power consumption of the MCU until an
interrupt occurs, at which point execution continues.
pyb.standby()
pyb.stop()
Miscellaneous functions
pyb.have_cdc()
Return True if USB is connected as a serial device, False otherwise.
pyb.hid((buttons, x, y, z))
Takes a 4-tuple (or list) and sends it to the USB host (the PC) to signal a HID mouse-motion event.
pyb.info([dump_alloc_table ])
Print out lots of information about the board.
pyb.mount(device, mountpoint, *, readonly=False, mkfs=False)
Mount a block device and make it available as part of the filesystem. device must be an object that provides
the block protocol:
•readblocks(self, blocknum, buf)
•writeblocks(self, blocknum, buf) (optional)
•count(self)
•sync(self) (optional)
readblocks and writeblocks should copy data between buf and the block device, starting from block
number blocknum on the device. buf will be a bytearray with length a multiple of 512. If writeblocks is
not defined then the device is mounted read-only. The return value of these two functions is ignored.
count should return the number of blocks available on the device. sync, if implemented, should sync the data
on the device.
The parameter mountpoint is the location in the root of the filesystem to mount the device. It must begin
with a forward-slash.
If readonly is True, then the device is mounted read-only, otherwise it is mounted read-write.
If mkfs is True, then a new filesystem is created if one does not already exist.
To unmount a device, pass None as the device and the mount location as mountpoint.
pyb.repl_uart(uart)
Get or set the UART object that the REPL is repeated on.
pyb.rng()
Return a 30-bit hardware generated random number.
pyb.sync()
Sync all file systems.
pyb.unique_id()
Returns a string of 12 bytes (96 bits), which is the unique ID for the MCU.
Classes
class Accel – accelerometer control Accel is an object that controls the accelerometer. Example usage:
accel = pyb.Accel()
for i in range(10):
print(accel.x(), accel.y(), accel.z())
Constructors
class pyb.Accel
Create and return an accelerometer object.
Note: if you read accelerometer values immediately after creating this object you will get 0. It takes around
20ms for the first sample to be ready, so, unless you have some other code between creating this object and
reading its values, you should put a pyb.delay(20) after creating it. For example:
accel = pyb.Accel()
pyb.delay(20)
print(accel.x())
Methods
accel.filtered_xyz()
Get a 3-tuple of filtered x, y and z values.
accel.tilt()
Get the tilt register.
accel.x()
Get the x-axis value.
accel.y()
Get the y-axis value.
accel.z()
Get the z-axis value.
class ADC – analog to digital conversion: read analog values on a pin Usage:
import pyb
Constructors
class pyb.ADC(pin)
Create an ADC object associated with the given pin. This allows you to then read analog values on that pin.
Methods
adc.read()
Read the value on the analog pin and return it. The returned value will be between 0 and 4095.
adc.read_timed(buf, freq)
Read analog values into the given buffer at the given frequency. Buffer can be bytearray or array.array for
example. If a buffer with 8-bit elements is used, sample resolution will be reduced to 8 bits.
Example:
adc = pyb.ADC(pyb.Pin.board.X19) # create an ADC on pin X19
buf = bytearray(100) # create a buffer of 100 bytes
adc.read_timed(buf, 10) # read analog values into buf at 10Hz
# this will take 10 seconds to finish
for val in buf: # loop over all values
print(val) # print the value out
class CAN – controller area network communication bus CAN implements the standard CAN communications
protocol. At the physical level it consists of 2 lines: RX and TX. Note that to connect the pyboard to a CAN bus you
must use a CAN transceiver to convert the CAN logic signals from the pyboard to the correct voltage levels on the bus.
Example usage (works without anything connected):
from pyb import CAN
can = CAN(1, CAN.LOOPBACK)
can.setfilter(0, CAN.LIST16, 0, (123, 124, 125, 126)) # set a filter to receive messages with id=123
can.send(’message!’, 123) # send a message with id 123
can.recv(0) # receive message on FIFO 0
Constructors
class pyb.CAN(bus, ...)
Construct a CAN object on the given bus. bus can be 1-2, or ‘YA’ or ‘YB’. With no additional parameters, the
CAN object is created but not initialised (it has the settings from the last initialisation of the bus, if any). If extra
arguments are given, the bus is initialised. See init for parameters of initialisation.
The physical pins of the CAN busses are:
•CAN(1) is on YA: (RX, TX) = (Y3, Y4) = (PB8, PB9)
•CAN(2) is on YB: (RX, TX) = (Y5, Y6) = (PB12, PB13)
Class Methods
CAN.initfilterbanks(nr)
Reset and disable all filter banks and assign how many banks should be available for CAN(1).
STM32F405 has 28 filter banks that are shared between the two available CAN bus controllers. This function
configures how many filter banks should be assigned to each. nr is the number of banks that will be assigned
to CAN(1), the rest of the 28 are assigned to CAN(2). At boot, 14 banks are assigned to each controller.
Methods
can.init(mode, extframe=False, prescaler=100, *, sjw=1, bs1=6, bs2=8)
Initialise the CAN bus with the given parameters:
•mode is one of: NORMAL, LOOPBACK, SILENT, SILENT_LOOPBACK
•if extframe is True then the bus uses extended identifiers in the frames (29 bits); otherwise it uses
standard 11 bit identifiers
•prescaler is used to set the duration of 1 time quanta; the time quanta will be the input clock (PCLK1,
see pyb.freq()) divided by the prescaler
•sjw is the resynchronisation jump width in units of the time quanta; it can be 1, 2, 3, 4
•bs1 defines the location of the sample point in units of the time quanta; it can be between 1 and 1024
inclusive
•bs2 defines the location of the transmit point in units of the time quanta; it can be between 1 and 16
inclusive
The time quanta tq is the basic unit of time for the CAN bus. tq is the CAN prescaler value divided by PCLK1
(the frequency of internal peripheral bus 1); see pyb.freq() to determine PCLK1.
A single bit is made up of the synchronisation segment, which is always 1 tq. Then follows bit segment 1, then
bit segment 2. The sample point is after bit segment 1 finishes. The transmit point is after bit segment 2 finishes.
The baud rate will be 1/bittime, where the bittime is 1 + BS1 + BS2 multiplied by the time quanta tq.
For example, with PCLK1=42MHz, prescaler=100, sjw=1, bs1=6, bs2=8, the value of tq is 2.38 microseconds.
The bittime is 35.7 microseconds, and the baudrate is 28kHz.
See page 680 of the STM32F405 datasheet for more details.
can.deinit()
Turn off the CAN bus.
can.setfilter(bank, mode, fifo, params)
Configure a filter bank:
•bank is the filter bank that is to be configured.
•mode is the mode the filter should operate in.
•fifo is which fifo (0 or 1) a message should be stored in, if it is accepted by this filter.
•params is an array of values the defines the filter. The contents of the array depends on the mode
argument.
mode contents of parameter array
CAN.LIST16 Four 16 bit ids that will be accepted
CAN.LIST32 Two 32 bit ids that will be accepted
CAN.MASK16
Two 16 bit id/mask pairs. E.g. (1, 3, 4, 4)
The first pair, 1 and 3 will accept all ids
that have bit 0 = 1 and bit 1 = 0.
The second pair, 4 and 4, will accept all ids
that have bit 2 = 1.
Constants
CAN.NORMAL
CAN.LOOPBACK
CAN.SILENT
CAN.SILENT_LOOPBACK
the mode of the CAN bus
CAN.LIST16
CAN.MASK16
CAN.LIST32
CAN.MASK32
the operation mode of a filter
class DAC – digital to analog conversion The DAC is used to output analog values (a specific voltage) on pin X5
or pin X6. The voltage will be between 0 and 3.3V.
This module will undergo changes to the API.
Example usage:
from pyb import DAC
Constructors
class pyb.DAC(port)
Construct a new DAC object.
port can be a pin object, or an integer (1 or 2). DAC(1) is on pin X5 and DAC(2) is on pin X6.
Methods
dac.noise(freq)
Generate a pseudo-random noise signal. A new random sample is written to the DAC output at the given
frequency.
dac.triangle(freq)
Generate a triangle wave. The value on the DAC output changes at the given frequency, and the frequence of
the repeating triangle wave itself is 2048 times smaller.
dac.write(value)
Direct access to the DAC output (8 bit only at the moment).
dac.write_timed(data, freq, *, mode=DAC.NORMAL)
Initiates a burst of RAM to DAC using a DMA transfer. The input data is treated as an array of bytes (8 bit data).
mode can be DAC.NORMAL or DAC.CIRCULAR.
TIM6 is used to control the frequency of the transfer.
class ExtInt – configure I/O pins to interrupt on external events There are a total of 22 interrupt lines. 16 of these
can come from GPIO pins and the remaining 6 are from internal sources.
For lines 0 thru 15, a given line can map to the corresponding line from an arbitrary port. So line 0 can map to Px0
where x is A, B, C, ... and line 1 can map to Px1 where x is A, B, C, ...
def callback(line):
print("line =", line)
Now every time a falling edge is seen on the X1 pin, the callback will be called. Caution: mechani-
cal pushbuttons have “bounce” and pushing or releasing a switch will often generate multiple edges. See:
http://www.eng.utah.edu/~cs5780/debouncing.pdf for a detailed explanation, along with various techniques for de-
bouncing.
Trying to register 2 callbacks onto the same pin will throw an exception.
If pin is passed as an integer, then it is assumed to map to one of the internal interrupt sources, and must be in the
range 16 thru 22.
All other pin objects go through the pin mapper to come up with one of the gpio pins.
extint = pyb.ExtInt(pin, mode, pull, callback)
Constructors
class pyb.ExtInt(pin, mode, pull, callback)
Create an ExtInt object:
•pin is the pin on which to enable the interrupt (can be a pin object or any valid pin name).
•mode can be one of: - ExtInt.IRQ_RISING - trigger on a rising edge; - ExtInt.IRQ_FALLING -
trigger on a falling edge; - ExtInt.IRQ_RISING_FALLING - trigger on a rising or falling edge.
•pull can be one of: - pyb.Pin.PULL_NONE - no pull up or down resistors; - pyb.Pin.PULL_UP -
enable the pull-up resistor; - pyb.Pin.PULL_DOWN - enable the pull-down resistor.
•callback is the function to call when the interrupt triggers. The callback function must accept exactly
1 argument, which is the line that triggered the interrupt.
Class methods
ExtInt.regs()
Dump the values of the EXTI registers.
Methods
extint.disable()
Disable the interrupt associated with the ExtInt object. This could be useful for debouncing.
extint.enable()
Enable a disabled interrupt.
extint.line()
Return the line number that the pin is mapped to.
extint.swint()
Trigger the callback from software.
Constants
ExtInt.IRQ_FALLING
interrupt on a falling edge
ExtInt.IRQ_RISING
interrupt on a rising edge
ExtInt.IRQ_RISING_FALLING
interrupt on a rising or falling edge
class I2C – a two-wire serial protocol I2C is a two-wire protocol for communicating between devices. At the
physical level it consists of 2 wires: SCL and SDA, the clock and data lines respectively.
I2C objects are created attached to a specific bus. They can be initialised when created, or initialised later on:
from pyb import I2C
Printing the i2c object gives you information about its configuration.
Basic methods for slave are send and recv:
Constructors
class pyb.I2C(bus, ...)
Construct an I2C object on the given bus. bus can be 1 or 2. With no additional parameters, the I2C object is
created but not initialised (it has the settings from the last initialisation of the bus, if any). If extra arguments are
given, the bus is initialised. See init for parameters of initialisation.
The physical pins of the I2C busses are:
•I2C(1) is on the X position: (SCL, SDA) = (X9, X10) = (PB6, PB7)
•I2C(2) is on the Y position: (SCL, SDA) = (Y9, Y10) = (PB10, PB11)
Methods
i2c.deinit()
Turn off the I2C bus.
i2c.init(mode, *, addr=0x12, baudrate=400000, gencall=False)
Initialise the I2C bus with the given parameters:
•mode must be either I2C.MASTER or I2C.SLAVE
•addr is the 7-bit address (only sensible for a slave)
•baudrate is the SCL clock rate (only sensible for a master)
•gencall is whether to support general call mode
i2c.is_ready(addr)
Check if an I2C device responds to the given address. Only valid when in master mode.
i2c.mem_read(data, addr, memaddr, timeout=5000, addr_size=8)
Read from the memory of an I2C device:
Constants
I2C.MASTER
for initialising the bus to master mode
I2C.SLAVE
for initialising the bus to slave mode
class LCD – LCD control for the LCD touch-sensor pyskin The LCD class is used to control the LCD on the
LCD touch-sensor pyskin, LCD32MKv1.0. The LCD is a 128x32 pixel monochrome screen, part NHD-C12832A1Z.
The pyskin must be connected in either the X or Y positions, and then an LCD object is made using:
lcd = pyb.LCD(’X’) # if pyskin is in the X position
lcd = pyb.LCD(’Y’) # if pyskin is in the Y position
This driver implements a double buffer for setting/getting pixels. For example, to make a bouncing dot, try:
x = y = 0
dx = dy = 1
while True:
# update the dot’s position
x += dx
y += dy
Constructors
class pyb.LCD(skin_position)
Construct an LCD object in the given skin position. skin_position can be ‘X’ or ‘Y’, and should match
the position where the LCD pyskin is plugged in.
Methods
lcd.command(instr_data, buf )
Send an arbitrary command to the LCD. Pass 0 for instr_data to send an instruction, otherwise pass 1 to
send data. buf is a buffer with the instructions/data to send.
lcd.contrast(value)
Set the contrast of the LCD. Valid values are between 0 and 47.
lcd.fill(colour)
Fill the screen with the given colour (0 or 1 for white or black).
This method writes to the hidden buffer. Use show() to show the buffer.
lcd.get(x, y)
Get the pixel at the position (x, y). Returns 0 or 1.
This method reads from the visible buffer.
lcd.light(value)
Turn the backlight on/off. True or 1 turns it on, False or 0 turns it off.
lcd.pixel(x, y, colour)
Set the pixel at (x, y) to the given colour (0 or 1).
This method writes to the hidden buffer. Use show() to show the buffer.
lcd.show()
Show the hidden buffer on the screen.
lcd.text(str, x, y, colour)
Draw the given text to the position (x, y) using the given colour (0 or 1).
This method writes to the hidden buffer. Use show() to show the buffer.
lcd.write(str)
Write the string str to the screen. It will appear immediately.
class LED – LED object The LED object controls an individual LED (Light Emitting Diode).
Constructors
class pyb.LED(id)
Create an LED object associated with the given LED:
•id is the LED number, 1-4.
Methods
led.intensity([value ])
Get or set the LED intensity. Intensity ranges between 0 (off) and 255 (full on). If no argument is given, return
the LED intensity. If an argument is given, set the LED intensity and return None.
led.off()
Turn the LED off.
led.on()
Turn the LED on, to maximum intensity.
led.toggle()
Toggle the LED between on (maximum intensity) and off. If the LED is at non-zero intensity then it is considered
“on” and toggle will turn it off.
class Pin – control I/O pins A pin is the basic object to control I/O pins. It has methods to set the mode of the pin
(input, output, etc) and methods to get and set the digital logic level. For analog control of a pin, see the ADC class.
Usage Model:
All Board Pins are predefined as pyb.Pin.board.Name
x1_pin = pyb.Pin.board.X1
g = pyb.Pin(pyb.Pin.board.X1, pyb.Pin.IN)
CPU pins which correspond to the board pins are available as pyb.cpu.Name. For the CPU pins, the names are the
port letter followed by the pin number. On the PYBv1.0, pyb.Pin.board.X1 and pyb.Pin.cpu.B6 are the
same pin.
You can also use strings:
g = pyb.Pin(’X1’, pyb.Pin.OUT_PP)
pyb.Pin.mapper(MyMapper)
Constructors
class pyb.Pin(id, ...)
Create a new Pin object associated with the id. If additional arguments are given, they are used to initialise the
pin. See pin.init().
Class methods
Pin.af_list()
Returns an array of alternate functions available for this pin.
Pin.debug([state ])
Get or set the debugging state (True or False for on or off).
Pin.dict([dict ])
Get or set the pin mapper dictionary.
Pin.mapper([fun ])
Get or set the pin mapper function.
Methods
pin.init(mode, pull=Pin.PULL_NONE, af=-1)
Initialise the pin:
•mode can be one of: - Pin.IN - configure the pin for input; - Pin.OUT_PP - configure the pin for
output, with push-pull control; - Pin.OUT_OD - configure the pin for output, with open-drain control; -
Pin.AF_PP - configure the pin for alternate function, pull-pull; - Pin.AF_OD - configure the pin for
alternate function, open-drain; - Pin.ANALOG - configure the pin for analog.
•pull can be one of: - Pin.PULL_NONE - no pull up or down resistors; - Pin.PULL_UP - enable the
pull-up resistor; - Pin.PULL_DOWN - enable the pull-down resistor.
•when mode is Pin.AF_PP or Pin.AF_OD, then af can be the index or name of one of the alternate functions
associated with a pin.
Returns: None.
pin.high()
Set the pin to a high logic level.
pin.low()
Set the pin to a low logic level.
pin.value([value ])
Get or set the digital logic level of the pin:
•With no argument, return 0 or 1 depending on the logic level of the pin.
•With value given, set the logic level of the pin. value can be anything that converts to a boolean. If it
converts to True, the pin is set high, otherwise it is set low.
pin.__str__()
Return a string describing the pin object.
pin.af()
Returns the currently configured alternate-function of the pin. The integer returned will match one of the allowed
constants for the af argument to the init function.
pin.gpio()
Returns the base address of the GPIO block associated with this pin.
pin.mode()
Returns the currently configured mode of the pin. The integer returned will match one of the allowed constants
for the mode argument to the init function.
pin.name()
Get the pin name.
pin.names()
Returns the cpu and board names for this pin.
pin.pin()
Get the pin number.
pin.port()
Get the pin port.
pin.pull()
Returns the currently configured pull of the pin. The integer returned will match one of the allowed constants
for the pull argument to the init function.
Constants
Pin.AF_OD
initialise the pin to alternate-function mode with an open-drain drive
Pin.AF_PP
initialise the pin to alternate-function mode with a push-pull drive
Pin.ANALOG
initialise the pin to analog mode
Pin.IN
initialise the pin to input mode
Pin.OUT_OD
initialise the pin to output mode with an open-drain drive
Pin.OUT_PP
initialise the pin to output mode with a push-pull drive
Pin.PULL_DOWN
enable the pull-down resistor on the pin
Pin.PULL_NONE
don’t enable any pull up or down resistors on the pin
Pin.PULL_UP
enable the pull-up resistor on the pin
class PinAF – Pin Alternate Functions A Pin represents a physical pin on the microcprocessor. Each pin can have
a variety of functions (GPIO, I2C SDA, etc). Each PinAF object represents a particular function for a pin.
Usage Model:
x3 = pyb.Pin.board.X3
x3_af = x3.af_list()
x3_af will now contain an array of PinAF objects which are availble on pin X3.
For the pyboard, x3_af would contain: [Pin.AF1_TIM2, Pin.AF2_TIM5, Pin.AF3_TIM9, Pin.AF7_USART2]
Normally, each peripheral would configure the af automatically, but sometimes the same function is available on
multiple pins, and having more control is desired.
To configure X3 to expose TIM2_CH3, you could use:
pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=pyb.Pin.AF1_TIM2)
or:
pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=1)
Methods
pinaf.__str__()
Return a string describing the alternate function.
pinaf.index()
Return the alternate function index.
pinaf.name()
Return the name of the alternate function.
pinaf.reg()
Return the base register associated with the peripheral assigned to this alternate function. For example, if the
alternate function were TIM2_CH3 this would return stm.TIM2
class RTC – real time clock The RTC is and independent clock that keeps track of the date and time.
Example usage:
rtc = pyb.RTC()
rtc.datetime((2014, 5, 1, 4, 13, 0, 0, 0))
print(rtc.datetime())
Constructors
class pyb.RTC
Create an RTC object.
Methods
rtc.datetime([datetimetuple ])
Get or set the date and time of the RTC.
With no arguments, this method returns an 8-tuple with the current date and time. With 1 argument (being an
8-tuple) it sets the date and time.
The 8-tuple has the following format:
(year, month, day, weekday, hours, minutes, seconds, subseconds)
weekday is 1-7 for Monday through Sunday.
subseconds counts down from 255 to 0
rtc.info()
Get information about the startup time and reset source.
•The lower 0xffff are the number of milliseconds the RTC took to start up.
•Bit 0x10000 is set if a power-on reset occurred.
•Bit 0x20000 is set if an external reset occurred
class Servo – 3-wire hobby servo driver Servo objects control standard hobby servo motors with 3-wires (ground,
power, signal). There are 4 positions on the pyboard where these motors can be plugged in: pins X1 through X4 are
the signal pins, and next to them are 4 sets of power and ground pins.
Example usage:
import pyb
Note: The Servo objects use Timer(5) to produce the PWM output. You can use Timer(5) for Servo control, or your
own purposes, but not both at the same time.
Constructors
class pyb.Servo(id)
Create a servo object. id is 1-4, and corresponds to pins X1 through X4.
Methods
servo.angle([angle, time=0 ])
If no arguments are given, this function returns the current angle.
If arguments are given, this function sets the angle of the servo:
•angle is the angle to move to in degrees.
•time is the number of milliseconds to take to get to the specified angle. If omitted, then the servo moves
as quickly as possible to its new position.
servo.speed([speed, time=0 ])
If no arguments are given, this function returns the current speed.
If arguments are given, this function sets the speed of the servo:
•speed is the speed to change to, between -100 and 100.
•time is the number of milliseconds to take to get to the specified speed. If omitted, then the servo
accelerates as quickly as possible.
servo.pulse_width([value ])
If no arguments are given, this function returns the current raw pulse-width value.
If an argument is given, this function sets the raw pulse-width value.
servo.calibration([pulse_min, pulse_max, pulse_centre[, pulse_angle_90, pulse_speed_100 ]])
If no arguments are given, this function returns the current calibration data, as a 5-tuple.
If arguments are given, this function sets the timing calibration:
•pulse_min is the minimum allowed pulse width.
•pulse_max is the maximum allowed pulse width.
•pulse_centre is the pulse width corresponding to the centre/zero position.
•pulse_angle_90 is the pulse width corresponding to 90 degrees.
•pulse_speed_100 is the pulse width corresponding to a speed of 100.
class SPI – a master-driven serial protocol SPI is a serial protocol that is driven by a master. At the physical level
there are 3 lines: SCK, MOSI, MISO.
See usage model of I2C; SPI is very similar. Main difference is parameters to init the SPI bus:
from pyb import SPI
spi = SPI(1, SPI.MASTER, baudrate=600000, polarity=1, phase=0, crc=0x7)
Only required parameter is mode, SPI.MASTER or SPI.SLAVE. Polarity can be 0 or 1, and is the level the idle clock
line sits at. Phase can be 0 or 1 to sample data on the first or second clock edge respectively. Crc can be None for no
CRC, or a polynomial specifier.
Additional method for SPI:
data = spi.send_recv(b’1234’) # send 4 bytes and receive 4 bytes
buf = bytearray(4)
spi.send_recv(b’1234’, buf) # send 4 bytes and receive 4 into buf
spi.send_recv(buf, buf) # send/recv 4 bytes from/to buf
Constructors
class pyb.SPI(bus, ...)
Construct an SPI object on the given bus. bus can be 1 or 2. With no additional parameters, the SPI object is
created but not initialised (it has the settings from the last initialisation of the bus, if any). If extra arguments are
given, the bus is initialised. See init for parameters of initialisation.
The physical pins of the SPI busses are:
•SPI(1) is on the X position: (NSS, SCK, MISO, MOSI) = (X5, X6, X7, X8) = (PA4,
PA5, PA6, PA7)
•SPI(2) is on the Y position: (NSS, SCK, MISO, MOSI) = (Y5, Y6, Y7, Y8) = (PB12,
PB13, PB14, PB15)
At the moment, the NSS pin is not used by the SPI driver and is free for other use.
Methods
spi.deinit()
Turn off the SPI bus.
spi.init(mode, baudrate=328125, *, prescaler, polarity=1, phase=0, bits=8, firstbit=SPI.MSB, ti=False,
crc=None)
Initialise the SPI bus with the given parameters:
•mode must be either SPI.MASTER or SPI.SLAVE.
•baudrate is the SCK clock rate (only sensible for a master).
•prescaler is the prescaler to use to derive SCK from the APB bus frequency; use of prescaler
overrides baudrate.
•polarity can be 0 or 1, and is the level the idle clock line sits at.
•phase can be 0 or 1 to sample data on the first or second clock edge respectively.
•firstbit can be SPI.MSB or SPI.LSB.
•crc can be None for no CRC, or a polynomial specifier.
Note that the SPI clock frequency will not always be the requested baudrate. The hardware only supports
baudrates that are the APB bus frequency (see pyb.freq()) divided by a prescaler, which can be 2, 4, 8,
16, 32, 64, 128 or 256. SPI(1) is on AHB2, and SPI(2) is on AHB1. For precise control over the SPI clock
frequency, specify prescaler instead of baudrate.
Printing the SPI object will show you the computed baudrate and the chosen prescaler.
spi.recv(recv, *, timeout=5000)
Receive data on the bus:
•recv can be an integer, which is the number of bytes to receive, or a mutable buffer, which will be filled
with received bytes.
•timeout is the timeout in milliseconds to wait for the receive.
Return value: if recv is an integer then a new buffer of the bytes received, otherwise the same buffer that was
passed in to recv.
spi.send(send, *, timeout=5000)
Send data on the bus:
•send is the data to send (an integer to send, or a buffer object).
•timeout is the timeout in milliseconds to wait for the send.
Return value: None.
Constants
SPI.MASTER
SPI.SLAVE
for initialising the SPI bus to master or slave mode
SPI.LSB
SPI.MSB
set the first bit to be the least or most significant bit
class Switch – switch object A Switch object is used to control a push-button switch.
Usage:
sw = pyb.Switch() # create a switch object
sw() # get state (True if pressed, False otherwise)
sw.callback(f) # register a callback to be called when the
# switch is pressed down
sw.callback(None) # remove the callback
Example:
pyb.Switch().callback(lambda: pyb.LED(1).toggle())
Constructors
class pyb.Switch
Create and return a switch object.
Methods
switch()
Return the switch state: True if pressed down, False otherwise.
switch.callback(fun)
Register the given function to be called when the switch is pressed down. If fun is None, then it disables the
callback.
class Timer – control internal timers Timers can be used for a great variety of tasks. At the moment, only the
simplest case is implemented: that of calling a function periodically.
Each timer consists of a counter that counts up at a certain rate. The rate at which it counts is the peripheral clock
frequency (in Hz) divided by the timer prescaler. When the counter reaches the timer period it triggers an event, and
the counter resets back to zero. By using the callback method, the timer event can call a Python function.
Example usage to toggle an LED at a fixed frequency:
Further examples:
tim = pyb.Timer(4, freq=100) # freq in Hz
tim = pyb.Timer(4, prescaler=0, period=99)
tim.counter() # get counter (can also set)
tim.prescaler(2) # set prescaler (can also get)
tim.period(199) # set period (can also get)
tim.callback(lambda t: ...) # set callback for update interrupt (t=tim instance)
tim.callback(None) # clear callback
Note: Timer 3 is reserved for internal use. Timer 5 controls the servo driver, and Timer 6 is used for timed ADC/DAC
reading/writing. It is recommended to use the other timers in your programs.
Constructors
class pyb.Timer(id, ...)
Construct a new timer object of the given id. If additional arguments are given, then the timer is initialised by
init(...). id can be 1 to 14, excluding 3.
Methods
timer.callback(fun)
Set the function to be called when the timer triggers. fun is passed 1 argument, the timer object. If fun is
None then the callback will be disabled.
timer.channel(channel, mode, ...)
If only a channel number is passed, then a previously initialized channel object is returned (or None if there is
no previous channel).
Othwerwise, a TimerChannel object is initialized and returned.
Each channel can be configured to perform pwm, output compare, or input capture. All channels share the same
underlying timer, which means that they share the same timer clock.
Keyword arguments:
•mode can be one of:
–Timer.PWM — configure the timer in PWM mode (active high).
–Timer.PWM_INVERTED — configure the timer in PWM mode (active low).
–Timer.OC_TIMING — indicates that no pin is driven.
–Timer.OC_ACTIVE — the pin will be made active when a compare match occurs (active is deter-
mined by polarity)
–Timer.OC_INACTIVE — the pin will be made inactive when a compare match occurs.
–Timer.OC_TOGGLE — the pin will be toggled when an compare match occurs.
–Timer.OC_FORCED_ACTIVE — the pin is forced active (compare match is ignored).
–Timer.OC_FORCED_INACTIVE — the pin is forced inactive (compare match is ignored).
–Timer.IC — configure the timer in Input Capture mode.
–Timer.ENC_A — configure the timer in Encoder mode. The counter only changes when CH1
changes.
–Timer.ENC_B — configure the timer in Encoder mode. The counter only changes when CH2
changes.
–Timer.ENC_AB — configure the timer in Encoder mode. The counter changes when CH1 or CH2
changes.
•callback - as per TimerChannel.callback()
•pin None (the default) or a Pin object. If specified (and not None) this will cause the alternate function
of the the indicated pin to be configured for this timer channel. An error will be raised if the pin doesn’t
support any alternate functions for this timer channel.
Keyword arguments for Timer.PWM modes:
•pulse_width - determines the initial pulse width value to use.
•pulse_width_percent - determines the initial pulse width percentage to use.
Keyword arguments for Timer.OC modes:
•compare - determines the initial value of the compare register.
•polarity can be one of:
–Timer.HIGH - output is active high
–Timer.LOW - output is acive low
Optional keyword arguments for Timer.IC modes:
•polarity can be one of:
–Timer.RISING - captures on rising edge.
–Timer.FALLING - captures on falling edge.
–Timer.BOTH - captures on both edges.
Note that capture only works on the primary channel, and not on the complimentary channels.
Notes for Timer.ENC modes:
•Requires 2 pins, so one or both pins will need to be configured to use the appropriate timer AF using the
Pin API.
•Read the encoder value using the timer.counter() method.
•Only works on CH1 and CH2 (and not on CH1N or CH2N)
•The channel number is ignored when setting the encoder mode.
PWM Example:
timer = pyb.Timer(2, freq=1000)
ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=8000)
ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=16000)
timer.counter([value ])
Get or set the timer counter.
timer.deinit()
Deinitialises the timer.
Disables the callback (and the associated irq). Disables any channel callbacks (and the associated irq). Stops
the timer, and disables the timer peripheral.
timer.freq([value ])
Get or set the frequency for the timer (changes prescaler and period if set).
Keyword arguments:
•freq — specifies the periodic frequency of the timer. You migh also view this as the frequency
with which the timer goes through one complete cycle.
•prescaler [0-0xffff] - specifies the value to be loaded into the timer’s Prescaler Register
(PSC). The timer clock source is divided by (prescaler + 1) to arrive at the timer clock.
Timers 2-7 and 12-14 have a clock source of 84 MHz (pyb.freq()[2] * 2), and Timers 1, and 8-11
have a clock source of 168 MHz (pyb.freq()[3] * 2).
•period [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5. Specifies the
value to be loaded into the timer’s AutoReload Register (ARR). This determines the period of
the timer (i.e. when the counter cycles). The timer counter will roll-over after period + 1
timer clock cycles.
•mode can be one of:
–Timer.UP - configures the timer to count from 0 to ARR (default)
–Timer.DOWN - configures the timer to count from ARR down to 0.
–Timer.CENTER - confgures the timer to count from 0 to ARR and then back down to 0.
•div can be one of 1, 2, or 4. Divides the timer clock to determine the sampling clock used by
the digital filters.
•callback - as per Timer.callback()
•deadtime - specifies the amount of “dead” or inactive time between transitions on compli-
mentary channels (both channels will be inactive) for this time). deadtime may be an integer
between 0 and 1008, with the following restrictions: 0-128 in steps of 1. 128-256 in steps of 2,
256-512 in steps of 8, and 512-1008 in steps of 16. deadime measures ticks of source_freq
divided by div clock ticks. deadtime is only available on timers 1 and 8.
You must either specify freq or both of period and prescaler.
timer.period([value ])
Get or set the period of the timer.
timer.prescaler([value ])
Get or set the prescaler for the timer.
timer.source_freq()
Get the frequency of the source of the timer.
class TimerChannel — setup a channel for a timer Timer channels are used to generate/capture a signal using a
timer.
TimerChannel objects are created using the Timer.channel() method.
Methods
timerchannel.callback(fun)
Set the function to be called when the timer channel triggers. fun is passed 1 argument, the timer object. If
fun is None then the callback will be disabled.
timerchannel.capture([value ])
Get or set the capture value associated with a channel. capture, compare, and pulse_width are all aliases for the
same function. capture is the logical name to use when the channel is in input capture mode.
timerchannel.compare([value ])
Get or set the compare value associated with a channel. capture, compare, and pulse_width are all aliases for
the same function. compare is the logical name to use when the channel is in output compare mode.
timerchannel.pulse_width([value ])
Get or set the pulse width value associated with a channel. capture, compare, and pulse_width are all aliases for
the same function. pulse_width is the logical name to use when the channel is in PWM mode.
In edge aligned mode, a pulse_width of period + 1 corresponds to a duty cycle of 100% In center aligned
mode, a pulse width of period corresponds to a duty cycle of 100%
timerchannel.pulse_width_percent([value ])
Get or set the pulse width percentage associated with a channel. The value is a number between 0 and 100 and
sets the percentage of the timer period for which the pulse is active. The value can be an integer or floating-point
number for more accuracy. For example, a value of 25 gives a duty cycle of 25%.
class UART – duplex serial communication bus UART implements the standard UART/USART duplex serial
communications protocol. At the physical level it consists of 2 lines: RX and TX. The unit of communication is a
character (not to be confused with a string character) which can be 8 or 9 bits wide.
UART objects can be created and initialised using:
from pyb import UART
Note: The stream functions read, write, etc. are new in Micro Python v1.3.4. Earlier versions use uart.send
and uart.recv.
Constructors
class pyb.UART(bus, ...)
Construct a UART object on the given bus. bus can be 1-6, or ‘XA’, ‘XB’, ‘YA’, or ‘YB’. With no additional
parameters, the UART object is created but not initialised (it has the settings from the last initialisation of the
bus, if any). If extra arguments are given, the bus is initialised. See init for parameters of initialisation.
The physical pins of the UART busses are:
•UART(4) is on XA: (TX, RX) = (X1, X2) = (PA0, PA1)
•UART(1) is on XB: (TX, RX) = (X9, X10) = (PB6, PB7)
•UART(6) is on YA: (TX, RX) = (Y1, Y2) = (PC6, PC7)
•UART(3) is on YB: (TX, RX) = (Y9, Y10) = (PB10, PB11)
•UART(2) is on: (TX, RX) = (X3, X4) = (PA2, PA3)
Methods
uart.init(baudrate, bits=8, parity=None, stop=1, *, timeout=1000, timeout_char=0, read_buf_len=64)
Initialise the UART bus with the given parameters:
•baudrate is the clock rate.
•bits is the number of bits per character, 7, 8 or 9.
•parity is the parity, None, 0 (even) or 1 (odd).
•stop is the number of stop bits, 1 or 2.
•timeout is the timeout in milliseconds to wait for the first character.
•timeout_char is the timeout in milliseconds to wait between characters.
•read_buf_len is the character length of the read buffer (0 to disable).
This method will raise an exception if the baudrate could not be set within 5% of the desired value. The minimum
baudrate is dictated by the frequency of the bus that the UART is on; UART(1) and UART(6) are APB2, the rest
are on APB1. The default bus frequencies give a minimum baudrate of 1300 for UART(1) and UART(6) and
650 for the others. Use pyb.freq to reduce the bus frequencies to get lower baudrates.
Note: with parity=None, only 8 and 9 bits are supported. With parity enabled, only 7 and 8 bits are supported.
uart.deinit()
Turn off the UART bus.
uart.any()
Return True if any characters waiting, else False.
uart.read([nbytes ])
Read characters. If nbytes is specified then read at most that many bytes.
Note: for 9 bit characters each character takes two bytes, nbytes must be even, and the number of characters
is nbytes/2.
Return value: a bytes object containing the bytes read in. Returns b’’ on timeout.
uart.readall()
Read as much data as possible.
Return value: a bytes object.
uart.readchar()
Receive a single character on the bus.
Return value: The character read, as an integer. Returns -1 on timeout.
uart.readinto(buf [, nbytes ])
Read bytes into the buf. If nbytes is specified then read at most that many bytes. Otherwise, read at most
len(buf) bytes.
Return value: number of bytes read and stored into buf.
uart.readline()
Read a line, ending in a newline character.
Return value: the line read.
uart.write(buf )
Write the buffer of bytes to the bus. If characters are 7 or 8 bits wide then each byte is one character. If characters
are 9 bits wide then two bytes are used for each character (little endian), and buf must contain an even number
of bytes.
Return value: number of bytes written.
uart.writechar(char)
Write a single character on the bus. char is an integer to write. Return value: None.
uart.sendbreak()
Send a break condition on the bus. This drives the bus low for a duration of 13 bits. Return value: None.
class USB_VCP – USB virtual comm port The USB_VCP class allows creation of an object representing the USB
virtual comm port. It can be used to read and write data over USB to the connected host.
Constructors
class pyb.USB_VCP
Create a new USB_VCP object.
Methods
usb_vcp.setinterrupt(chr)
Set the character which interrupts running Python code. This is set to 3 (CTRL-C) by default, and when a
CTRL-C character is received over the USB VCP port, a KeyboardInterrupt exception is raised.
Set to -1 to disable this interrupt feature. This is useful when you want to send raw bytes over the USB VCP
port.
usb_vcp.isconnected()
Return True if USB is connected as a serial device, else False.
usb_vcp.any()
Return True if any characters waiting, else False.
usb_vcp.close()
usb_vcp.read([nbytes ])
usb_vcp.readall()
usb_vcp.readline()
usb_vcp.recv(data, *, timeout=5000)
Receive data on the bus:
•data can be an integer, which is the number of bytes to receive, or a mutable buffer, which will be filled
with received bytes.
•timeout is the timeout in milliseconds to wait for the receive.
Return value: if data is an integer then a new buffer of the bytes received, otherwise the number of bytes read
into data is returned.
usb_vcp.send(data, *, timeout=5000)
Send data over the USB VCP:
•data is the data to send (an integer to send, or a buffer object).
•timeout is the timeout in milliseconds to wait for the send.
Return value: number of bytes sent.
usb_vcp.write(buf )
This module provides network drivers and routing configuration. Network drivers for specific hardware are available
within this module and are used to configure a hardware network interface. Configured interfaces are then available
for use via the socket module.
For example:
# configure a specific network interface
# see below for examples of specific drivers
import network
nic = network.Driver(...)
print(nic.ifconfig())
class CC3K
This class provides a driver for CC3000 wifi modules. Example usage:
import network
nic = network.CC3K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4, pyb.Pin.board.Y3)
nic.connect(’your-ssid’, ’your-password’)
while not nic.isconnected():
pyb.delay(50)
print(nic.ifconfig())
For this example to work the CC3000 module must have the following connections:
• MOSI connected to Y8
• MISO connected to Y7
• CLK connected to Y6
• CS connected to Y5
• VBEN connected to Y4
• IRQ connected to Y3
It is possible to use other SPI busses and other pins for CS, VBEN and IRQ.
Constructors
class network.CC3K(spi, pin_cs, pin_en, pin_irq)
Create a CC3K driver object, initialise the CC3000 module using the given SPI bus and pins, and return the
CC3K object.
Arguments are:
•spi is an SPI object which is the SPI bus that the CC3000 is connected to (the MOSI, MISO and CLK
pins).
•pin_cs is a Pin object which is connected to the CC3000 CS pin.
•pin_en is a Pin object which is connected to the CC3000 VBEN pin.
•pin_irq is a Pin object which is connected to the CC3000 IRQ pin.
All of these objects will be initialised by the driver, so there is no need to initialise them yourself. For example,
you can use:
nic = network.CC3K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4, pyb.Pin.board.Y3)
Methods
cc3k.connect(ssid, key=None, *, security=WPA2, bssid=None)
Connect to a wifi access point using the given SSID, and other security parameters.
cc3k.disconnect()
Disconnect from the wifi access point.
cc3k.isconnected()
Returns True if connected to a wifi access point and has a valid IP address, False otherwise.
cc3k.ifconfig()
Returns a 7-tuple with (ip, subnet mask, gateway, DNS server, DHCP server, MAC address, SSID).
cc3k.patch_version()
Return the version of the patch program (firmware) on the CC3000.
cc3k.patch_program(‘pgm’)
Upload the current firmware to the CC3000. You must pass ‘pgm’ as the first argument in order for the upload
to proceed.
Constants
CC3K.WEP
CC3K.WPA
CC3K.WPA2
security type to use
class WIZNET5K
This class allows you to control WIZnet5x00 Ethernet adaptors based on the W5200 and W5500 chipsets (only W5200
tested).
Example usage:
import network
nic = network.WIZNET5K(pyb.SPI(1), pyb.Pin.board.X5, pyb.Pin.board.X4)
print(nic.ifconfig())
For this example to work the WIZnet5x00 module must have the following connections:
• MOSI connected to X8
• MISO connected to X7
• SCLK connected to X6
• nSS connected to X5
• nRESET connected to X4
It is possible to use other SPI busses and other pins for nSS and nRESET.
Constructors
class network.WIZNET5K(spi, pin_cs, pin_rst)
Create a WIZNET5K driver object, initialise the WIZnet5x00 module using the given SPI bus and pins, and
return the WIZNET5K object.
Arguments are:
•spi is an SPI object which is the SPI bus that the WIZnet5x00 is connected to (the MOSI, MISO and
SCLK pins).
•pin_cs is a Pin object which is connected to the WIZnet5x00 nSS pin.
•pin_rst is a Pin object which is connected to the WIZnet5x00 nRESET pin.
All of these objects will be initialised by the driver, so there is no need to initialise them yourself. For example,
you can use:
nic = network.WIZNET5K(pyb.SPI(1), pyb.Pin.board.X5, pyb.Pin.board.X4)
Methods
wiznet5k.ifconfig([(ip, subnet, gateway, dns) ])
Get/set IP address, subnet mask, gateway and DNS.
When called with no arguments, this method returns a 4-tuple with the above information.
To set the above values, pass a 4-tuple with the required information. For example:
nic.ifconfig((’192.168.0.4’, ’255.255.255.0’, ’192.168.0.1’, ’8.8.8.8’))
wiznet5k.regs()
Dump the WIZnet5x00 registers. Useful for debugging.
• The LCD display on the LCD touch-sensor skin: Newhaven Display NHD-C12832A1Z-FSW-FBW-3V3
(460KiB PDF)
• The touch sensor chip on the LCD touch-sensor skin: Freescale MPR121 (280KiB PDF)
• The digital potentiometer on the audio skin: Microchip MCP4541 (2.7MiB PDF)
• genindex
• modindex
• search
161
Micro Python Documentation, Release 1.4
c
cmath, 118
g
gc, 119
m
math, 120
n
network, 157
o
os, 122
p
pyb, 130
s
select, 123
struct, 123
sys, 124
t
time, 124
u
ubinascii, 125
uctypes, 125
uhashlib, 127
uheapq, 128
ujson, 128
ure, 129
usocket, 130
uzlib, 130
163
Micro Python Documentation, Release 1.4
165
Micro Python Documentation, Release 1.4
F L
fabs() (in module math), 39, 120 ldexp() (in module math), 39, 121
fill() (lcd method), 61, 142 lgamma() (in module math), 39, 121
filtered_xyz() (accel method), 52, 133 light() (lcd method), 61, 142
floor() (in module math), 39, 120 line() (extint method), 58, 139
fmod() (in module math), 39, 120 listdir() (in module os), 41, 122
freq() (in module pyb), 50, 131 LITTLE_ENDIAN (in module uctypes), 45, 127
freq() (timer method), 71, 152 loads() (in module ujson), 47, 128
frexp() (in module math), 39, 121 localtime() (in module time), 43, 124
log() (in module cmath), 37, 119
G log() (in module math), 39, 121
gamma() (in module math), 39, 121 log10() (in module cmath), 37, 119
gc (module), 38, 119 log10() (in module math), 39, 121
get() (lcd method), 61, 142 log2() (in module math), 39, 121
getaddrinfo() (in module usocket), 48, 130 low() (pin method), 63, 145
getcwd() (in module os), 41, 122
gpio() (pin method), 64, 145 M
group() (ure.match method), 48, 129 mapper() (Pin method), 63, 144
match() (in module ure), 48, 129
H match() (ure.regex method), 48, 129
hard_reset() (in module pyb), 50, 131 math (module), 38, 120
have_cdc() (in module pyb), 51, 132 mem_alloc() (in module gc), 38, 119
heapify() (in module uheapq), 47, 128 mem_free() (in module gc), 38, 119
heappop() (in module uheapq), 47, 128 mem_read() (i2c method), 59, 140
heappush() (in module uheapq), 47, 128 mem_write() (i2c method), 59, 141
hexdigest() (uhashlib.sha256 method), 46, 128 micros() (in module pyb), 49, 130
hexlify() (in module ubinascii), 44, 125 millis() (in module pyb), 49, 130
hid() (in module pyb), 51, 132 mkdir() (in module os), 41, 122
high() (pin method), 63, 145 mktime() (in module time), 43, 125
mode() (pin method), 64, 145
166 Index
Micro Python Documentation, Release 1.4
modf() (in module math), 40, 121 pyb.ExtInt (built-in class), 57, 139
modify() (select.poll method), 42, 123 pyb.I2C (built-in class), 59, 140
mount() (in module pyb), 51, 132 pyb.LCD (built-in class), 61, 142
pyb.LED (built-in class), 62, 143
N pyb.Pin (built-in class), 63, 144
name() (pin method), 64, 145 pyb.RTC (built-in class), 65, 147
name() (pinaf method), 65, 146 pyb.Servo (built-in class), 66, 148
names() (pin method), 64, 145 pyb.SPI (built-in class), 67, 149
NATIVE (in module uctypes), 45, 127 pyb.Switch (built-in class), 69, 150
network (module), 76, 157 pyb.Timer (built-in class), 70, 151
noise() (dac method), 56, 138 pyb.UART (built-in class), 73, 154
pyb.USB_VCP (built-in class), 75, 156
O
off() (led method), 62, 143 R
on() (led method), 62, 143 radians() (in module math), 40, 121
os (module), 40, 122 read() (adc method), 53, 134
read() (uart method), 74, 155
P read() (usb_vcp method), 75, 156
pack() (in module struct), 42, 123 read_timed() (adc method), 53, 134
patch_program() (network.cc3k method), 77, 158 readall() (uart method), 74, 155
patch_version() (network.cc3k method), 77, 158 readall() (usb_vcp method), 75, 156
path (in module sys), 43, 124 readchar() (uart method), 74, 155
period() (timer method), 72, 153 readinto() (uart method), 74, 155
phase() (in module cmath), 37, 119 readline() (uart method), 75, 156
pi (in module cmath), 38, 119 readline() (usb_vcp method), 75, 156
pi (in module math), 40, 122 rect() (in module cmath), 37, 119
pin() (pin method), 64, 145 recv() (can method), 55, 136
Pin.AF_OD (built-in variable), 64, 145 recv() (i2c method), 60, 141
Pin.AF_PP (built-in variable), 64, 145 recv() (spi method), 68, 149
Pin.ANALOG (built-in variable), 64, 145 recv() (usb_vcp method), 75, 156
Pin.IN (built-in variable), 64, 146 reg() (pinaf method), 65, 146
Pin.OUT_OD (built-in variable), 64, 146 register() (select.poll method), 42, 123
Pin.OUT_PP (built-in variable), 64, 146 regs() (ExtInt method), 57, 139
Pin.PULL_DOWN (built-in variable), 64, 146 regs() (network.wiznet5k method), 78, 159
Pin.PULL_NONE (built-in variable), 64, 146 remove() (in module os), 41, 122
Pin.PULL_UP (built-in variable), 64, 146 repl_uart() (in module pyb), 51, 133
pixel() (lcd method), 61, 142 rmdir() (in module os), 41, 122
platform (in module sys), 43, 124 rng() (in module pyb), 51, 133
polar() (in module cmath), 37, 119 rxcallback() (can method), 55, 136
poll() (in module select), 41, 123
poll() (select.poll method), 42, 123 S
port() (pin method), 64, 145 scan() (i2c method), 60, 141
pow() (in module math), 40, 121 search() (in module ure), 48, 129
prescaler() (timer method), 72, 153 search() (ure.regex method), 48, 129
print_exception() (in module sys), 42, 124 select (module), 41, 123
pull() (pin method), 64, 145 select() (in module select), 41, 123
pulse_width() (servo method), 67, 148 send() (can method), 55, 136
pulse_width() (timerchannel method), 73, 154 send() (i2c method), 60, 141
pulse_width_percent() (timerchannel method), 73, 154 send() (spi method), 68, 149
pyb (module), 49, 130 send() (usb_vcp method), 76, 157
pyb.Accel (built-in class), 52, 133 send_recv() (spi method), 68, 149
pyb.ADC (built-in class), 53, 134 sendbreak() (uart method), 75, 156
pyb.CAN (built-in class), 53, 135 sep (in module os), 41, 122
pyb.DAC (built-in class), 56, 137 setfilter() (can method), 54, 135
Index 167
Micro Python Documentation, Release 1.4
setinterrupt() (usb_vcp method), 75, 156 urandom() (in module os), 41, 122
show() (lcd method), 61, 143 ure (module), 47, 129
sin() (in module cmath), 37, 119 usocket (module), 48, 130
sin() (in module math), 40, 121 uzlib (module), 48, 130
sinh() (in module math), 40, 121
sizeof() (in module uctypes), 45, 127 V
sleep() (in module time), 43, 125 value() (pin method), 63, 145
socket() (in module usocket), 48, 130 version (in module sys), 43, 124
source_freq() (timer method), 72, 153 version_info (in module sys), 43, 124
speed() (servo method), 67, 148
SPI.LSB (built-in variable), 69, 150 W
SPI.MASTER (built-in variable), 69, 150 wfi() (in module pyb), 50, 132
SPI.MSB (built-in variable), 69, 150 WIZNET5K (class in network), 78, 159
SPI.SLAVE (built-in variable), 69, 150 write() (dac method), 56, 138
split() (ure.regex method), 48, 129 write() (lcd method), 61, 143
sqrt() (in module cmath), 37, 119 write() (uart method), 75, 156
sqrt() (in module math), 40, 121 write() (usb_vcp method), 76, 157
standby() (in module pyb), 50, 132 write_timed() (dac method), 56, 138
stat() (in module os), 41, 122 writechar() (uart method), 75, 156
stderr (in module sys), 43, 124
stdin (in module sys), 43, 124 X
stdout (in module sys), 43, 124
x() (accel method), 52, 133
stop() (in module pyb), 51, 132
struct (class in uctypes), 45, 127
struct (module), 42, 123
Y
swint() (extint method), 58, 139 y() (accel method), 52, 133
switch(), 69, 150
sync() (in module os), 41, 122 Z
sync() (in module pyb), 51, 133 z() (accel method), 52, 134
sys (module), 42, 124
T
tan() (in module math), 40, 121
tanh() (in module math), 40, 121
text() (lcd method), 61, 143
tilt() (accel method), 52, 133
time (module), 43, 124
time() (in module time), 43, 125
toggle() (led method), 62, 143
triangle() (dac method), 56, 138
trunc() (in module math), 40, 121
U
ubinascii (module), 44, 125
uctypes (module), 44, 125
udelay() (in module pyb), 49, 130
uhashlib (module), 46, 127
uhashlib.sha256 (class in uhashlib), 46, 128
uheapq (module), 47, 128
ujson (module), 47, 128
unique_id() (in module pyb), 51, 133
unpack() (in module struct), 42, 123
unregister() (select.poll method), 42, 123
update() (uhashlib.sha256 method), 46, 128
168 Index