Programming the Pyboard in the Thonny IDE
Contents
What is MicroPython?
From the official website, micropython.org, we learn MicroPython is a lean and efficient implementation of the Python 3 programming language that includes a small subset of the Python standard library and is optimised to run on microcontrollers and in constrained environments.
It also includes MicroPython specific modules that allow direct access to hardware and peripherals commonly found on microcontrollers.
The MicroPython system is flashed to the microcontroller's flash memory. It runs "bare metal" i.e. does not require an underlying operating system. It consists of a core runtime which includes an interpreter and a runtime VM (virtual machine).
MicroPython source code scripts are flashed to the microcontroller. When the microcontroller is reset the interpreter converts the MicroPython source code into an intermediate format called bytecode. This bytecode is then executed by the VM.
What is Thonny?
MicroPython exists entirely on the microcontroller. It does not provide the tools to write the source code and flash it to the microcontroller's memory. Thus a separate specialist IDE (or toolchain) running on a computer is required.
Thonny provides this, all in one simple to use package. With respect to microcontrollers, Thonny is specifically for the development and deployment of MicroPython programs. It cannot be used to program a microcontroller with other languages eg. C or C++.
Installing Thonny
Thonny is easy to install. It's available for Windows, Mac and Linux. This article; Installing & Configuring the Thonny IDE; gives full instructions on:
- How to install Thonny on Windows and Linux computers.
- Connecting Thonny to the Pyboard.
- Configuring the application interface.
- Using the application toolbar
Writing and Running a MicroPython Script
Enter (or copy) the following MicroPython program into the Thonny Editor pane:
# Returns the sum of a series of sequential integers:
# 1, 2, ..., limit
def sum(limit):
sum = 0
for i in range(1, limit + 1):
sum += i
return sum
# Sum the first 100,000 integers
count = 100000
print('Sum of first', count, 'integers:', sum(count))
Click the Run current script button on the toolbar. The following should appear in the REPL:
>>> %Run -c $EDITOR_CONTENT
MPY: sync filesystems
MPY: soft reboot
Sum of first 100000 integers: 5000050000
>>>