Tutorial AutoRun

From Sketching with Hardware at LMU Wiki
Jump to navigation Jump to search

Run your MicroPyton code directly at Boot-up of ESP32/ESP8266

In this part of the tutorial, we talk about the boot process and how to start your own code at boot-up time. For this, we show how to use 'main.py' as entry point. We have an example how to use a Pin/switch to select whether to boot into your code or to not start a program.

We also look at how to use the uPyCraft IDE when autorun code, basically how to connect with Putty (or any terminal program) to remove main.py to be able to connect again with uPyCraft IDE.

Success criteria

  • you understand the boot process works (boot.py then main.py)
  • you have written some code and configured the ESP32 so that it is executed at boot time automatically
  • you have written a main.py that allows to select whether to boot into your code or not

Required Module and Files

To enable autorun you have to create a file that is called 'main.py' that is in the main directory. There are different ways to do this:

  • write the code you want to execute into the file main.py
  • write your code as a module that can be executed by calling a function. call this function from main.

Related Components

The components are related to the LMUBox. For more components, see the Hardware List. Many of the pages on actuators and sensor include additional examples.

Microcontroller

Sensors (and physical controllers)

Instructional Videos

How to Autorun MicroPython code

This shows how to use main.py as entry point to shart your MicroPython code. It looks at how to stop a running program with a terminal program (e.g. Putty). We introduce how to add a boot selector switch.

There is a video on Youtube (29:23) that shows the software: https://youtu.be/kzgUN_h1bqw


Examples of main.py

Code Example: code in main.py

 1 # main.py - example how to have the code directly in the main.py file
 2 # here an example for blinking an LED
 3 from machine import Pin 
 4 from time import sleep
 5 p25 = Pin(25, Pin.OUT)
 6 
 7 while True:
 8     pin25.on()
 9     sleep(1)
10     pin25.off()
11     sleep(0.5)

Code Example: function in module and called from main.py

1 # main.py - example how to call a function (with your code) from the main.py file
2 # we assume you have a function mymain() defined in a module mycode.py
3 import mycode
4 mycode.mymain()

Code Example: selectively call function in module from main.py - boot switch

BootSelektor.JPG

 1 # main.py - example how to call a function (with your code) from the main.py file
 2 # the function is only called if Pin26 is '1' (connected to 3.3V)
 3 # if Pin26 is '0' the function will not be callwd
 4 # we assume you have a function mymain() defined in a module mycode.py
 5 import mycode
 6 from machine import Pin
 7 
 8 p26 = Pin(26, Pin.IN)
 9 
10 if (p26.value()==1):
11     mycode.mymain()