MicroPython.présentation

De MCHobby - Wiki
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é.

PyBoard, 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 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 est une langage de scripting vraiment très facile à apprendre, très expressif, vraiment très puissant et disposant d'une gigantesque communauté. En fonctionnant sur un microcontroleur, MicroPython permet de faire clignoter des LEDs sans aucun effort, lire des tensions, faire bouger des moteurs et servo moteurs, jouer du son, écrire/lire des données sur la carte micro SD, établir des communications sans fils (avec un module complémentaire) et devenir ce cerveau que votre robot attend désespérément. Il y a tant d'autres d'opportunité accessible à PyBoard et MicroPyhton.... c'est un choix parfait pour votre prochain projet!

Lors de la conception d'un projet électronique, tel qu'un détecteur d'intrusion or a robot intelligent, le microcontroleur est utilisé en tant que "cerveau" et prend toutes les décisions d'action et de vérifications. Un microcontroleur a typiquement besoin de faire deux choses: (1) il doit être capable d'agir au niveau matériel (dit "low level") pour commander des lumières, écran LCD, moteurs, être très réactif, etc, (2) ainsi que des opération de haut niveau (dit "high level") comme comme lire et écrire des données, images, communiquer sans fil ou disposer d'une "intelligence artificiel".

Micro Python à ceci d'extraordinaire qu'il permet le contrôle low-level et high-level en agrémentant le language Python avec de l'assembleur inline et des types natifs (comme présenté ci-dessous).

Comment l'utiliser?

La carte Micro Python est flashée (pré-installée) avec Micro Python pour le rendre instantanément accessible aussi bien au néophyte, au débutant, développeur curieux, maker qu'à l'expert, ingénieur ou roboticien. La carte ne requière aucune installation/configuration, pas de compilateur, pas de soudure et si vous ne connaissez pas Python vous le découvrirez qu'il est très facile à apprendre.

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.

PyBoard, la carte MicroPython

La carte Micro Python (PyBoard pour les intimes) est une carte de développement électronique basée sur un microcontroleur STM32F405 qui exécute Micro Python. Ce microcontroleur est un des plus puissant disponible sur le marché et à été spécialement sélectionné parce qu'il permettrait à Micro Python de fonctionner à son plein potentiel.

