MicroPython.présentation

De MCHobby - Wiki
Révision datée du 24 janvier 2015 à 16:37 par Admin (discussion | contributions) (Page créée avec « == Introduction == {{bloc-etroit|text= '''MicroPython''' est une version rapide, optimisée et allégée du langage de programmation Python 3 ([http://python.org Python.org]... »)
(diff) ← Version précédente | Voir la version actuelle (diff) | Version suivante → (diff)
Sauter à la navigation Sauter à la recherche

Introduction

MicroPython est une version rapide, optimisée et allégée du langage de programmation Python 3 (Python.org) pour système embarqué.

La carte MicroPython est une petite carte électronique qui exécute MicroPython en bare metal et vous offre un système d'exploitation Python bas niveau permettant de contrôler toute sorte de projets électroniques.

Grâce au lancement de [ttps://www.kickstarter.com/projects/214379695/micro-python-python-for-microcontrollers MicroPython en KickStarter], il a été possible de concevoir la carte en y incluant:

  • Le support de connexion Wi-Fi à l'aide du module CC3000. Micro Python incluera une bibliothèque permettant vous permettant de vous connecter via Wi-Fi. Il est donc possible d'ajouter un module CC3000. Ce module se connecte via les broches du bus SPI sur la carte Micro Python.
  • Le support Ethernet à l'aide d'un module WIZ820io module. Similaire au module CC3000, le module WIZ820io se branche également sur la carte micro Python via le module le bus SPI et une bibliothèque développée dans ce but.
  • Le support de communication sans-fil basse consommation avec le NRF24L01+ (et une bibliothèque adéquate).

MicroPython est un projet logiciel open-source (sous licence MIT) que vous pouvez utiliser dans vos propres projets.

Python is a scripting language that is very easy to learn, yet highly expressive and very powerful, and has a huge existing community. Running on a small microcontroller, Micro Python allows you to effortlessly blink LEDs, read voltages, make motors and servos move, play sounds, write data to SD cards, communicate wirelessly, and be the brains of your robot, among countless other things. It is the perfect choice to control your next project!

When building an electronics project, like an intruder detector or a smart robot, a microcontroller is used as the "brain", and does all the decision making and control. There are two kinds of things that a microcontroller typically needs to do. It must do low-level control of lights, LCD displays, motors, etc, as well as high-level tasks such as reading and writing data and images, communicating wirelessly, and being an artificial intelligence. Micro Python allows you to do both low-level and high-level control, by augmenting the Python language with inline assembler and native types, as described below.

Comment l'utiliser?

The Micro Python board comes preinstalled with Micro Python and is suitable for everyone, whether a beginner or an expert robot builder. It requires no set-up, no compiling and no soldering, and if you don't know Python it is very easy to learn the language.

You plug the board into your PC (Windows, Mac and Linux all work) using a USB cable. It then acts just like a USB flash drive.

To control servo motors, it is a simple as writing the following code:

pyb.servo(1, 45) # mettre le servo 1 a 45 degres
pyb.servo(2, 90) # set servo 2 a 90 degres

Put this code in a text file and copy it to the Micro Python USB flash drive, press the reset button on the board and it will run! You can also open a terminal emulator (freely available for Windows, Mac and Linux) to connect to the board over USB and type these commands directly to the board (which gives you a Python command line), and it will run them as soon as you press the enter key.

To flash an LED once a second, you could use the following code:

while True:  # Faire une boucle infinie
     pyb.led( True )  # allumer la LED
     pyb.delay(1000)  # Attendre 1000 millisecondes (1 seconde)
     pyb.led( False ) # eteindre la LED
     pyb.delay(1000)

To read the accelerometer and print out the x-axis value:

accel = pyb.mma() # obtenir les donnees de l accelerometre
print( accel[0] ) # afficher la donnee de l axe-X

You have the full Python programming language at your disposal, and can write functions and classes, make lists and dictionaries, do string processing, read and write files (to the SD card or built-in flash storage), and have more sophisticated features such as generators, closures, list comprehension and exception handling. The possibilities for programming are endless!


The board has many input/output pins which can be connected to other circuits, and you can solder on wires to make it part of your own project. The board can run without a PC, as long as it is connected to a battery or other power supply between 3.6V and 10V.


Some of the rewards on offer include a kit of parts with the Micro Python board. These kits allow you to get started programming and building things straight away. There will be a set of online instructions explaining exactly how to get it all working, and detailing some example projects. Even with just the Micro Python board on its own you can still do some pretty nifty things, such as logging accelerometer data, making a Python USB mouse, and using the USB serial Python command line. These projects will also be explained online for you to follow.


You may be wondering how the Micro Python board compares with other, similar boards. Compared with an Arduino, the Micro Python board is more powerful, easier to program, and you don't need a compiler on your PC. Compared with a Raspberry Pi, the Micro Python board is cheaper, smaller, simpler (you can make one yourself, or even modify the design to fit your needs) and it uses less power. Most other boards are programmed in C, which is a low-level language and can be difficult to program correctly. On the other hand, Python is a very high-level language, which means that Python has simpler, smaller code to do the same thing as C.

Logiciel MicroPython

Certainly! Micro Python is a complete rewrite, from scratch, of the Python scripting language. It is written in clean, ANSI C and includes a complete parser, compiler, virtual machine, runtime system, garbage collector and support libraries to run on a microcontroller. The compiler can compile to byte code or native machine code, selectable per function using a function decorator. It also supports inline assembler. All compilation happens on the chip, so there is no need for any software on your PC.

Micro Python currently supports 32-bit ARM processors with the Thumb v2 instruction set, such as the Cortex-M range used in low-cost microcontrollers. It has been tested on an STM32F405 chip.

Micro Python has the following features:

  • Full implementation of the Python 3 grammar (but not yet all of Python's standard libraries).
  • Implements a lexer, parser, compiler, virtual machine and runtime.
  • Can execute files, and also has a command line interface (a read-evaluate-print-loop, or REPL).
  • Python code is compiled to a compressed byte code that runs on the built-in virtual machine.
  • Memory usage is minimised by storing objects in efficient ways. Integers that fit in 31-bits do not allocate an object on the heap, and so require memory only on the stack.
  • Using Python decorators, functions can be optionally compiled to native machine code, which takes more memory but runs around 2 times faster than byte code. Such functions still implement the complete Python language.
  • A function can also be optionally compiled to use native machine integers as numbers, instead of Python objects. Such code runs at close to the speed of an equivalent C function, and can still be called from Python, and can still call Python. These functions can be used to perform time-critical procedures, such as interrupts.
  • An implementation of inline assembler allows complete access to the underlying machine. Inline assembler functions can be called from Python as though they were a normal function.
  • Memory is managed using a simple and fast mark-sweep garbage collector. It takes less than 4ms to perform a full collection. A lot of functions can be written to use no heap memory at all and therefore require no garbage collection.

La carte MicroPython (sous le capot)

The Micro Python board is an electronics development board that runs Micro Python, and is based on the STM32F405 microcontroller. This microcontroller is one of the more powerful ones available, and was chosen so that Micro Python could run at its full potential. The microcontroller is clocked at 168MHz and has 1MiB flash and 192KiB RAM, which is plenty for writing complex Python scripts. The board measures 33x40 mm and is pictured below.

{{{2}}}
Crédit: MicroPython micropython.org

The board has a built-in USB interface that presents itself as a serial device (CDC VCP) as well as a removable storage device (MSC). When connected to a PC, you can open a serial communications program and interact with the board through a Python command line. You can also print messages and read input, since the serial device acts like stdin and stdout. The board also acts as a storage device (a USB flash drive) and you can easily copy your Python scripts to the board's local filesystem or SD card, and they are then executed independent of the PC.


Powered by a battery, the board can compile and execute Python scripts without any PC connection. There is a Micro SD slot for storing large amounts of data, 2 LEDs, a switch, a real-time clock, an accelerometer, and 30 general purpose I/O pins. The I/O pins include: 5 USARTs, 2SPIs, 2 I2C busses, 14 ADC pins, 2 DAC pins, and 4 servo ports with power.


There is a special pin, BOOT0, which is used to reprogram the microcontroller. By connecting the BOOT0 pin to the 3.3V pin next to it, and resetting the board with the reset button, you enter the "device firmware upgrade" mode. This is a standard USB mode and allows you to easily put an updated version of Micro Python onto the microcontroller (using freely available software for Windows, Mac and Linux). It also allows you to download your own version of Micro Python if you want to modify it, or even download your own C program.


The Micro Python board is suitable for everyone, regardless of knowledge in hardware or software. With a few lines of Python code in a text file, anyone can start flashing LEDs and responding to accelerometer input, all without soldering, or connecting components, or installing software on your PC.

Pour les friands de détails

The Micro Python implementation is a complete rewrite of Python specifically designed to be run on a microcontroller with minimal flash storage and minimal RAM. When design decisions were made, the first priority was to minimise RAM usage, then minimise code size, and, finally, to execute quickly. Some of the important features of the implementation are listed below.

  • Follows the Python 3.3 grammar and language semantics. This means that Micro Python produces equivalent byte code (up to optimisations) to the official CPython version 3.3.
  • Size of space-optimised binary compiled to Thumb v2 machine code: around 60KiB. This includes the parser, compiler, runtime and garbage collector, but excludes all other code, including file system support and libraries related to the specific microcontroller. This size will increase if more Python libraries are added.
  • Size of all code, including FAT support, SD card, USB serial, USB mass storage, USB HID, Bluetooth, LCD, servo, timer: about 110KiB.
  • Minimum RAM required to compile and execute "print('hello world')": around 4KiB.
  • Memory is managed using a fast, non-precise, mark-sweep garbage collector. This eliminates reference counting overhead in flash code size and object RAM size. A fast CPU and small amount of RAM means that a complete garbage collection takes under 4ms. The garbage collector RAM overhead is 2 bits per 32 bytes = 1KiB for 128KiB usable RAM.
  • Size of int object: 4 bytes, stored on the stack or directly in a tuple/list/dictionary.
  • Size of other objects: 32 bytes, plus extra for, eg, elements of a list.
  • Limit on number of objects: none, so long as there is enough RAM.
  • The grammar is encoded in a compact table using EBNF which is interpreted on-the-fly when parsing.
  • RAM is minimised during compilation by performing 3 separate passes over the same data structure.
  • There are 4 types of code emitters, selectable per function by function decorators: (compressed) byte code, native code, native code with native types, and inline assembler. Byte code runs on a virtual machine, similar to CPython. Native code has each byte code unrolled to its equivalent machine code, and supports the full Python language. It takes about 2-3 times more RAM, but runs about 2-3 times faster than byte code. The third type, native code with native types, has byte code unrolled to machine code and further assumes that integers are smaller than 31 bits, so that it can use a single machine instruction for integer and pointer operations. You can think of it as "Python syntax, C semantics". For tight loops that perform arithmetic and bit manipulation (common on a microcontroller), it can perform close to the speed of the equivalent C program. The fourth code emitter is inline assembler. It uses the Python grammar, but is interpreted as a list of machine code instructions. Inline assembler can be called from normal Python code with integer and pointer arguments.
  • Python exceptions are handled using a variant of setjmp/longjmp. This reduces the amount of flash and RAM needed to implement exceptions.
  • A function (byte code, native or inline assembler) can be called on an interrupt long as it does not allocate heap memory (since it can be called while a garbage collection is taking place). In practice this is not a big restriction, as you can do a lot of things using only memory on the stack. For example, you can make loops with while/for, do integer arithmetic and bitwise operations (but no bignums), call other functions and access and overwrite elements of collections like bytearrays (but not create new ones).

The Micro Python language can also run on a PC (it was developed under Linux on a 64-bit machine) and can be used as a lean version of Python where low memory usage is important. The PC version of Micro Python (compiling to byte code) actually runs faster than CPython for the various benchmarks I have tested, and the native compilation option makes Micro Python run significantly faster than CPython.


You can think of Micro Python as a "mini Python operating system", and the boot-up process proceeds as follows:

  • Power on, or hard reset. If the DFU (device firmware upgrade) header is enabled (across BOOT0 and 3.3V pin) then the device enters DFU mode, allowing you to upgrade the Micro Python binary, or download your own C/C++ program.
  • Otherwise, it goes into boot mode and the boot-LED turns on.
  • Checks for a local filesystem on the flash. If none exists, or it is corrupt, a fresh one is created.
  • Checks for /boot.py. If it doesn't exist, a fresh one is created.
  • Runs /boot.py to configure USB and other low-level parameters that can't be changed without a reset.
  • Sets up USB interfaces, depending on the configuration in boot.py. The default is a CDC VCP (virtual communications port, to redirect stdio) and an MSD (mass storage device for the flash and SD card). The MSD allows Linux/Mac/Windows to access the flash and SD card filesystem just like a USB flash drive. This way you can easily copy Python scripts to the board, and copy data files back.
  • Boot-up finishes successfully and the boot-LED turns off.
  • The main Python script is run if it exists. Default is /src/main.py. This is your main Python program and it can do whatever you like!
  • If the main script doesn't exist, or exits, REPL (read-evaluate-print-loop) mode is entered. This gives you a standard Python interpreter prompt over the USB serial device. Exiting from this will soft-reset the board.