Jump to content

MicroPython: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
→See also: add portal
 
(104 intermediate revisions by 63 users not shown)
Line 1: Line 1:
{{Short description|Microcontroller software based on Python}}
{{Use dmy dates|date=April 2022}}
{{Infobox software
{{Infobox software
| name = MicroPython
| name = MicroPython
| logo = Micropython-logo.svg
| logo = MicroPython new logo.svg{{!}}class=skin-invert
| logo size = 200px
| logo size = 100px
| author = Damien George
| developer = Damien P. George
| released = {{Start date and age|2014|05|03|df=yes}}
| released = {{Start date and age|2014|05|03|df=yes}}
| latest release version = 1.10
| latest release version = {{wikidata|property|edit|P548=Q2804309|P348}}
| latest release date = {{Start date and age|2019|01|24|df=yes}}
| latest release date = {{start date and age|{{wikidata|qualifier|single|P548=Q2804309|P348|P577}}}}
| programming language = [[C (programming language)|C]]
| programming language = [[C (programming language)|C]]
| platform = [[Micro Bit]], [[Arduino]], [[ESP8266]], [[ESP32]],[[STM32]]
| platform = [[ARM Cortex-M]], [[STM32]], [[ESP8266]], [[ESP32]], 16-bit [[PIC microcontrollers|PIC]], [[Unix]], [[Microsoft Windows]], [[Zephyr (operating system)|Zephyr]], [[JavaScript]], [[RP2040]]
| license = [[MIT license]]<ref>{{Cite web|url=https://github.com/micropython/micropython/blob/master/LICENSE|title=micropython/LICENSE at master · micropython/micropython|last=George|first=Damien P.|date=4 May 2014|website=[[GitHub]]|access-date=11 February 2017}}</ref>
| genre = [[Python (programming language)|Python]] implementation
| license = [[MIT license]]<ref>{{Cite web|url=https://github.com/micropython/micropython/blob/master/LICENSE|title=micropython/LICENSE at master · micropython/micropython|last=George|first=Damien P.|date=4 May 2014|website=[[GitHub]]|archive-url=|archive-date=|dead-url=|access-date=11 February 2017}}</ref>
| website = {{URL|https://micropython.org}}
| website = {{URL|https://micropython.org}}
}}
}}
'''MicroPython'''<ref name="MP-Website">{{cite web|url=https://micropython.org/|title=MicroPython - Python for microcontrollers|website=micropython.org|accessdate=12 August 2017}}</ref> is a [[software]] implementation of the [[Python (programming language)|Python]] 3 [[programming language]], written in [[C (programming language)|C]], that is optimized to run on a [[microcontroller]].<ref>{{cite news|last1=Venkataramanan|first1=Madhumita|title=Micro Python: more powerful than Arduino, simpler than the Raspberry Pi|url=https://www.wired.co.uk/article/micro-python|accessdate=15 December 2016|publisher=Wired|date=6 December 2013}}</ref><ref>{{cite news|last1=Yegulalp|first1=Serdar|title=Micro Python's tiny circuits: Python variant targets microcontrollers|url=http://www.infoworld.com/article/2608012/python/micro-python-s-tiny-circuits--python-variant-targets-microcontrollers.html|accessdate=15 December 2016|publisher=InfoWorld|date=5 July 2014}}</ref> MicroPython is a full Python compiler and runtime that runs on the micro-controller hardware. The user is presented with an interactive prompt (the [[Read–eval–print loop|REPL]]) to execute supported commands immediately. Included are a selection of core Python libraries; MicroPython includes modules which give the programmer access to low-level hardware.<ref name="MP-Website"/>
'''MicroPython''' is a [[software]] implementation of a [[programming language]] largely compatible with [[Python (programming language)|Python]] 3, written in [[C (programming language)|C]], that is optimized to run on a [[microcontroller]].<ref>{{cite magazine|last1=Venkataramanan|first1=Madhumita|title=Micro Python: more powerful than Arduino, simpler than the Raspberry Pi|url=https://www.wired.co.uk/article/micro-python|accessdate=15 December 2016|magazine=Wired|date=6 December 2013}}</ref><ref>{{cite news|last1=Yegulalp|first1=Serdar|title=Micro Python's tiny circuits: Python variant targets microcontrollers|url=http://www.infoworld.com/article/2608012/python/micro-python-s-tiny-circuits--python-variant-targets-microcontrollers.html|accessdate=15 December 2016|publisher=InfoWorld|date=5 July 2014}}</ref>


MicroPython consists of a Python compiler to bytecode and a runtime interpreter of that bytecode. The user is presented with an interactive prompt (the [[Read–eval–print loop|REPL]]) to execute supported commands immediately. Included are a selection of core Python libraries; MicroPython includes modules which give the programmer access to low-level hardware.<ref name="MP-Website">{{cite web|url=https://micropython.org/|title=MicroPython - Python for microcontrollers|website=micropython.org|accessdate=12 August 2017}}</ref>
MicroPython was originally created by the Australian programmer and physicist [http://dpgeorge.net/ Damien George], after a successful [[Kickstarter]] backed campaign in 2013.<ref>{{cite web|title=Micro Python: Python for microcontrollers|url=https://www.kickstarter.com/projects/214379695/micro-python-python-for-microcontrollers|website=Kickstarter|publisher=Kickstarter|accessdate=15 December 2016}}</ref> While the original Kickstart campaign released MicroPython with a pyboard microcontroller, MicroPython supports a number of [[ARM architecture|ARM]] based architectures.<ref>{{cite news|last1=Beningo|first1=Jacob|title=Prototype to production: MicroPython under the hood|url=http://www.edn.com/electronics-blogs/embedded-basics/4442357/Prototype-to-production---MicroPython-under-the-hood|accessdate=15 December 2016|publisher=EDN Network|date=11 July 2016}}</ref> MicroPython has since been run on [[Arduino]] platform based products,<ref>{{cite news|last1=Horsey|first1=Julian|title=Pyduino Arduino Based Development Board That Supports MicroPython (video)|url=http://www.geeky-gadgets.com/pyduino-arduino-based-development-board-that-supports-micropython-12-10-2016/|accessdate=15 December 2016|publisher=Geeky Gadgets|date=12 October 2016}}</ref><ref>{{cite news|last1=Beningo|first1=Jacob|title=Getting Started with Micro Python|url=http://www.edn.com/electronics-blogs/embedded-basics/4441798/Getting-Started-with-Micro-Python|accessdate=15 December 2016|publisher=EDN Network|date=6 April 2016}}</ref> [[ESP8266]],<ref>{{cite news|last1=Williams|first1=Elliot|title=MicroPython on the ESP8266: Kicking the Tires|url=https://hackaday.com/2016/07/21/micropython-on-the-esp8266-kicking-the-tires/|accessdate=15 December 2016|publisher=Hackaday|date=21 July 2016}}</ref> [[ESP32]],<ref>{{cite web|title=MicroPython ported to the ESP32|url=https://github.com/micropython/micropython-esp32|website=GitHub|accessdate=8 March 2017}}</ref> and [[Internet of things]]<ref>{{cite web|title=MicroPython on the ESP8266: beautifully easy IoT|url=https://www.kickstarter.com/projects/214379695/micropython-on-the-esp8266-beautifully-easy-iot|website=Kickstarter|publisher=Kickstarter|accessdate=6 December 2017}}</ref><ref>{{cite web|title=MICROPYTHON BRINGING PYTHON TO THE INTERNET OF THINGS|url=https://todayispotato.github.io/micropython-talk/|website=MICROPYTHON BRINGING PYTHON TO THE INTERNET OF THINGS|publisher=github.io|accessdate=6 December 2017}}</ref><ref>{{cite web|title=FiPy – The world's first 5-network IoT dev board|url=https://www.kickstarter.com/projects/1795343078/fipy-the-worlds-first-5-network-iot-dev-board|website=Kickstarter|accessdate=15 December 2016}}</ref><ref>{{cite news|title=Pycom Incorporating Sequans LTE-M Technology in New 5-Network IoT Development Board|url=http://www.businesswire.com/news/home/20161122005481/en/Pycom-Incorporating-Sequans-LTE-M-Technology-5-Network-IoT|accessdate=15 December 2016|publisher=Business Wire|date=22 November 2016}}</ref> hardware. In 2016 a version of MicroPython for the [[BBC]] [[Micro Bit]] was created as part of the [[Python Software Foundation]]'s contribution to the Micro Bit partnership with the BBC.<ref name=elecweekly_williams>{{cite web|last1=Williams|first1=Alun|title=Hands on with the BBC Micro-Bit user interface|url=http://www.electronicsweekly.com/news/design/embedded-systems/video-bbc-micro-bit-user-interface-2015-07/|website=ElectronicsWeekly.com|accessdate=8 July 2015}}</ref>

MicroPython does have an [[inline assembler]], which lets the code run at full speed, but it is not portable across different microcontrollers.

The source code for the project is available on [[GitHub]] under the [[MIT License]].<ref>{{cite web|url=https://github.com/micropython/micropython|title=MicroPython on GitHub|website=[[GitHub]]|date=7 February 2022}}</ref>

== History ==
[[File:Casio FX-9860G3.jpg|thumb|right|A Casio FX-9860GIII calculator which was introduced in 2020, and came with built-in MicroPython]]

MicroPython was originally created by the Australian programmer Damien George, after a successful [[Kickstarter]]-backed campaign in 2013.<ref>{{cite web|title=Micro Python: Python for microcontrollers|url=https://www.kickstarter.com/projects/214379695/micro-python-python-for-microcontrollers|website=Kickstarter|date=26 February 2016 |accessdate=15 December 2016}}</ref> The original Kickstarter campaign released MicroPython with an [[STM32#STM32 F4|STM32F4]]-powered development board "pyboard". In the meantime MicroPython has been developed to support a number of [[ARM architecture|ARM]] based architectures.<ref>{{cite news|last1=Beningo|first1=Jacob|title=Prototype to production: MicroPython under the hood|url=http://www.edn.com/electronics-blogs/embedded-basics/4442357/Prototype-to-production---MicroPython-under-the-hood|accessdate=15 December 2016|publisher=EDN Network|date=11 July 2016}}</ref>
The ports supported in the mainline are ARM Cortex-M (many [[STM32]]<ref>{{Cite web |title=MicroPython on Nucleo STM32, STM32F411CE, and STM32F401CC: flashing firmware and basic tools |url=https://mischianti.org/micropython-on-nucleo-stm32-stm32f411ce-and-stm32f401cc-flashing-firmware-and-basic-tools/ |website=Mischianti|date=August 2023 }}</ref>
boards, [[RP2040]] boards, TI CC3200/WiPy, Teensy boards, Nordic nRF series, SAMD21 and SAMD51), [[ESP8266]], [[ESP32]],<ref>{{Cite web |title=MicroPython with esp8266 and esp32: flashing firmware and programming with basic tools |url=https://mischianti.org/micropython-with-esp8266-and-esp32-flashing-firmware-and-programming-with-basic-tools-1/ |website=Mischianti|date=7 June 2023 }}</ref>
16-bit PIC, Unix, Windows, Zephyr, and JavaScript.<ref>{{cite web|last1=George|first1=Damien P.|title=micropython/ports at master · micropython/micropython|url=https://github.com/micropython/micropython/tree/master/ports|accessdate=22 October 2019|website=GitHub}}</ref>
Also, there are many forks for a variety of systems and hardware platforms not supported in the mainline.<ref>{{cite web|last1=Sokolovsky|first1=Paul|title=Awesome MicroPython|url=https://github.com/pfalcon/awesome-micropython#forks-and-variants|accessdate=22 October 2019|website=GitHub}}</ref>

In 2016, a version of MicroPython for the [[BBC]] [[Micro Bit]] was created as part of the [[Python Software Foundation]]'s contribution to the Micro Bit partnership with the BBC.<ref>{{cite web|last1=Williams|first1=Alun|title=Hands on with the BBC Micro-Bit user interface|url=http://www.electronicsweekly.com/news/design/embedded-systems/video-bbc-micro-bit-user-interface-2015-07/|website=ElectronicsWeekly.com|date=7 July 2015|accessdate=8 July 2015}}</ref>

In July 2017, MicroPython was forked to create [[CircuitPython]], a version of MicroPython with emphasis on education and ease of use. MicroPython and CircuitPython support somewhat different sets of hardware (e.g. CircuitPython supports [[Atmel]] SAM D21 and D51 boards, but dropped support for ESP8266). As of version 4.0, CircuitPython is based on MicroPython version 1.9.4.<ref>{{cite web|first1=Scott|last1=Shawcroft|title=CircuitPython 4.0.1 released!|url=https://blog.adafruit.com/2019/05/22/circuitpython-4-0-1-released/|website=Adafruit Blog|date=22 May 2019|publisher=Adafruit Industries|accessdate=11 Jun 2019}}</ref>


In 2017, [[Microsemi]] made a MicroPython port for [[RISC-V]] (RV32 and RV64) architecture.<ref>{{cite web| title=RISC-V Poster Preview — 7th RISC-V Workshop| url=https://content.riscv.org/wp-content/uploads/2017/12/RISC-V-Poster-Preview.pdf| date=28 November 2017| accessdate=17 December 2018}}</ref>
In 2017, [[Microsemi]] made a MicroPython port for [[RISC-V]] (RV32 and RV64) architecture.<ref>{{cite web| title=RISC-V Poster Preview — 7th RISC-V Workshop| url=https://content.riscv.org/wp-content/uploads/2017/12/RISC-V-Poster-Preview.pdf| date=28 November 2017| accessdate=17 December 2018}}</ref>


The source code for the project is available on [[GitHub]].<ref>{{cite web|url=https://github.com/micropython/micropython|title=MicroPython on GitHub}}</ref>
In April 2019, a version of MicroPython for the [[Lego Mindstorms EV3]] was created.<ref>{{Cite web|url=https://www.ev3dev.org/news/2019/04/13/ev3-micropython/|title=LEGO releases MicroPython for EV3 based on ev3dev and Pybricks|website=www.ev3dev.org|access-date=2020-04-21}}</ref>


In January 2021, a MicroPython port for the RP2040 (ARM Cortex-M0+, on [[Raspberry Pi Pico]] and others) was created.<ref>{{Cite web|url=https://www.raspberrypi.org/blog/raspberry-pi-silicon-pico-now-on-sale/|title= Meet Raspberry Silicon: Raspberry Pi Pico now on sale at $4|website=www.raspberrypi.org|date= 21 January 2021|access-date=2021-01-21}}</ref>
==References==
{{Reflist}}


==External links==
== Features ==

=== Ability to run Python ===

MicroPython has the ability to run Python, allowing users to create simple and easy-to-understand programs.<ref name=":0">{{cite book |last=Alsabbagh |first=Marwan |title=MicroPython Cookbook |date=2019 |publisher=[[Packt Publishing]] |location=Birmingham, UK |author-link=Marwan Alsabbagh}}</ref> MicroPython supports many standard Python libraries, supporting more than 80% of the features of Python's most used libraries.<ref name=":0" /> MicroPython was designed specifically to support the typical performance gap between microcontrollers and Python.<ref name=":1">{{cite web |last1=Bruno |first1=P. |title=An Introduction to MicroPython |url=https://all3dp.com/2/micropython-beginner-s-guide/ |website=All3DP |date=25 November 2021 |access-date=9 May 2022}}</ref> Python code is able to directly access and interact with hardware, with increased hardware possibilities that are not available using a normal Python application that is run on an [[operating system]].<ref name=":2">{{cite book |last=Bell |first=Charles |title=MicroPython for the Internet of Things |date=2017 |publisher=[[Apress]] |location=Berkeley, USA |author-link=Charles Bell}}</ref>

=== Code portability ===

MicroPython's utilisation of [[Hardware Abstraction Layer|hardware abstraction layer]] (HAL) technology allows developed code to be portable among different microcontrollers within the same family or platform and on devices that support and can download MicroPython. Programs are often developed and tested on high-performance microcontrollers and distributed with the final application used on lower-performance microcontrollers.<ref name=":3">{{cite conference |last1=Gaspar |first1=G. |last2=Kuba |first2=P. |last3=Flochova |first3=J. |last4=Dudak |first4=J. |last5=Florkova |first5=Z. |date=2020 |title=Development of IoT applications based on the MicroPython platform for Industry 4.0 implementation |conference=2020 19th International Conference on Mechatronics – Mechatronika (ME) |pages=1–7}}</ref>

=== Modules ===

MicroPython offers functionality, once new code has been written, to create a frozen module and use it as a library which can be a part of developed [[firmware]]. This feature assists with avoiding repetitive downloading of the same, already error-free, tested code into a MicroPython environment. This type of module will be saved to a microcontroller's modules directory for [[Compiler|compiling]] and uploading to the microcontroller where the library will be available using Python's import command to be used repeatedly.<ref name=":3" />

=== Read–eval–print loop ===

The [[read–eval–print loop]] (REPL) allows a developer to enter individual lines of code and have them run immediately on a [[Terminal emulator|terminal]].<ref name=":4">{{cite web |last1=Rembor |first1=K. |title=The REPL |work=Welcome to CircuitPython! |url=http://learn.adafruit.com/welcome-to-circuitpython/the-repl |publisher=Adafruit Learning System |access-date=9 May 2022}}</ref> [[Linux]]-based and [[macOS]] systems have terminal [[emulator]]s that can be used to create a direct connection to a MicroPython device's REPL using a serial [[USB]] connection. The REPL assists with the immediate testing of parts of an [[Application software|application]] as each part of the code can be run and the results visually examined. Once different parts of code are loaded into the REPL, additional REPL features can be used to experiment with that code's functionality.<ref name=":0" />

Helpful REPL commands (once connected to a serial console):<ref name=":4" />
* {{keypress|CTRL|C}}: keyboard interrupt
* {{keypress|CTRL|D}}: reload
* {{code|2=python|help()}}: help message
* {{code|2=python|help("modules")}}: lists built-in [[Modules Environment|modules]]
* {{code|2=python|import board}}{{keypress|ENTER}}{{code|2=python|dir(board)}}: lists all the pins on your microcontroller board that are available to be used in a program's code

=== Limitations ===

Although MicroPython fully implements Python language version 3.4 and much of 3.5, it does not implement all language features introduced from 3.5 onwards,<ref>{{cite web |title=MicroPython differences from CPython — MicroPython latest documentation |url=https://docs.micropython.org/en/latest/genrst/index.html |website=docs.micropython.org}}</ref> though some new syntax from 3.6 and more recent features from later versions, e.g. from 3.8 (assignment expressions) and 3.9. It includes a subset of the standard library.<ref>{{cite web |title=MicroPython - Python for microcontrollers |url=https://www.micropython.org |website=micropython.org |language=en}}</ref>

MicroPython has more limited hardware support in the microcontroller market than other popular platforms, like [[Arduino]] with a smaller number of microcontroller choices that support the language.<ref name=":1" /> MicroPython does not include an [[integrated development environment]] (IDE) or specific editor unlike other platforms.<ref name=":1" />

== Syntax and semantics ==
{{Main|Python syntax and semantics}}

MicroPython's [[Syntax (programming languages)|syntax]] is adopted from Python, due to its clear and easy-to-understand style and power.<ref>{{cite conference |last1=Wang |first1=L. |last2=Li |first2=Y. |last3=Zhang |first3=H. |last4=Han |first4=Q. |last5=Chen |first5=L. |date=2021 |title=An Efficient Control-flow based Obfuscator for Micropython Bytecode |conference=2021 7th International Symposium on System and Software Reliability (ISSSR) |pages=54–63}}</ref> Unlike most other programming languages less punctuation is used with fewer syntactical machinations in order to prioritise readability.<ref name=":0" />

=== Code blocks ===

MicroPython adopts Python's code block style, with code specific to a particular [[Function_(computer_programming)|function]], condition or loop being indented.<ref name=":0" /> This differs from most other languages which typically use symbols or keywords to delimit blocks.<ref name=":0" /> This assists with the readability of MicroPython code as the visual structure mirrors the semantic structure. This key feature is simple but important as misused indentation can result in code executing under a wrong condition or an overall error from the [[Interpreter (computing)|interpreter]].<ref name=":0" />

A colon (:) is the key symbol used to indicate the ending of a condition statement.<ref name=":0" /> The indent size is equivalent to one tab or 4 spaces.

=== Operations ===

MicroPython has the ability to perform various mathematical operations using primitive and logical operations.<ref name=":2" />

{| class="wikitable"
|+ Supported operations<ref name=":2" />
|-
! Type !! Operator !! Name !! Example
|-
| rowspan="5" | Arithmetic || {{tt|+}} || Addition || {{tt|1=variable + 1}}
|-
| {{tt|-}} || Subtraction || {{tt|1=variable - 1}}
|-
| {{tt|*}} || Multiplication || {{tt|1=variable * 4}}
|-
| {{tt|/}} || Division || {{tt|1=variable / 4}}
|-
| {{tt|%}} || Modulo division || {{tt|1=variable % 4}}
|-
| rowspan="6" | Comparison || {{tt|1===}} || Equals || {{tt|1=expression1 == expression2}}
|-
| {{tt|1=!=}} || Not equal || {{tt|1=expression1 != expression2}}
|-
| {{tt|<}} || Less than || {{tt|1=expression1 < expression2}}
|-
| {{tt|>}} || Greater than || {{tt|1=expression1 > expression2}}
|-
| {{tt|1=<=}} || Less than or equals || {{tt|1=expression1 <= expression2}}
|-
| {{tt|1=>=}} || Greater than or equals || {{tt|1=expression1 >= expression2}}
|-
| rowspan="6" | Logical || {{tt|&}} || [[Bitwise operation|bitwise]] and || {{tt|1=variable1 & variable2}}
|-
| {{tt|&#124;}} || bitwise or || {{tt|1=variable1 &#124; variable2}}
|-
| {{tt|^}} || bitwise exclusive or || {{tt|1=variable1 ^ variable2}}
|-
| {{tt|~}} || bitwise complement || {{tt|1=~variable1}}
|-
| {{tt|and}} || logical and || {{tt|1=variable1 and variable2}}
|-
| {{tt|or}} || logical or || {{tt|1=variable1 or variable2}}
|}

=== Libraries ===

MicroPython is a lean and efficient implementation of Python with libraries similar to those in Python.<ref>{{cite conference |last1=Khamphroo |first1=M. |last2=Kwankeo |first2=N. |last3=Kaemarungsi |first3=K. |last4=Fukawa |first4=K. |date=2017 |title=MicroPython-based educational mobile robot for computer coding learning |conference=2017 8th International Conference of Information and Communication Technology for Embedded Systems (IC-ICTES) |pages=1–6}}</ref> Some standard Python libraries have an equivalent library in MicroPython renamed to distinguish between the two. MicroPython libraries are smaller with less popular features removed or modified to save [[Memory management|memory]].<ref name=":2" />

The three types of libraries in MicroPython:<ref name=":2" />
* derived from a standard Python library (built-in libraries)
* specific MicroPython libraries
* specific libraries to assist with hardware functionality

MicroPython is highly customisable and configurable, with language differing between each board ([[microcontroller]]) and the availability of libraries may differ. Some functions and classes in a module or the entire module may be unavailable or altered.<ref name=":2" />

{| class="wikitable"
|+ Standard Python libraries in MicroPython<ref name="MP-Website" />
|-
! Library name !! Description
|-
| array || operations on [[Array data structure|arrays]]
|-
| cmath || provides math functions for [[complex number]]s
|-
| gc || [[Garbage collection (computer science)|garbage collector]]
|-
| math || provides basic math operations for [[Floating point numbers|floating-point numbers]]
|-
| sys || system-level functions; provides access to variables used by the interpreter
|-
| binascii || functions for converting between [[Binary number|binary]] and [[ASCII]]
|-
| collections || operations for collections and container types that hold various objects
|-
| errno || provides access to error codes
|-
| hashlib || operations for binary [[Hash function|hash algorithms]]
|-
| heapq || operations to implement [[Heap (data structure)|heap queue algorithm]]
|-
| io || operations for handling [[input/output]] streams
|-
| json || handles conversion between [[JSON]] documents and Python objects
|-
| os || functions for [[File system|filesystem]] access and basic [[operating system]] functions
|-
| re || implements regular expression matching operations
|-
| select || functions for handling events on multiple streams
|-
| socket || connecting to sockets (networks), providing access to socket interface
|-
| struct || performs conversions to Python objects by packing and unpacking [[primitive data type]]s
|-
| time || provides time and date function, including measuring time intervals and implementing delays
|-
| zlib || operations to decompress binary data
|}

{| class="wikitable"
|+ MicroPython-specific libraries<ref name="MP-Website" />
|-
! Library name !! Description
|-
| framebuf || provides a [[Framebuffer|frame buffer]] that can be used to create [[bitmap]] images to be sent to a display
|-
| machine || functions assisting with accessing and interacting with hardware blocks
|-
| micropython || access and control of MicroPython internals
|-
| network || assists with installing network driver, allowing interactions through networks
|-
| ctypes || access binary data structures
|}

=== Custom MicroPython libraries ===

When developers begin to create a new application, standard MicroPython libraries and drivers may not meet the requirements, with insufficient operations or calculations. Similar to Python, there is the possibility of extending MicroPython's functionality with custom libraries which extend the ability of the existing libraries and firmware.<ref name=":3" />

In MicroPython, files ending with .py take preference over other library aliases which allows users to extend the use and implementation of the existing libraries.<ref name=":2" />

== Supporting hardware ==

As MicroPython's implementation and popularity continues to grow, more boards have the ability to run MicroPython. Many developers are building processor specific versions that can be downloaded onto different microcontrollers.<ref name=":2" /> Installing MicroPython on microcontrollers is well documented and user-friendly.<ref name=":3" /> MicroPython allows interactions between microcontroller hardware and applications to be simple, allowing access to a range of functionality while working in a resource constrained environment, with a strong level of responsiveness.<ref name=":0" />

The two types of boards used to run MicroPython:<ref name=":2" />
* MicroPython loaded when manufactured, meaning only MicroPython can be run.
* boards that have firmware that allows MicroPython to be installed to the board.

=== Executing code ===

To move a program onto a MicroPython board, create a file and copy it onto the microcontroller in order to execute. With the hardware connected to a device, such as a [[computer]], the board's [[Flashdrive|flash drive]] will appear on the device allowing files to be moved to the flash drive. There will be two existing python files, boot.py and main.py that are typically not modified, main.py may be modified if you wish to run the program every time the microcontroller is [[Booting|booted]], otherwise, programs will be run using the REPL console.<ref name=":2" />

=== Pyboard ===

The pyboard is the official MicroPython microcontroller board which fully supports MicroPython's software features. The pyboard's hardware features include:<ref name="MP-Website" />

* [[microcontroller]] (MCU consisting of [[Central processing unit|CPU]], flash [[Read-only memory|ROM]] and [[Random-access memory|RAM]])
* [[microUSB]] connector
* [[micro-SD]] card slot
* IO pins
* [[switch]]es, [[LEDs]], [[Servomotor|servo]] ports, [[Real-time clock|real time clock]], [[accelerometer]]

==== The booting process ====

The pyboard contains an internal drive with filesystem named <code>/flash</code> which is stored within the board's flash memory, additionally, a [[microSD]] card can be inserted into a slot and is accessible through <code>/sd</code>. When booted up, a pyboard must select a filesystem to boot from either <code>/flash</code> or <code>/sd</code> with the current directory being set to either <code>/flash</code> or <code>/sd</code>. By default, if an SD card is inserted, <code>/sd</code> will be used, if not, <code>/flash</code> is used. If needed, the use of the SD card for the booting process can be avoided by creating an empty file called <code>/flash/SKIPSD</code> which is stored on the board flash memory to skip the SD card for the booting process.<ref name="MP-Website" />

==== Boot modes ====

When the pyboard is powered up normally or the reset button is pressed then the pyboard is booted in a standard mode, meaning that the boot.py file is executed, then the USB configured and finally the python program will run.<ref name="MP-Website" />

There is an ability to override the standard boot sequence through holding down the user switch whilst the board is in the booting process and then pressing reset as you continue to hold the user switch. The pyboard's LEDs will flick between modes and once the LEDs have reached the mode wanted by the user, they can let go of the user switch and the board will boot in the specific mode.<ref name="MP-Website" />

the boot modes are:<ref name="MP-Website" />
* standard boot: green LED only (runs boot.py then python program)
* safe boot: orange LED only (does not run any scripts during boot-up)
* filesystem reset: green and orange LED together (resets flash drive to factory state and boots in safe mode) – used as a fix when filesystem is corrupted

==== Errors ====

* if red and green LEDs flash alternatively then the python script has an error, and you must use the REPL to [[Debugging|debug]].
* if all 4 LEDs cycle on and off then there is a hard fault which cannot be recovered from and requires a hard reset.<ref name="MP-Website" />

== Programming examples ==
Source:<ref name=":2" />

[["Hello, World!" program|Hello world]] program:
<syntaxhighlight lang="python">
# Print to serial console

print("Hello, World!")
</syntaxhighlight>

Importing + turning on a LED:
<syntaxhighlight lang="python" line="1">
import pyb

# Turn LED on

pyb.LED(1).on()
</syntaxhighlight>

Reading a file + loop:
<syntaxhighlight lang="python" line="1" start="1">
import os

# Open and read a file

with open("/readme.txt") as f:
print(f.read())
</syntaxhighlight>

== Bytecode ==
MicroPython includes a [[cross compiler]] which generates MicroPython [[bytecode]] (file extension ''.mpy''). The Python code can be compiled into the bytecode either directly on a microcontroller or it can be precompiled elsewhere.

MicroPython firmware can be built without the compiler, leaving only the [[virtual machine]] which can run the precompiled ''mpy'' programs.

== Implementation and uses ==

MicroPython is utilised through firmware being loaded by standard software onto a particular microcontroller into flash memory, communicating using a terminal application loaded onto a computer that emulates a serial interface.<ref name=":3" />

The main uses of MicroPython can be generalised into three categories:<ref name=":3" />
* '''educational purposes''': using MicroPython's read–eval–print Loop (REPL) to interact with a microcontroller, it is possible to visually explain the concepts of data processing and communicating with boards in a simpler way than more complicated programming languages.
* '''developing and testing device and sensor designs''': MicroPython offers verified, bug-free, and thoroughly tested reference implementations of interfaces used in microcontrollers solving a common developer's task of implementing peripheral communication setup and control. MicroPython offers direct and interactive accessibility to device registers which makes it easy to verify functionality and develop and test hardware parts and devices and algorithms for control and acquiring data from a device.
* '''monitoring and configuring tool for design of complex applications''': certain applications require specific applications on high performing microcontrollers. MicroPython is able to assist with state monitoring and set-up of system parameters.

Implementation of MicroPython can differ depending on the availability of standard and supporting libraries and the microcontroller's flash memory and RAM size.<ref name=":3" />

== See also ==
{{Portal|Computer programming|Free and open-source software}}
* [[Espruino]]
* [[CircuitPython]]

== References ==
{{reflist}}

== External links ==
* {{Official website|https://micropython.org}}
* {{Official website|https://micropython.org}}
* {{GitHub|micropython/micropython}}
* {{GitHub|micropython/micropython}}
Line 33: Line 308:


[[Category:BBC computer literacy projects]]
[[Category:BBC computer literacy projects]]
[[Category:Embedded systems]]
[[Category:Free software programmed in C]]
[[Category:Free software programmed in C]]
[[Category:Microcontroller software]]
[[Category:Microcontroller software]]
[[Category:Python (programming language)]]
[[Category:Python (programming language)]]
[[Category:Software using the MIT license]]
[[Category:Software using the MIT license]]

{{prog-lang-stub}}

Latest revision as of 18:33, 3 April 2026

MicroPython
DeveloperDamien P. George
Release3 May 2014; 12 years ago (2014-05-03)
Stable release
1.29.0 Edit this on Wikidata / 24 August 2026; 2 months ago (24 August 2026)
Written inC
PlatformARM Cortex-M, STM32, ESP8266, ESP32, 16-bit PIC, Unix, Microsoft Windows, Zephyr, JavaScript, RP2040
LicenseMIT license[1]
Websitemicropython.org
Repository

MicroPython is a software implementation of a programming language largely compatible with Python 3, written in C, that is optimized to run on a microcontroller.[2][3]

MicroPython consists of a Python compiler to bytecode and a runtime interpreter of that bytecode. The user is presented with an interactive prompt (the REPL) to execute supported commands immediately. Included are a selection of core Python libraries; MicroPython includes modules which give the programmer access to low-level hardware.[4]

MicroPython does have an inline assembler, which lets the code run at full speed, but it is not portable across different microcontrollers.

The source code for the project is available on GitHub under the MIT License.[5]

History

[edit | edit source]
A Casio FX-9860GIII calculator which was introduced in 2020, and came with built-in MicroPython

MicroPython was originally created by the Australian programmer Damien George, after a successful Kickstarter-backed campaign in 2013.[6] The original Kickstarter campaign released MicroPython with an STM32F4-powered development board "pyboard". In the meantime MicroPython has been developed to support a number of ARM based architectures.[7] The ports supported in the mainline are ARM Cortex-M (many STM32[8] boards, RP2040 boards, TI CC3200/WiPy, Teensy boards, Nordic nRF series, SAMD21 and SAMD51), ESP8266, ESP32,[9] 16-bit PIC, Unix, Windows, Zephyr, and JavaScript.[10] Also, there are many forks for a variety of systems and hardware platforms not supported in the mainline.[11]

In 2016, a version of MicroPython for the BBC Micro Bit was created as part of the Python Software Foundation's contribution to the Micro Bit partnership with the BBC.[12]

In July 2017, MicroPython was forked to create CircuitPython, a version of MicroPython with emphasis on education and ease of use. MicroPython and CircuitPython support somewhat different sets of hardware (e.g. CircuitPython supports Atmel SAM D21 and D51 boards, but dropped support for ESP8266). As of version 4.0, CircuitPython is based on MicroPython version 1.9.4.[13]

In 2017, Microsemi made a MicroPython port for RISC-V (RV32 and RV64) architecture.[14]

In April 2019, a version of MicroPython for the Lego Mindstorms EV3 was created.[15]

In January 2021, a MicroPython port for the RP2040 (ARM Cortex-M0+, on Raspberry Pi Pico and others) was created.[16]

Features

[edit | edit source]

Ability to run Python

[edit | edit source]

MicroPython has the ability to run Python, allowing users to create simple and easy-to-understand programs.[17] MicroPython supports many standard Python libraries, supporting more than 80% of the features of Python's most used libraries.[17] MicroPython was designed specifically to support the typical performance gap between microcontrollers and Python.[18] Python code is able to directly access and interact with hardware, with increased hardware possibilities that are not available using a normal Python application that is run on an operating system.[19]

Code portability

[edit | edit source]

MicroPython's utilisation of hardware abstraction layer (HAL) technology allows developed code to be portable among different microcontrollers within the same family or platform and on devices that support and can download MicroPython. Programs are often developed and tested on high-performance microcontrollers and distributed with the final application used on lower-performance microcontrollers.[20]

Modules

[edit | edit source]

MicroPython offers functionality, once new code has been written, to create a frozen module and use it as a library which can be a part of developed firmware. This feature assists with avoiding repetitive downloading of the same, already error-free, tested code into a MicroPython environment. This type of module will be saved to a microcontroller's modules directory for compiling and uploading to the microcontroller where the library will be available using Python's import command to be used repeatedly.[20]

Read–eval–print loop

[edit | edit source]

The read–eval–print loop (REPL) allows a developer to enter individual lines of code and have them run immediately on a terminal.[21] Linux-based and macOS systems have terminal emulators that can be used to create a direct connection to a MicroPython device's REPL using a serial USB connection. The REPL assists with the immediate testing of parts of an application as each part of the code can be run and the results visually examined. Once different parts of code are loaded into the REPL, additional REPL features can be used to experiment with that code's functionality.[17]

Helpful REPL commands (once connected to a serial console):[21]

  • CTRL+C: keyboard interrupt
  • CTRL+D: reload
  • help(): help message
  • help("modules"): lists built-in modules
  • import board↵ Enterdir(board): lists all the pins on your microcontroller board that are available to be used in a program's code

Limitations

[edit | edit source]

Although MicroPython fully implements Python language version 3.4 and much of 3.5, it does not implement all language features introduced from 3.5 onwards,[22] though some new syntax from 3.6 and more recent features from later versions, e.g. from 3.8 (assignment expressions) and 3.9. It includes a subset of the standard library.[23]

MicroPython has more limited hardware support in the microcontroller market than other popular platforms, like Arduino with a smaller number of microcontroller choices that support the language.[18] MicroPython does not include an integrated development environment (IDE) or specific editor unlike other platforms.[18]

Syntax and semantics

[edit | edit source]

MicroPython's syntax is adopted from Python, due to its clear and easy-to-understand style and power.[24] Unlike most other programming languages less punctuation is used with fewer syntactical machinations in order to prioritise readability.[17]

Code blocks

[edit | edit source]

MicroPython adopts Python's code block style, with code specific to a particular function, condition or loop being indented.[17] This differs from most other languages which typically use symbols or keywords to delimit blocks.[17] This assists with the readability of MicroPython code as the visual structure mirrors the semantic structure. This key feature is simple but important as misused indentation can result in code executing under a wrong condition or an overall error from the interpreter.[17]

A colon (:) is the key symbol used to indicate the ending of a condition statement.[17] The indent size is equivalent to one tab or 4 spaces.

Operations

[edit | edit source]

MicroPython has the ability to perform various mathematical operations using primitive and logical operations.[19]

Supported operations[19]
TypeOperatorNameExample
Arithmetic+Additionvariable + 1
-Subtractionvariable - 1
*Multiplicationvariable * 4
/Divisionvariable / 4
%Modulo divisionvariable % 4
Comparison==Equalsexpression1 == expression2
!=Not equalexpression1 != expression2
<Less thanexpression1 < expression2
>Greater thanexpression1 > expression2
<=Less than or equalsexpression1 <= expression2
>=Greater than or equalsexpression1 >= expression2
Logical&bitwise andvariable1 & variable2
|bitwise orvariable1 | variable2
^bitwise exclusive orvariable1 ^ variable2
~bitwise complement~variable1
andlogical andvariable1 and variable2
orlogical orvariable1 or variable2

Libraries

[edit | edit source]

MicroPython is a lean and efficient implementation of Python with libraries similar to those in Python.[25] Some standard Python libraries have an equivalent library in MicroPython renamed to distinguish between the two. MicroPython libraries are smaller with less popular features removed or modified to save memory.[19]

The three types of libraries in MicroPython:[19]

  • derived from a standard Python library (built-in libraries)
  • specific MicroPython libraries
  • specific libraries to assist with hardware functionality

MicroPython is highly customisable and configurable, with language differing between each board (microcontroller) and the availability of libraries may differ. Some functions and classes in a module or the entire module may be unavailable or altered.[19]

Standard Python libraries in MicroPython[4]
Library nameDescription
arrayoperations on arrays
cmathprovides math functions for complex numbers
gcgarbage collector
mathprovides basic math operations for floating-point numbers
syssystem-level functions; provides access to variables used by the interpreter
binasciifunctions for converting between binary and ASCII
collectionsoperations for collections and container types that hold various objects
errnoprovides access to error codes
hashliboperations for binary hash algorithms
heapqoperations to implement heap queue algorithm
iooperations for handling input/output streams
jsonhandles conversion between JSON documents and Python objects
osfunctions for filesystem access and basic operating system functions
reimplements regular expression matching operations
selectfunctions for handling events on multiple streams
socketconnecting to sockets (networks), providing access to socket interface
structperforms conversions to Python objects by packing and unpacking primitive data types
timeprovides time and date function, including measuring time intervals and implementing delays
zliboperations to decompress binary data
MicroPython-specific libraries[4]
Library nameDescription
framebufprovides a frame buffer that can be used to create bitmap images to be sent to a display
machinefunctions assisting with accessing and interacting with hardware blocks
micropythonaccess and control of MicroPython internals
networkassists with installing network driver, allowing interactions through networks
ctypesaccess binary data structures

Custom MicroPython libraries

[edit | edit source]

When developers begin to create a new application, standard MicroPython libraries and drivers may not meet the requirements, with insufficient operations or calculations. Similar to Python, there is the possibility of extending MicroPython's functionality with custom libraries which extend the ability of the existing libraries and firmware.[20]

In MicroPython, files ending with .py take preference over other library aliases which allows users to extend the use and implementation of the existing libraries.[19]

Supporting hardware

[edit | edit source]

As MicroPython's implementation and popularity continues to grow, more boards have the ability to run MicroPython. Many developers are building processor specific versions that can be downloaded onto different microcontrollers.[19] Installing MicroPython on microcontrollers is well documented and user-friendly.[20] MicroPython allows interactions between microcontroller hardware and applications to be simple, allowing access to a range of functionality while working in a resource constrained environment, with a strong level of responsiveness.[17]

The two types of boards used to run MicroPython:[19]

  • MicroPython loaded when manufactured, meaning only MicroPython can be run.
  • boards that have firmware that allows MicroPython to be installed to the board.

Executing code

[edit | edit source]

To move a program onto a MicroPython board, create a file and copy it onto the microcontroller in order to execute. With the hardware connected to a device, such as a computer, the board's flash drive will appear on the device allowing files to be moved to the flash drive. There will be two existing python files, boot.py and main.py that are typically not modified, main.py may be modified if you wish to run the program every time the microcontroller is booted, otherwise, programs will be run using the REPL console.[19]

Pyboard

[edit | edit source]

The pyboard is the official MicroPython microcontroller board which fully supports MicroPython's software features. The pyboard's hardware features include:[4]

The booting process

[edit | edit source]

The pyboard contains an internal drive with filesystem named /flash which is stored within the board's flash memory, additionally, a microSD card can be inserted into a slot and is accessible through /sd. When booted up, a pyboard must select a filesystem to boot from either /flash or /sd with the current directory being set to either /flash or /sd. By default, if an SD card is inserted, /sd will be used, if not, /flash is used. If needed, the use of the SD card for the booting process can be avoided by creating an empty file called /flash/SKIPSD which is stored on the board flash memory to skip the SD card for the booting process.[4]

Boot modes

[edit | edit source]

When the pyboard is powered up normally or the reset button is pressed then the pyboard is booted in a standard mode, meaning that the boot.py file is executed, then the USB configured and finally the python program will run.[4]

There is an ability to override the standard boot sequence through holding down the user switch whilst the board is in the booting process and then pressing reset as you continue to hold the user switch. The pyboard's LEDs will flick between modes and once the LEDs have reached the mode wanted by the user, they can let go of the user switch and the board will boot in the specific mode.[4]

the boot modes are:[4]

  • standard boot: green LED only (runs boot.py then python program)
  • safe boot: orange LED only (does not run any scripts during boot-up)
  • filesystem reset: green and orange LED together (resets flash drive to factory state and boots in safe mode) – used as a fix when filesystem is corrupted

Errors

[edit | edit source]
  • if red and green LEDs flash alternatively then the python script has an error, and you must use the REPL to debug.
  • if all 4 LEDs cycle on and off then there is a hard fault which cannot be recovered from and requires a hard reset.[4]

Programming examples

[edit | edit source]

Source:[19]

Hello world program:

# Print to serial console

print("Hello, World!")

Importing + turning on a LED:

import pyb

# Turn LED on

pyb.LED(1).on()

Reading a file + loop:

import os

# Open and read a file

with open("/readme.txt") as f:
	print(f.read())

Bytecode

[edit | edit source]

MicroPython includes a cross compiler which generates MicroPython bytecode (file extension .mpy). The Python code can be compiled into the bytecode either directly on a microcontroller or it can be precompiled elsewhere.

MicroPython firmware can be built without the compiler, leaving only the virtual machine which can run the precompiled mpy programs.

Implementation and uses

[edit | edit source]

MicroPython is utilised through firmware being loaded by standard software onto a particular microcontroller into flash memory, communicating using a terminal application loaded onto a computer that emulates a serial interface.[20]

The main uses of MicroPython can be generalised into three categories:[20]

  • educational purposes: using MicroPython's read–eval–print Loop (REPL) to interact with a microcontroller, it is possible to visually explain the concepts of data processing and communicating with boards in a simpler way than more complicated programming languages.
  • developing and testing device and sensor designs: MicroPython offers verified, bug-free, and thoroughly tested reference implementations of interfaces used in microcontrollers solving a common developer's task of implementing peripheral communication setup and control. MicroPython offers direct and interactive accessibility to device registers which makes it easy to verify functionality and develop and test hardware parts and devices and algorithms for control and acquiring data from a device.
  • monitoring and configuring tool for design of complex applications: certain applications require specific applications on high performing microcontrollers. MicroPython is able to assist with state monitoring and set-up of system parameters.

Implementation of MicroPython can differ depending on the availability of standard and supporting libraries and the microcontroller's flash memory and RAM size.[20]

See also

[edit | edit source]

References

[edit | edit source]
  1. ↑ George, Damien P. (4 May 2014). "micropython/LICENSE at master · micropython/micropython". GitHub. Retrieved 11 February 2017.
  2. ↑ Venkataramanan, Madhumita (6 December 2013). "Micro Python: more powerful than Arduino, simpler than the Raspberry Pi". Wired. Retrieved 15 December 2016.
  3. ↑ Yegulalp, Serdar (5 July 2014). "Micro Python's tiny circuits: Python variant targets microcontrollers". InfoWorld. Retrieved 15 December 2016.
  4. 1 2 3 4 5 6 7 8 9 "MicroPython - Python for microcontrollers". micropython.org. Retrieved 12 August 2017.
  5. ↑ "MicroPython on GitHub". GitHub. 7 February 2022.
  6. ↑ "Micro Python: Python for microcontrollers". Kickstarter. 26 February 2016. Retrieved 15 December 2016.
  7. ↑ Beningo, Jacob (11 July 2016). "Prototype to production: MicroPython under the hood". EDN Network. Retrieved 15 December 2016.
  8. ↑ "MicroPython on Nucleo STM32, STM32F411CE, and STM32F401CC: flashing firmware and basic tools". Mischianti. August 2023.
  9. ↑ "MicroPython with esp8266 and esp32: flashing firmware and programming with basic tools". Mischianti. 7 June 2023.
  10. ↑ George, Damien P. "micropython/ports at master · micropython/micropython". GitHub. Retrieved 22 October 2019.
  11. ↑ Sokolovsky, Paul. "Awesome MicroPython". GitHub. Retrieved 22 October 2019.
  12. ↑ Williams, Alun (7 July 2015). "Hands on with the BBC Micro-Bit user interface". ElectronicsWeekly.com. Retrieved 8 July 2015.
  13. ↑ Shawcroft, Scott (22 May 2019). "CircuitPython 4.0.1 released!". Adafruit Blog. Adafruit Industries. Retrieved 11 June 2019.
  14. ↑ "RISC-V Poster Preview — 7th RISC-V Workshop" (PDF). 28 November 2017. Retrieved 17 December 2018.
  15. ↑ "LEGO releases MicroPython for EV3 based on ev3dev and Pybricks". www.ev3dev.org. Retrieved 21 April 2020.
  16. ↑ "Meet Raspberry Silicon: Raspberry Pi Pico now on sale at $4". www.raspberrypi.org. 21 January 2021. Retrieved 21 January 2021.
  17. 1 2 3 4 5 6 7 8 9 Alsabbagh, Marwan (2019). MicroPython Cookbook. Birmingham, UK: Packt Publishing.
  18. 1 2 3 Bruno, P. (25 November 2021). "An Introduction to MicroPython". All3DP. Retrieved 9 May 2022.
  19. 1 2 3 4 5 6 7 8 9 10 11 Bell, Charles (2017). MicroPython for the Internet of Things. Berkeley, USA: Apress.
  20. 1 2 3 4 5 6 7 Gaspar, G.; Kuba, P.; Flochova, J.; Dudak, J.; Florkova, Z. (2020). Development of IoT applications based on the MicroPython platform for Industry 4.0 implementation. 2020 19th International Conference on Mechatronics – Mechatronika (ME). pp. 1–7.
  21. 1 2 Rembor, K. "The REPL". Welcome to CircuitPython!. Adafruit Learning System. Retrieved 9 May 2022.
  22. ↑ "MicroPython differences from CPython — MicroPython latest documentation". docs.micropython.org.
  23. ↑ "MicroPython - Python for microcontrollers". micropython.org.
  24. ↑ Wang, L.; Li, Y.; Zhang, H.; Han, Q.; Chen, L. (2021). An Efficient Control-flow based Obfuscator for Micropython Bytecode. 2021 7th International Symposium on System and Software Reliability (ISSSR). pp. 54–63.
  25. ↑ Khamphroo, M.; Kwankeo, N.; Kaemarungsi, K.; Fukawa, K. (2017). MicroPython-based educational mobile robot for computer coding learning. 2017 8th International Conference of Information and Communication Technology for Embedded Systems (IC-ICTES). pp. 1–6.
[edit | edit source]