Reputation: 2025
For a upcoming project I have a need for a microcontroller that can "self update" - load new code and logic at runtime. So far my thoughts where that I would use two ESP devices, one as the "version controller/updater" and the other one for logic. Recently I came upon the Raspberry pico and saw that it was using micropython that basically uploads python files to pico "storage". I am unfamiliar with this system, but would I be right to presume that it could just "create" these files on it's own and execute as it seems they are interpreted by some micropython loader? Google doesn't really have any results on this.
Upvotes: 0
Views: 246
Reputation: 6284
MicroPython source code that you place in your board's flash memory is interpreted at runtime, and MicroPython has access to the filesystem on the flash memory, so the answer is yes: you can create or modify Python code in files on the device's filesystem and then execute them.
Here is a quick example I have tested in the Wokwi online emulator; I haven't tested it on a real board but have no reason to believe it would behave differently:
import time
import os
time.sleep(0.1) # Wait for USB to become ready
os.mkdir('foo')
with open('foo/foo.py', 'w') as f:
f.write('print("foo!")')
from foo import foo
When you run this it prints foo!
to the MicroPython console.
You can run MicroPython on ESP8266 (depending on memory) and ESP32 boards as well as on the Pico, so you might not even need to switch hardware if you are already using the ESP. The MicroPython documentation describes the differences between boards.
Allowing your code to download and run external code creates a potential security vulnerability of course, so you should consider whether this is an issue in your project.
Upvotes: 2