Le microcontroleur est cadencé à 168MHz (fréquence d'horloge), dispose de 1Mb de Flash et de 192Kb de RAM, un très large espace mémoire pour écrire de complexes scripts Python. La carte mesure 33x40 mm comme présenté sur l'image ci-dessous.

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

La carte intègre une interface USB qui se présente comme un périphérique série (CDC VCP) ainsi que comme un périphérique de stockage USB amovible (MSC, l'équivalent de votre clé USB). Lorsque PyBoard est connecté sur un PC, vous pouvez ouvrir un programme de communication série (terminal telnet/minicom ou Putty) et interagir la carte par l'intermédiaire d'une ligne de commande Python. Vous pouvez également afficher des message (fonction print) et saisir des entrées puisque le périphérique série agit en tant que stdin et stdout (entrée et sortie console, standard simple hérité du monde Unix). La carte se comporte également comme un périphérique de stockage (un lecteur Flash USB) vous permettant de facilement copier vos scripts sur le système de fichier de la carte ou de la carte SD. Ces fichiers peuvent être exécutés indépendamment du PC.


Alimenté par une pile/accu, la carte est capable de compiler et exécuter des scripts Python sans besoin d'une connexion PC. Il y a un connecteur carte Micro SD pour stocker de grandes quantités de donnée, 4 LEDs, des boutons poussoirs, une horloge temps réel, un accéléromètre et 30 broches d'entrée/sortie (dite GPIO ou 'I/O'. Les broche d'I/O inclus: 5 USART (pour Port Série), 2 bus SPI, 2 bus I2C, 14 broches ADC (convertisseur Analogique->digital), 2 broches DAC (convertisseur Digital->Analogique) ainsi que 4 port pour Servo Moteurs (avec alimentation).


Il y a une broche spéciale BOOT0, qui est utilisée pour reprogrammer le microcontroleur. En connectant BOOT0 sur 3.3V (la broche juste à côté) et en réinitialisant (reset) la carte, vous placez la carte en mode DFU "device firmware upgrade". C'est le mode USB standard qui vous permet de faire une mise-à-jour de Micro Python sur le microcontroleur en utilisant des logiciel librement disponible pour Windows, Mac et Linux). Elle vous permet également de téléverser votre propre version de Micro Python si vous désirez la modifier, voire téléverser vos propres programmes écrit directement en C.


La carte Micro Python est adapté pour tous, peu importe le niveau de connaissance en programmation ou éléectronique. Avec quelques lignes de code Python dans un fichier texte, le bédutant pourra faire clignoter les LEDs et réagir en fonction des données de l'accéléromètre, le tout sans soudure, ni connexion de composant, ni installation de logiciel sur votre l'ordinateur.


PyBoard c'est de nombreuses broches aux fonctionnalités multiples. Avec PyBoard vous avez sous la main:

  • 30 GPIO - Broches d'entrées/sorties pouvant servir à de nombreuses applications. Avec un GPIO, vous pouvez commander des LEDs, des relais (via transistor ou UNL2803), des moteurs (via L293). Lire l'état de boutons et senseurs. Commander des périphériques tels que des écrans LCD, afficheurs graphiques, des cartes d'extension, etc.
  • 2 bus I2C - Pour commander des périphériques à l'aide de 3 fils.
  • 5 UARTs - Un port série c'est un outil de communication très utile... en avoir 5 c'est absolument génial.
  • 20 PWMs - Permettant de produire des signaux permettant de contrôler des servo-moteurs ou la puissance d'une LED (voyez "[AdaFruit_PWM_Driver#C.27est_quoi_PWM c'est quoi PWM]" dans cet autre tutoriel)
  • 16 ADC - Convertisseur Analogique->Digital permettant de lire une tension analogie (pratique pour utiliser des senseurs flex, photo-résistance, potentiomètre, etc).
  • 2 DAC - Très rares sur les cartes de prototypages, les convertisseurs Digital->Analogique permettent de produire des tensions analogiques en sortie. Grâce à cela, vous pouvez produire divers types de signaux (en dent de scie, sinusoide, ... et même du son).
  • 13 timers - Les timers permettent de mesurer des durées et d'exécuter du code/fonction à intervalle régulier. C'est un élément de synchronisation important lorsque l'on désire écrire des applications avancées.
  • 16 ext int - Les interruptions externes permettent d'interrompre le programme principal pour exécuter du code (fonction d’interruption) lorsqu'une broche change d'état. Cela permet d'écrire des programmes réagissant instantanément à changement de conditions physique autour du la carte. Exemple: arrêter immédiatement des moteurs si l'arrêt d'urgence est activé.
  • 1 RTC - L'horloge temps réel vous permet de connaître l'heure, de mesurer des laps de temps assez grand, de créer des exécutions basées sur un calendrier, de réaliser des horloges. Le RTC est un élément utile qui manque souvent dans les plateformes de prototypage (comme c'est la cas pour Raspberry, Arduino ou encore de Spark Core où le RTC n'est pas exploitée)
  • 4 LEDs - Les LEDs/DELs sont bien pratiques pour informer l'utilisateur sur l'état du programme. En avoir sur la carte permet de tester/prototyper rapidement du code sans avoir besoin de faire des raccordements.
  • 1 Accéléromètre - PyBoard fut conçue avec la robotique comme finalité. Du coup, Damien à intégrer un accéléromètre à même la carte. Un tel dispositif permet de mesurer les accélération (cas pratique: un smartphone qui tombe) mais surtout l’accélération terrestre G sur les 3 axes. Cette accélération terrestre responsable de la gravité est dirigée vers le centre de la terre, en mesurant cette accélération sur 3 axes, il est donc possible de déterminer la position/orientation 3D de la carte par rapport au sol (cas pratique: la rotation automatique des écrans sur un smartphone, tenue d'équilibre pour un robot bipède).

Pour les friands de détails

L'interpréteur MicroPython

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).

MicroPython sur PC

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.

Mini système d'exploitation Python

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.

PyBoard sous le capot

  • STM32F405RG microcontroller.
  • 168 MHz Cortex-M4 CPU with 32-bit hardware floating point.
  • 1 MiB flash storage, 192 KiB RAM.
  • Micro-B USB connector, with software support for USB serial, USB mass storage, and USB HID (mouse, keyboard).
  • Micro SD slot.
  • MMA7660 3-axis accelerometer, up to 64 6-bit samples per second per axis.
  • 4 LEDs, 1 reset switch, 1 user switch.
  • 3.3V LDO regulator at 300mA, power from USB or external voltage source between 3.6V and 10V.
  • Real-time clock with date and time.
  • 30 general purpose I/O lines, 28 are 5V tolerant (unless in ADC mode).
  • Communication: 2x SPI, 2x CAN, 2x I2C, 5x USART.
  • 14x 12-bit ADC pins (analog signal in).
  • 2x DAC pins (analog signal out).
  • Board dimensions: 33mm by 40mm.
  • Board weight: 6 grams.
  • Board I/O connectors: 46 holes, standard 0.1 inch separation.

Brochage

Pybv10-pinout.jpg
Crédit: MicroPython micropython.org

Licence Micro Python

Micro Python rst sous licence MIT.

J'ai repris le texte de licence tel que disponible sur le site MicroPython.org (docs.micropython.org/en/latest/license.html)

The MIT License (MIT)

Copyright (c) 2013, 2014 Damien P. George, and others

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the 
Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the 
Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Où Acheter

Vous pouvez vous procurer une carte MicroPython chez MCHobby (vendus uniquement sur stock)!



Source: Micro Python Python for microcontrollers écrit par/written by Damien P.George

Traduit par Meurisse D. pour MCHobby.be - Translated by Meurisse D. for MCHobby.be

Traduit avec l'autorisation de micropython.org - Translated with the authorisation of micropython.org

Toute référence, mention ou extrait de cette traduction doit être explicitement accompagné du texte suivant : «  Traduction par MCHobby (www.MCHobby.be) - Vente de kit et composants » avec un lien vers la source (donc cette page) et ce quelque soit le média utilisé.

L'utilisation commercial de la traduction (texte) et/ou réalisation, même partielle, pourrait être soumis à redevance. Dans tous les cas de figures, vous devez également obtenir l'accord du(des) détenteur initial des droits. Celui de MC Hobby s'arrêtant au travail de traduction proprement dit.