Movatterモバイル変換


[0]ホーム

URL:


Skip to content
HOMEESP32ESP8266ESP32-CAMRASPBERRY PIMICROPYTHONRPi PICOARDUINOREVIEWS

Getting Started with MicroPython on ESP32 and ESP8266

Learn how to get started with MicroPython firmware on the ESP32 and ESP8266. We’ll introduce you to MicroPython, show you the differences between MicroPython and regular Python, and how to program your ESP based boards with MicroPython using uPyCraft IDE. After completing this guide, you’ll have your first LED blinking using MicroPython.

What is MicroPython?

MicroPython is a re-implementation of Python 3 targeted for microcontrollers and embedded systems. MicroPython is very similar with regular Python. So, if you already know how to program in Python, you also know how to program in MicroPython.

Python vs MicroPython

Apart from a few exceptions, the language features of Python are also available in MicroPython. The biggest difference between Python and MicroPython is that MicroPython was designed to work under constrained conditions.

Because of that, MicroPython does not come with the full standard library. It only includes a small subset of the Python standard library. However, it does include modules to access low-level hardware – this means that there are libraries to easily access and interact with the GPIOs.

Additionally, devices with Wi-Fi capabilities like the ESP8266 and ESP32 include modules to support network connections.

Why MicroPython?

Python is one of the most widely used, simple and easy-to-learn programming languages around. So, the emergence of MicroPython makes it extremely easy and simple to program digital electronics. If you’ve never programmed digital electronics before, MicroPython is a good starting point.

MicroPython’s goal is to make programming digital electronics as simple as possible, so it can be used by anyone. Currently, MicroPython is used by hobbyists, researchers, teachers, educators, and even in commercial products. The code for blinking an LED on a ESP32 or ESP8266 is as simple as follows:

# Complete project details at https://RandomNerdTutorials.com/micropython-programming-with-esp32-and-esp8266/from machine import Pinfrom time import sleepled = Pin(2, Pin.OUT)while True:  led.value(not led.value())  sleep(0.5)

View raw code

One great feature of MicroPython is that it comes with an interactive REPL (Read-Evaluate-Print Loop). The REPL allows you to connect to a board and execute code quickly without the need to compile or upload code.

MicroPython – Boards support

MicroPython runs on many different devices and boards, such as:

  • ESP32
  • ESP8266
  • PyBoard
  • Micro:Bit
  • Teensy 3.X
  • WiPy – Pycom
  • Adafruit Circuit Playground Express
  • Other ESP32/ESP8266 based boards

For more information about other boards that support MicroPython, take a look at the following links:

In our projects, we’ll use MicroPython with the ESP32 and ESP8266 boards.

ESP32 is the successor of the ESP8266. So, at the moment, not all features are available in MicroPython to take the most out of the ESP32 – it’s still an ongoing project. However, it’s very usable and you can make a lot of projects with it.

ESP32 and ESP8266 boards are similar, and you won’t feel almost any difference programming them using MicroPython. This means that anything you write for the ESP8266 should also run with no changes or minimal changes on the ESP32 (mainly changing the pin assignment).


Installing uPyCraft IDE

Before continuing with this tutorial, you should install uPyCraft IDE in your computer. Follow one of the next tutorials to install uPyCraft IDE:

Note: if you’re having trouble installing or using uPyCraft IDE, we’ve also created an alternative guide on how toprogram the ESP32/ESP8266 using Thonny IDE.

Flashing MicroPython Firmware to ESP32/ESP8266

Unlike other boards, MicroPython isn’t flashed onto the ESP32 or ESP8266 by default. That’s the first thing you need to do to start programming your boards with MicroPython: flash/upload the firmware. Follow the next tutorial to flash MicroPython firmware on your board:


Getting Started with uPyCraft IDE

In this section we’ll give you an overview of the uPyCraft IDE software, so that you can start programming the ESP32/ESP8266 with MicroPython.

