How to Run Your MicroPython Script Automatically on Boot (ESP32 Friendly)

Never manually restart again! Learn how your MicroPython script runs on boot with ESP32, ensuring your projects are always ready, effortlessly.

Unlocking the power of MicroPython on ESP32, one morning, one cup of coffee, and one line of code at a time. This is where innovation begins, right here at home.

Forget manual restarts: your MicroPython script can be truly “on boot,” every single time.

I remember countless times tweaking a MicroPython script on an ESP32, confident it was perfect, only to pull the plug, plug it back in, and… nothing.

The script wouldn’t run on boot, leaving me scrambling to manually initiate it. It was a frustrating dance, especially for projects destined for remote locations or unattended operation.

Ready to liberate your ESP32 projects from manual intervention?

Keep reading to discover the straightforward path to reliable MicroPython startup.

Your First Steps with MicroPython and ESP32

Before we dive into the magic of automatic startup, let’s ensure we’re all on the same page with the basics. If you’re new to the world of MicroPython on ESP32, think of MicroPython as a lean, mean, Python-speaking machine perfectly tailored for microcontrollers like our beloved ESP32. It lets us write familiar Python code to control hardware, connect to networks, and build all sorts of embedded projects, freeing us from the complexities of C/C++ typically used in embedded development.

The very first hurdle is getting MicroPython onto your ESP32. This process is called “flashing the firmware.” You’ll need a few things:

  • Your ESP32 board: Connected to your computer via a USB cable.
  • A Python installation on your computer: Essential for the esptool.py utility.
  • esptool.py: A command-line utility used to flash firmware to ESP chips. You can usually install it via pip: pip install esptool.
  • The MicroPython firmware .bin file: Download the latest stable release for your specific ESP32 board from the MicroPython downloads page.

Once you have these, the basic steps typically involve:

Like what you’re reading?
Help keep DevDigest
free and caffeine-powered
—buy me a coffee on Ko-fi.

Erasing the flash

esptool.py --chip esp32 --port <your_COM_port> erase_flash 

Replace <your_COM_port> with the actual serial port your ESP32 is on, e.g., COM3 on Windows, /dev/ttyUSB0 on Linux, /dev/cu.usbserial-XXXX on macOS).

Flashing the firmware

esptool.py --chip esp32 --port <your_COM_port> --baud 460800 write_flash -z 0x1000 <path_to_firmware.bin> 

Again, replace the port and <path_to_firmware.bin>.

This foundational step transforms your ESP32 into a MicroPython-ready device, giving you a fresh canvas for your FOSS creations. Without this, there’s no boot.py or main.py to even speak of!

· · ─ ·𖥸· ─ · ·

Getting Your Code Onto the ESP32: The Tools of the Trade

So you’ve crafted your brilliant MicroPython script, perhaps blinking an LED or fetching data from a sensor. But how do you get that .py file from your computer’s editor onto the ESP32’s tiny filesystem? Unlike a desktop Python script, you can’t just double-click it. This is where dedicated MicroPython tools come in handy. For beginners, two popular and FOSS-friendly options stand out:

Thonny IDE

This is often recommended for MicroPython beginners, and for good reason. Thonny is a Python IDE that comes with built-in support for MicroPython, including a straightforward way to connect to your ESP32, browse its files, and upload your scripts. It provides a visual file explorer for your MicroPython board, making file transfer as simple as dragging and dropping or using menu options like “Save copy to MicroPython device.” It also integrates a REPL (Read-Eval-Print Loop) for immediate interaction, which is incredibly useful for debugging.

How it helps: Thonny simplifies the entire workflow from coding to uploading to interacting with your board. It abstracts away command-line complexities, letting you focus on your code.

ampy (Adafruit MicroPython Tool)

For those who prefer the command line or need to automate uploads, ampy is a fantastic tool. It’s a Python package that allows you to interact with your MicroPython device’s filesystem directly from your terminal.

pip install adafruit-ampy

Key commands for uploading:

ampy --port <your_COM_port> put your_script.py

