Boot Scripts

There are two important files that MicroPython looks for in the root of its filesystem.  These files contain MicroPython code that will be executed whenever the board is powered up or reset (i.e. it 'boots').  These files are:

  • /boot.py - This file is run first on power up/reset and should contain low-level code that sets up the board to finish booting.  You typically don't need to modify boot.py unless you're customizing or modifying MicroPython itself.  However it's interesting to look at the contents of the file to see what happens when the board boots up.  Remember you can use the ampy get command to read this and any other file!
  • /main.py - If this file exists it's run after boot.py and should contain any main script that you want to run when the board is powered up or reset.

The main.py script is what you can use to have your own code run whenever a MicroPython board powers up.  Just like how an Arduino sketch runs whenever the Arduino board has power, writing a main.py to a MicroPython board will run that code whenever the MicroPython board has power.

You can create and edit the main.py on a board using the file operations in ampy.  For example create a test.py on your computer and put the following Python code inside it:

###########################################################################
# Setup code goes below, this is called once at the start of the program: #
###########################################################################
import time
print('Hello world! I can count:')
i = 1

while True:
    ###################################################################
    # Loop code goes inside the loop here, this is called repeatedly: #
    ###################################################################
    print(i)
    i += 1
    time.sleep(1.0)  # Delay for 1 second.

Then copy the file to /main.py on a connected MicroPython board with ampy's put command:

ampy --port /serial/port put test.py /main.py

Reset the board or unplug it and plug it back in, then connect to the serial REPL and notice the board is counting numbers!  The main.py code started as soon as the board finished booting.

Putting all the pieces of this guide together you can see a simple workflow for MicroPython that's similar to Arduino & Arduino sketches:

  • Write Python code on your computer using your favorite text editor.  Structure the code so it puts setup code at the top and loop code inside a main loop.
  • Use the ampy run command with the --no-output option to run the script on the MicroPython board.
  • Edit and run the script as much as you need for it to work the way you expect.
  • When you want the code to automatically run on boot use the ampy put command to save the script as a /main.py file on the board.

That's all there is to loading files & running code on MicroPython boards!

Last updated on 2016-08-22 at 12.01.23 PM Published on 2016-08-22 at 12.02.25 PM