The IDE is a software that contains tools to make the process of development, debugging and upload code easier. There are many ways to program your ESP board with MicroPython. We’ve chosen uPyCraft IDE because it is simple and intuitive to use and works great with the ESP boards.

At this point, we assumed that you have:

  • uPyCraft IDE installed on your computer
  • ESP32/ESP8266 flashed with MicroPython firmware

uPyCraft IDE Overview

Open uPyCraft IDE, a new window opens as follows:

Let’s take a closer look at each section of uPyCraft IDE:

  1. Folder and files
  2. Editor
  3. MicroPython Shell/Terminal
  4. Tools

1. Folder and files

This section shows several folders and files. Thedevice folder shows the files that are currently stored on your ESP board. If you have your ESP32 or ESP8266 connected via serial to uPyCraft IDE, when you expand thedevice folder, all files stored should load. By default, you should only have a boot.py file. To run your main code, it is recommended to create amain.py file.

  • boot.py: runs when the device starts and sets up several configuration options;
  • main.py: this is the main script that contains your code. It is executed immediately after the boot.py.

Thesd folder is meant to access files stored on SD cards – this is only works with boards like the PyBoard that come with an SD card slot.

TheuPy_lib shows the built-in IDE library files.

Finally, theworkspace is a directory to save your files. These files are saved in your computer in a directory defined by you. This is a specially useful to keep all your files organized at hand.

When using uPycraft for the first time, to select your working directory, click theworkspace folder. A new window pops up for you to chose yourworkspace path. Create a new folder or select an existing folder to be your working directory.

Then, go toFile >Reflush Directory to update the directory.

Note: to change your user directory, simply go toTools >InitConfig and click theworkspace directory folder to chose a different path.

2. Editor

The Editor section is where you write your code and edit your.py files. You can open more than one file, and the Editor will open a new tab for each file.

3. MicroPython Shell/terminal

On the MicroPython Shell you can type commands to be executed immediately by your ESP board without the need to upload new files. The terminal also provides information about the state of an executing program, shows errors related with upload, syntax errors, prints messages, etc…

4. Tools

The icons placed at the rightmost side allow you to quickly perform tasks. Each button is labeled in the figure below:

  • New file: creates a new file on the Editor;
  • Open file: open a file from your computer;
  • Save file: saves a file;
  • Download and run: upload the code to your board and execute the code;
  • Stop: stop the execution of the code – it’s the same as entering CRTL+C on the Shell to stop all scripts from running;
  • Connect/Disconnect: connect or disconnect to your board via Serial. You must select the serial port first inTools Serial;
  • Undo: undo last change in the code Editor;
  • Redo: redo last change in the code Editor;
  • Syntax check: checks the syntax of your code;
  • Clear: clear the Shell/terminal window messages.

Running Your First Script

To get you familiar with the process of writing a file and executing code on your ESP32/ESP8266 boards, we’ll upload a new script that simply blinks the on-board LED of your ESP32 or ESP8266.

Establishing a communication with the board

After having the MicroPython firmware installed on your board and having the board connected to your computer through an USB cable, follow the next steps:

1. Go toTools >Board and select the board you’re using.

2. Go toTools >Port and select the com port your ESP is connected to.

3. Press theConnect button to establish a serial communication with your board.

4. The>>> should appear in the Shell window after a successful connection with your board. You can type the print command to test if it’s working:

>>> print('Hello')Hello>>>

It should print the “Hello” message. Only if you see that message, you can continue with this tutorial. Otherwise, make sure you have established a serial communication with your board or that you’ve flashed successfully the MicroPython firmware on your board.

Creating the main.py file on your board

1. Press the “New file” button to create a new file.

2. Press the “Save file” button to save the file in your computer.

3. A new window opens, name your filemain.pyand save it in your computer:

4. After that, you should see the following in your uPyCraft IDE (theboot.py file in your device and a new tab with the main.py file):

5. Click the“Download and run” button to upload the file to your ESP board:

6. The device directory should now load themain.py file. Your ESP has the filemain.py stored.

Uploading the blink LED script

1. Copy the following code to the Editor on themain.py file:

# Complete project details at https://RandomNerdTutorials.com/micropython-programming-with-esp32-and-esp8266/from machine import Pinfrom time import sleepled = Pin(2, Pin.OUT)while True:  led.value(not led.value())  sleep(0.5)

View raw code

2. Press the “Stop” button to stop any script from running in your board:

3. Click the “Download and Run button” to upload the script to the ESP32 or ESP8266:

4. You should see a message saying “download ok” in the Shell window.

Testing the script

To run the script that was just uploaded to your board, you need to follow these steps:

1. Press the “Stop” button

2. Press the on-board ESP32/ESP8266EN (ENABLE) orRST (RESET) button to restart your board and run the script from the start:

If you’re using an ESP32, your Terminal messages should look something as shown in the following figure after a EN/RST button press:

Your ESP32 or ESP8266 on-board LED should be blinking every 500 milliseconds. Here’s where the ESP32’s on-board LED is located:

Here’s the ESP8266 on-board LED:

Troubleshooting Tips

We’ve discovered some common problems and error messages that occur with uPyCraft IDE. Usually restarting your ESP with the on-board EN/RST button fixes your problem. Or pressing the uPyCraft IDE “Stop” button and repeating your desired action. In case it doesn’t work for you, read these next common errors and discover how to solve them.

Error #1: You get the following message:

>>>Select Serial Port could not open port 'COM4': FileNotFoundError(2, 'The system cannot find the file specified.', None, 2)

Or an equivalent message:

>>>could not open port 'COM4': PermissionError(13, 'A device attached to the system is not functioning.', None, 31)

Unplug, and plug back your ESP board. Then, double-check that you’ve selected the right serial port in theTools >Serial menu. Then, click the “Connect/disconnect” button to establish a serial communication. You should now be able to upload a new script or re-run new code.

This error might also mean that you have your serial port being used in another program (like a serial terminal or in the Arduino IDE). Double-check that you’ve closed all the programs that might be establishing a serial communication with your ESP board. Then, unplug and plug back your ESP board. Finally, restart the uPyCraft IDE – try to select the serial port in the Tools >Serial menu.

Error #2: Trouble uploading a new script.

>>> already in download model,please wait.

Press the “Stop” button in uPyCraft IDE (1 or 2 times) to make sure any code that was running stops. After that, press the “Download and run” button to upload the new script to your ESP board.

Error #3: After uploading a new script, if you see the following message:

>>>Ready to download this file,please wait!... download okos.listdir('.')Traceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name 'os' isn't defined

Or this message:

>>>Ready to download this file,please wait!... download okos.listdir('.')OSError: [Errno 98]

It means the new file was uploaded to your board successfully. You can notice that it printed the “download ok” message. Press the ESP on-board “EN/RST” button to restart your board and re-run the new uploaded script from the beginning.

Error #4:Problem restarting your ESP board, running a new script or opening the serial port:

>>>Brownout detector was triggered

The “Brownout detector was triggered” error message means that there’s some sort of hardware problem. It’s often related to one of the following issues:

  • Poor quality USB cable;
  • USB cable is too long;
  • Board with some defect (bad solder joints);
  • Bad computer USB port;
  • Or not enough power provided by the computer USB port.

Solution: try a different shorter USB cable (with data wires), try a different computer USB port or use a USB hub with an external power supply.

Important: if you keep having constant problems or weird error messages, we recommend re-flashing your ESP board with the latest version of MicroPython firmware:Flash/Upload MicroPython Firmware to ESP32 and ESP8266.

Error #5: When I try to open a serial communication with the ESP32/ESP8266 in uPyCraft IDE, sometimes it prompts the “Burn Firmware” window asking to re-flash the MicroPython firmware.

Basically, we think this is what’s happening: when you’re running a script in your board, sometimes it’s busy running that script and performing the tasks. So, you need to try opening the COM port multiple times or restart the ESP to catch it available to establish the serial communication with uPyCraft IDE.