This uploads your_script.py from your computer to the root directory of your ESP32’s filesystem.

ampy --port <your_COM_port> put your_script.py main.py

This specifically uploads your_script.py from your computer and renames it to main.py on the ESP32. This is how you’d typically get your main application logic onto the board to run on boot.

Why it’s powerful: ampy offers granular control and is excellent for scripting deployment, making it a favorite for more advanced FOSS projects where automated builds are common.

Choosing the right tool depends on your comfort level. Thonny offers a gentler entry, while ampy provides more power and flexibility as you grow. Both embody the open spirit of our community, giving you the means to bring your code to life on hardware.

· · ─ ·𖥸· ─ · ·

The Dynamic Duo: Understanding boot.py and main.py

The concept of your MicroPython script running “on boot” hinges entirely on two special files: boot.py and main.py. Think of them as the foundational scripts that MicroPython firmware on your ESP32 looks for immediately after it powers up. They are executed in a specific, intentional order, allowing for a structured startup process.

  • boot.py – The Setup Crew:
    • Execution Order: This is the very first Python script that MicroPython executes when your ESP32 powers on or resets.
    • Purpose:boot.py is your ideal place for low-level, essential configurations that need to happen before your main application logic kicks in. This includes things like:
      • Network setup: Connecting to Wi-Fi (import network, wlan.connect()).
      • Peripheral initialization: Setting up pins, I2C, SPI, or other hardware interfaces that your main script will rely on.
      • Mounting filesystems: If you have external flash or an SD card, this is where you’d mount it.
      • System-wide settings: Anything that impacts the general behavior of your MicroPython environment.
    • FOSS Best Practice: Keep boot.py lean and focused on foundational setup. If boot.py crashes, your board might become unresponsive or enter a boot loop, making it harder to recover. It’s like the bootstrap code for a larger system; it needs to be reliable.
  • main.py – The Main Event:
    • Execution Order: After boot.py successfully completes, MicroPython then automatically looks for and executes main.py.
    • Purpose: This is where the core logic of your application resides. It’s the “heart” of your project. Here you’ll put:
      • Your main program loop (e.g., reading sensors, controlling actuators, running a web server).
      • Function definitions and class implementations specific to your application.
      • Any import statements for custom modules you’ve written or libraries you’ve added (beyond those initialized in boot.py).
    • FOSS Best Practice: main.py should contain your primary application code. If your main.py encounters an error, it often provides a more graceful failure and might allow you to still interact with the REPL (Read-Eval-Print Loop) for debugging, unlike a fatal error in boot.py. For continuous operation, main.py often contains an infinite loop (while True:), ensuring your application keeps running.

By understanding this hierarchy, you can design more robust and maintainable MicroPython applications, ensuring that your FOSS projects wake up, configure themselves, and get to work without you needing to lift a finger.

Like what you’re reading?
Help keep DevDigest
free and caffeine-powered
—buy me a coffee on Ko-fi.

Understanding the Boot Process on ESP32

When your ESP32 powers on, it goes through a boot process, where it loads the firmware and waits for further commands. By default, the ESP32 does not run any scripts automatically. However, by configuring your ESP32 with MicroPython, you can set it up to run Python scripts on boot using the boot.py and main.py files.

The boot.py file is executed first during boot, followed by the main.py file. You can modify or create these files to automate various tasks, such as setting up Wi-Fi, initializing peripherals, or running custom scripts immediately upon boot.

· · ─ ·𖥸· ─ · ·

How to Set Up Your ESP32 to Run Python Scripts on Boot

Install MicroPython on Your ESP32

To start programming with the ESP32, you’ll need to set up the development environment. This involves installing the Arduino IDE, adding the ESP32 board through the Board Manager, and setting up necessary drivers for the microcontroller.
Find detailed steps on setting up the development environment here.

Create boot.py for Initial Setup

The boot.py file is executed as soon as the ESP32 starts up. Use this file to handle initial configurations, such as setting up Wi-Fi or loading essential libraries. For example, here’s a simple boot.py that prints a “Hello, World!” message when the device starts:

