Run MicroPython on NodeMCU

Posted by Afsal on Oct. 15, 2021, 6:14 a.m.

Hi Pythonistas!

This post is for those who are interested in IoT projects. We are using an IoT Platform code named NodeMCU. NodeMCU is an open-source firmware for which open-source prototyping board designs are available. The name "NodeMCU" combines “node” and "MCU" (micro-controller unit). The Development Kit based on ESP8266 integrates all GPIO, PWM, IIC, 1-Wire, and ADC in one board.

 Power your development in the fastest way combined with NodeMCU Firmware!

NodeMCU supports MicroPython for rapid prototyping. In this post, we are planning to discuss how we can flash Python on NodeMCU and the led blinking program.

First, we need to install a package called ‘esptool’ from pip.

pip  install esptool

Then connect the NodeMCU to our USB port.

Then run the below command.

esptool.py --port <port name> erase_flash

If the OS is Linux, the port name will be /dev/ttyUSB0.

In case of any permission issue run the following command:

sudo chmod a+rw <portname>

If the OS is Windows, connect the board to the machine, then open Device Manager > Ports > <Name of the port which the board is connecting>

Download the latest binary from the below link https://micropython.org/download/esp8266/

Then run the following command

esptool.py --port <port_name> --baud 460800 write_flash --flash_size=detect 0 <path to esp8266-20210902-v1.17.bin>

Once it is completed the MicroPython is flashed to our board.

The next step is to run the Python code on the board. For that, we need another tool, thonny. Download this from the link:  https://thonny.org/ 

After the installation, open thonny ide.

We are planning a program to blink onboard LED every one second

Paste this code in ide and press save and select the target as the board

from machine import Pin #import Pin from machine moduel
from time import sleep
led = Pin(2, Pin.OUT) #setting the pin 2 as ouput pin
## onboard LED is connected to pin 2
while True:
   led.value(0)  #set pin to off 
   sleep(2)
   led.value(1) # set pin to on
   sleep(2)

Then run un the code after the coding is done.

run > interpretter > esp8266

After running the code in board our LED starts to blink like image below