If you’re running a script that uses Wi-Fi, deep sleep, or it’s doing multiple tasks, I recommend trying 3 or 4 times to establish the communication. If you can’t, I recommend re-flash the ESP with MicroPython firmware.

Wrapping Up

We hope you’ve enjoyed learning how to program the ESP32 and ESP8266 boards using MicroPython firmware. If you want to learn more about MicroPython, take a look at our eBook:MicroPython Programming with ESP32 and ESP8266.



SMART HOME with Raspberry Pi ESP32 and ESP8266 Node-RED InfluxDB eBook
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

34 thoughts on “Getting Started with MicroPython on ESP32 and ESP8266”

  1. Does the firmware have to be re-flashed if you decide to go back to using the Arduino IDE?

    Reply
  2. Thank you so much for this tutorial. After flashing my esp with micropython, is it possible for me to program it with arduino ide again?

    Reply
  3. Amazing tutorial! Great stuff. Thanks Rui!

    Reply
  4. I thought I had followed a tutorial here using micro python on ESP32 that set a PWM output on the ESP32. I’m trying to find that tutorial but not having much luck.
    Thanks
    Paul

    Reply
  5. My blink LED script doesn’t work. I have TTGO MINI 32 V2.0 ESP32 board. Not sure if the pin 2 is the right LED pin for my board.
    Pin layout information:
    https://raw.githubusercontent.com/LilyGO/ESP32-MINI-32-V2.0/master/ZZ_Images/image1.jpg

    Reply
    • Hi Jayakumar.
      I’ve never used that board. But I was able to find the schematic diagram. For what I can tell, it seems that the built-in LED for your board is GPIO22.
      so, you just need to change the code to assign GPIO22 instead of 2.
      Can you try it and see if it solves your problem?
      Regards,
      Sara 🙂

      Reply
  6. Thanks for the clear tutorial, my ESP32 is blinking nicely.
    I am interested in the course/book, what is it with ‘currently closed for the general public’?
    Can you offer some suggestions how to proceed learning micropython?
    Best regards,
    Bart

    Reply
  7. hi,
    when I want to save my main.py file It doesn’t do anything. The “saved” file is not there and It doesn’t show me any errors either.

    Reply
  8. How to avoid some trouble shooting
    – After a first execution (essential) go to your user account \ AppData \ Local \ uPyCraft. In the config.json file replace git.oschina.net by github.com. You will no longer have an alert for a trojan.
    – There is a bug concerning SourceCodePro font whose name is incomplete which explains this systematic installation request. It should be SourceCodePro-black.ttf for example and not SourceCodePro.ttf (W10). To be done in a new version.
    – I had for several days this error consisting of rebuilding a burnfirmware before connecting to an ESP. This anomaly has disappeared without explanation !!
    I am working on the source code to go from Qt4 / PyQt4 to Qt5 / PyQt5
    Thank you Sara for your excellent site
    Didier

    Reply
    • Hi Didier.
      Thank you for sharing your knowledge about that subject.
      It will certainly be useful to resolve those annoying bugs in uPyCraft.
      Thank you.
      Regards.
      Sara

      Reply
  9. Well most people did better than I, I couldn’t even get uPyCraftIDE to load. My Del windows computer kept telling me it couldn’t install as file’s were missing. It suggested to download again & retry. I did this 9 times & each time was told file’s were missing & it wouldn’t install.

    Reply
  10. Hi
    How to control servo motors using micro python and PWM pins

    Reply
  11. Hi Sara Santos

    Thanks for this lovely tutorial and i have one question that after flasing arduino code to esp32 the micropython firmware will present or we have to reinstall back.

    Reply
  12. Thanks for the usefull tutorial!!! Great help
    I don´t see why, after disconecting and connecting again the ESP32, it doesn’t start blinking, even if I push the EN button.
    In fact, the only way to get it blinking, is to upload the program again… As if it wasn’t flash

    Reply
  13. Is there a similar program as uPyCraft IDE, but can also connect using wifi?

    Reply
  14. Hello, I’d like to know if wemos d1 mini can be flashed with micropython too.
    Thanks in advace
    Julio

    Reply
  15. I can run my program only when I have the ESP32 connect to uPyCraft, if I disconnect and push the EN button to test, it doesn’t run!
    I want to run my program without be connect to my PC.

    Reply
  16. So after millions of pages you still dont explain how to flush firmware. Why?

    Reply
  17. comment from may, 2019 :

    >
    How to avoid some trouble shooting
    – After a first execution (essential) go to your user account \ AppData \ Local \ uPyCraft. In the config.json file replace git.oschina.net by github.com. You will no longer have an alert for a trojan.
    – There is a bug concerning SourceCodePro font whose name is incomplete which explains this systematic installation request. It should be SourceCodePro-black.ttf for example and not SourceCodePro.ttf (W10). To be done in a new version.
    – I had for several days this error consisting of rebuilding a burnfirmware before connecting to an ESP. This anomaly has disappeared without explanation !!
    I am working on the source code to go from Qt4 / PyQt4 to Qt5 / PyQt5
    Thank you Sara for your excellent site
    Didier
    <<<

    the same problems i have. now we have 2022. THREE years ago, nothing happened. it’s a shame, isn’t it ?
    instead of Pin-Number use LED_BUILTIN .
    it’s the const implemented by all boards.

    for beginners thonny is not the wrong way. then u can use PyCharm with its modules and add-ons/plugins or Atom. uPyCraft is always the wrong way, shure for that !
    good luck …
    keep corona away !

    so long
    pc

    Reply