# boot.py
boot.py print("Hello, World!") 

This message will be printed to the console immediately upon boot.

Create main.py for Your Core Script

After the ESP32 runs boot.py, it will then run the main.py file. This is where the main functionality of your application resides. You can place the core logic of your project, such as sensor readings, device control, or communication, in this file.Example of a simple main.py script:

# main.py
def greet():
    print("This is from main.py!")

greet()

Import main.py into boot.py to Run on Boot

To keep your code modular and organized, you can import main.py into boot.py using the import keyword. This ensures that after printing the “Hello, World!” message, the ESP32 will load and execute main.py as part of the boot process.Here’s how boot.py should look:

# boot.py
print("Hello, World!")

# Import and run the greet function from main.py
import main

main.greet()

Save and Reboot Your ESP32

After saving both boot.py and main.py to your ESP32’s file system, reboot the device to see the changes take effect. You can reboot your ESP32 by running the following command in the REPL:

import machine
machine.reset()  # Reboots the ESP32

Test Your Setup

Upon reboot, your ESP32 will automatically run boot.py and print “Hello, World!” to the console. It will then import main.py and execute the greet() function, printing “This is from main.py!” as expected.

Troubleshooting Tips

  • Ensure Correct File Placement: The boot.py and main.py files must be placed in the root directory of the ESP32’s file system. Files located in subdirectories won’t be executed on boot.
  • Check for Code Errors: If the ESP32 doesn’t boot as expected, check the serial monitor for error messages. Simplifying your code can help you isolate the issue.
  • Resetting the Device: If needed, you can always reset the ESP32 to its default state and modify the boot configuration again.

· · ─ ·𖥸· ─ · ·

Your Projects, Truly Independent

I’ve been there: the late nights, the debugging, the triumph of a working MicroPython script. But the real magic, the true embodiment of the open-source spirit, is when your creation springs to life all on its own. We’ve walked through the simple yet powerful method to ensure your MicroPython script runs reliably on boot, transforming your ESP32 from a passive device into an active, self-starting member of your FOSS ecosystem. This isn’t just a hack; it’s a fundamental step toward building truly autonomous and dependable projects.

Want more insights, tips, and tricks to empower your open-source hardware and software endeavors? Don’t miss out on future articles that cut through the complexity and get straight to what matters.

Subscribe to the newsletter at https://www.samgalope.dev/newsletter/ and join a community passionate about making technology work for us, automatically.

Like what you’re reading?
Help keep DevDigest
free and caffeine-powered
—buy me a coffee on Ko-fi.

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments (

)

  1. Chuck Smullen

    Thanks for the suggestions you are sharing on this blog site. Another thing I would really like to say is always that getting hold of duplicates of your credit report in order to check out accuracy of any detail may be the first step you have to carry out in credit repair. You are looking to cleanse your credit reports from harmful details errors that spoil your credit score.

    1. Sam Galope

      Great insight! Checking your credit report for accuracy is definitely a crucial step in maintaining a healthy financial profile. Errors can impact your credit score more than most people realize, so staying on top of it is always a smart move.

      If you’re into tech projects, you might also find this ESP32 guide interesting:

      How to Monitor Soil Moisture Levels with an ESP32 and Soil Moisture Sensor using MicroPython

      Thanks for sharing your thoughts! 🚀

  2. Astrid Gebers

    Hello! Someone in my Facebook group shared this site with us so I came to look it over. I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers! Wonderful blog and terrific style and design.

    1. Sam Galope

      That’s awesome to hear! 🎉 Huge thanks to whoever shared it in your Facebook group. I’m glad you’re enjoying the content! If you’re into ESP32 projects, you might find this guide useful:

      How to Monitor Soil Moisture Levels with an ESP32 and Soil Moisture Sensor using MicroPython.

      Appreciate the bookmark and the tweet—every share helps spread the open-source love! 🚀 Let me know if you have any project requests.