Leave a CommentCancel reply

Learn MicroPython

MicroPython Introduction

Thonny IDE Install

VS Code Install

Flash Firmware esptool.py

MicroPython Programming

MicroPython GPIOs

ESP32 Pinout

MicroPython Inputs Outputs

MicroPython PWM

MicroPython Analog Inputs

MicroPython Interrupts

ESP32 Deep Sleep

ESP8266 Deep Sleep

Web Servers

MicroPython Output Web Server

MicroPython Relay Web Server

MicroPython DHT Web Server

MicroPython BME280 Web Server

MicroPython BME680 Web Server

MicroPython DS18B20 Web Server

Sensors and Modules

MicroPython Relay Module

MicroPython PIR

MicroPython DHT11/DHT22

MicroPython BME280

MicroPython BME680

MicroPython DS18B20

MicroPython Multiple DS18B20

Weather Station Datalogger

MicroPython OLED

MicroPython OLED Draw Shapes

MicroPython WS2812B LEDs

MicroPython HC-SR04

MQTT

MicroPython MQTT Introduction

MQTT DHT11/DHT22

MQTT BME280

MQTT BME680

MQTT DS18B20

Useful Guides

MicroPython Access Point

MicroPython WiFiManager

uPyCraft IDE Windows

uPyCraft IDE Mac OS X

uPyCraft IDE Linux

Flash MicroPython Firmware

Learn More

Learn ESP32

Learn ESP8266

Learn ESP32-CAM

Learn MicroPython

Learn Arduino

MicroPython eBook »

Affiliate Disclosure:Random Nerd Tutorials is a participant in affiliate advertising programs designed to provide a means for us to earn fees by linking to Amazon, eBay, AliExpress, and other sites. We might be compensated for referring traffic and business to these companies.



Learn ESP32 with Arduino IDE eBook » Complete guide to program the ESP32 with Arduino IDE!



SMART HOME with Raspberry Pi, ESP32, and ESP8266 » learn how to build a complete home automation system.



Learn Raspberry Pi Pico/Pico W with MicroPython​ » The complete getting started guide to get the most out of the the Raspberry Pi Pico/Pico W (RP2040) microcontroller board using MicroPython programming language.



🔥 Learn LVGL: Build GUIs for ESP32 Projects​ » Learn how to build Graphical User Interfaces (GUIs) for ESP32 Projects using LVGL (Light Versatile Graphics Library) with the Arduino IDE.

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.


[8]ページ先頭

©2009-2025 Movatter.jp