PROGRAMMING
Having to plug your microcontroller into your computer every time you make a software change gets tiresome. If the device has wifi, why not use that instead?
There are so many things about which people disagree. But there's one subject that brings us together to become of one mind. While it's wrong to be vindictive, whoever invented the micro-USB connector should be punished. Severely. Perhaps by being forced to use micro-USB on every device they own.
Micro-USB plugs and sockets are tiny, fiddly and work only one way up. And life gets even more complex when the device you're plugging into isn't conveniently to hand. This is the situation I now face with my Hestia robot project. The Raspberry Pi Pico 2W that is controlling its motors sits on the robot itself. Every time I want to update the firmware — which happens a lot at this early stage of development — I have to haul the robot on to my desk, or myself over to the robot, and fiddle about with a cable and that rage-inducing micro-USB connection.
You can add to that annoyance the issue of potential damage caused by frequent plugging and unplugging. USB sockets on PCBs are notoriously fragile. It's so easy to rip them off the circuit board. It's a lot harder to solder them back on. I know, I've tried.
However, the answer lies right there on the Pico itself. If you have the wifi-equipped 'W' variant, forget about feeding code to it through a USB cable and instead have it reach out over the local network and fetch the code for itself.
This kind of Over-The-Air (OTA) updating isn't worthwhile just for robots. Any device that can't easily be plugged into — such as Internet of Things (IoT) or home automation solutions that are in enclosures or difficult to reach places — benefit hugely from this approach. And updating becomes automatic rather than a chore.

Requirements
There are OTA upgrade solutions already. These include:
- senko: a small library that checks a GitHub repo (raw files) for a new version and overwrites your local files. It's the simplest option and works on the Pico W family. You host your code on GitHub, bump a version file and the device pulls the update.
- micropython-ota-updater: a more complete version of the same idea, with support for GitHub releases, version tracking and installing into a new directory before swapping, so a failed download doesn't brick the main code.
To be clear, I haven't tried either of these — they were suggested to me by web searches and maybe they are great. But I was put off by the use of GitHub repos. I didn't want to have to rely on services outside my local network. And while I could probably have used these solutions with the Gitea instance running on my NAS, overall this route seemed like too much overhead.
But for OTA updates you need something that can host and deliver the new files. And in the solution I adopted, that something is a web server.
I already have a web server for this project. It's a simple Docker-based Apache/PHP server that I'm currently running on my dev laptop but may be destined for my LAN's main server. That's the beauty of Docker — I can put the server anywhere I like and it's up and running in seconds. Indeed, another possibility I have in mind is a dedicated server for this project running on a Raspberry Pi. Right now, I really don't have to choose.
Within the file structure of the server I have a directory called firmware. And that's the entirety of the web server configuration. No scripts, no HTML—it just needs to host the files and be able to serve them in response to an HTTP request.
So this solution has three components. The first is the machine on which you're developing your MicroPython code. In my case, that's my laptop. The second is a web server. That' also my laptop. And the third is the Pico W board that can reach the web server. That's made easier (and safer) if everything is on the same LAN.
The process
The way it works is like this:
- You make changes to your code, in whatever editor your heart desires.
- You run a shell script in the project's base directory that copies the required MicroPython files (and one other) to a designated folder in the web server's file structure.
- When the Pico is powered up, it runs
main.pywhich establishes a wifi connection and interrogates the server to see if there are new files to download. If so, it downloads them. - The
main.pyprogram then hands control over to the main program file, which is called anything you want.
That 'one other' file in the second step is a manifest file containing a JSON array listing the files and their SHA-256 hashes. When the Pico powers up, it compares the hashes in the manifest file with hashes of the files it already has. If they are different, it assumes the files on the server are newer and downloads them. If it has downloaded new files, the microcontroller reboots in order to ensure it's using them. If there were no new files to download, it goes about its day unperturbed.
The script(s)
Let's talk first about the uploading of the program files from your dev machine to the web server. There are, in fact, two scripts, but as one calls the other, there's only one you need to run manually.
The first is a Python script I've named update.py. Its task is to create that manifest file (manifest.json) that contains details of the files that your microcontroller might want to download.
import hashlib
import json
import pathlib
FILES: list[str] = [
'config.py',
'hestia.py',
'ws_server.py',
'sensors.py',
'L298_motor_controller.py',
'ota.py',
'ssd1306.py',
]
manifest: dict[str, str] = {
f: hashlib.sha256(pathlib.Path(f).read_bytes()).hexdigest()
for f in FILES
if pathlib.Path(f).exists()
}
pathlib.Path('manifest.json').write_text(json.dumps(manifest, indent=2)) # pyright: ignore[reportCallIssue]
print('Generated manifest.json:', manifest)As you can see, you need to supply the names of all the files that the Pico needs and might want to update. These happen to be the ones for my project — yours will be different.
In case you're curious, the contents of the generated manifest.json file look something like this:
{
"config.py": "d938e0111facd9e29701cfa4b768934afbc7119cc6de364f98a4439ab03eb725",
"hestia.py": "5d14d3a586b22e8103cae21ab18697a6e2c65847a32ed67464e234d05550ee44",
"ws_server.py": "10ffb19633f062c06dca79164e984d20ca03bc28e89f3e70c9c01e7d89ead67f",
"sensors.py": "87d28830ba394f9511d2545a50ad5d9ff5d8767c8384a4edd5837cb01b8913c4",
"L298_motor_controller.py": "fb85b80d4a9b43bd01d19753808e950d9a93fd31d88995ed191c2ac104f7512b",
"ota.py": "a307feae856939a892fc343028349e2ed31dbc5cdb3f32768d0b11f716a49909",
"ssd1306.py": "0cf440d161d26dd146bc32e5ad17dc6fd9fb143173094e694fb904e66641648b"
}This is a simple JSON array with the filenames as keys and the SHA-256 hash of the file as a string value. This Python script creates the manifest.json file in the base folder of the project. But where it needs to be is in the file structure of the web server, so that's where the second script comes in.
This is a Bash/ZSH script I call update.sh (you might want to choose a more distinctive name):
#!/usr/bin/env zsh
set -euo pipefail # Exit immediately on any error or unset variable
SOURCE_DIR="."
TARGET_USER="smd"
TARGET_HOST="10.0.150.10"
TARGET_DIR="/Users/smd/Dev/PROJECTS/HESTIA/HESTIA_WEBSERVER/public_html/firmware"
TARGET_KEY="${HOME}/.ssh/ssh-key"
# Regenerate manifest.json
python3 update.py
# Extract filenames (JSON keys) from manifest.json into an array
# and append manifest.json itself to the upload list
files=( ${(f)"$(python3 -c 'import json; print("\n".join(json.load(open("manifest.json")).keys()))')"} )
files+=("manifest.json")
echo "Deploying ${#files[@]} files to ${TARGET_USER}@${TARGET_HOST}:${TARGET_DIR}..."
# Ensure target directory exists on remote/local host
ssh -i "${TARGET_KEY}" "${TARGET_USER}@${TARGET_HOST}" "mkdir -p '${TARGET_DIR}'"
# Upload all files in a single SCP batch (or use rsync for delta transfers)
scp -i "${TARGET_KEY}" "${files[@]}" "${TARGET_USER}@${TARGET_HOST}:${TARGET_DIR}/"
echo "Deployment complete"Both of these scripts live in the base folder of the project. When you've made changes to any of the Python program files, you go to a terminal (I use VS Code, so one is always available), make sure you're in the project base directory and run ./update.sh. When this runs, it invokes the Python script to create the manifest.json files. It then opens that manifest file with a one-line Python script to access the filenames and put them into an array. That means you have to maintain the file list in only one place—the Python script. The shell script also adds the manifest.json filename to the list. It then checks to see that the target directory, where we plan to copy these files (ie, on the web server) is reachable and, if it is, copies the files using scp. (That, and the directory check, depend on having a suitable SSH key, but that's outside the scope of this article.)
So, just invoking one script ensures that the files on the web server are up to date. This works great on Linux and MacOS. I'm not sure how you'd do this on Windows. You could always do it manually somehow, and as this is just about putting files in the right place it doesn't affect the rest of what we're discussing here. All the rest of the code for this article is for the Pico and so doesn't care what OS you prefer.
Project structure
If you're familiar with MicroPython projects on the Pico you'll know that the standard approach is to call your primary program file main.py. The MicroPython system looks for this on booting and runs it automatically.
And that's exactly what I'd been doing with my Hestia robot project. The main.pyfile for this is fairly complex, running a WebSocket server, UART interface, serial interface over USB, an OLED display, interpreting commands, controlling motors, reading sensors and more. I'm not bragging, I'm just pointing out that this was pretty much a completed project before I decided to bolt on OTA updates. And the changes to that code in order to make that happen were negligible. In fact, the only thing I had to do to main.py was change its name. I chose hestia.py, but it could have been anything.
That's because we need a new main.pywhich acts purely as a bootstrap program. It handles connecting to the wifi, checking for new files and, if necessary, updating before handing off to the star of the show (hestia.py in my case). One important thing to note about this new main.py: it's the one piece of code we won't be able to update over the air. You can do that, but it's risky. The more robust solution is to treat main.py as immutable, once you have a working version. You upload it to the Pico the same way you have been doing—over a USB cable—and then never touch it again.
Main tasks
The first task for main.py is to connect to the wifi. I'd previously been handling that in the WebSocket library and this led to the one change I chose to make to the primary code (we'll get back to that in a moment).
This connection routine takes up most of the file. It could be a lot simpler. It's just that a wifi connection is so crucial to this project that I want the best chance of getting one. So the code will make multiple connection attempts, allowing up to 15 secs for each to take effect.
The wifi object exists as a class property inside a class called Config. This contains a number of constants and settings I use across the project and the config.py file in which it lives gets imported into many of the project's other Python files. This way, I can share the wifi connection throughout the project. To give you an idea of what I mean, this is part of that config.py file:
from micropython import const
from network import WLAN
class Config:
"""
Basic configuration constants and default values.
"""
wlan: None | WLAN = None # Will be populated by main.py
WIFI_SSID: str = 'myssid' # Your wifi SSID goes here
WIFI_PASS: str = 'mypass' # Your super-secret wifi password
MAX_CONN_TRIES: int = const(20) # how many times we'll try to connect
WIFI_CONN_WAIT: int = const(15) # secs we'll wait for wifi to connect
OTA_SERVER_ADDR: str = 'http://10.0.150.10:8100' # my Macbook
OTA_DIR: str = 'firmware'Aside from the wlan variable, config.pyalso contains our wifi credentials plus the URL and folder name for the web server.
Once connected, we assign the connection to Config's wlan object and then import a new file, ota.py. We'll go into the details of that later but for now we just need to know that the program flow is temporarily handed to that file.
if wlan.isconnected():
Config.wlan = wlan # Hand off active interface to Config
import otaWe run a function in that file called ota.check_and_update() which returns True if all went well and False otherwise. As the name of the function suggests, that's where the OTA magic happens, but for now we just need to know if it happened. If it did, we reboot the microcontroller. If not, we carry on as if nothing has happened.
Except for the exceptions. The code in ota.py will raise exceptions in certain cases—for example, if something went badly wrong in moving new, downloaded files into place. If that happens, we ensure that the wifi connection is safely handed over and move on with our lives.
Whatever happens, we do a little tidying up and then import hestia.py to hand control over to that file.
import hestia # noqa: E402, F401(By the way, the # noqa: E402, F401comment is a way of getting Pylance in VS Code to stop shouting at me about the fact we're using an import statement at the end of a file instead of the beginning. It has no implications for the program itself.)
Here's the whole main.py file:
"""
main.py bootstrap program.
"""
import gc
import sys
import time
import machine
import network
from config import Config
def run_ota_boot() -> None:
"""
Make wifi connection and check for OTA updates.
"""
wlan = network.WLAN(network.STA_IF)
try:
# Clear any lingering CYW43 / lwIP state from a previous soft-reset
if wlan.active():
wlan.disconnect()
wlan.active(False)
time.sleep_ms(300)
wlan.active(True)
time.sleep_ms(500)
tries: int = 0
while not wlan.isconnected() and tries < Config.MAX_CONN_TRIES:
tries += 1
wlan.connect(Config.WIFI_SSID, Config.WIFI_PASS)
# Wait for up to a certain period for wifi to connect
timeout: int = Config.WIFI_CONN_WAIT
while timeout > 0 and wlan.status() not in (
network.STAT_GOT_IP,
network.STAT_CONNECT_FAIL,
network.STAT_NO_AP_FOUND,
network.STAT_WRONG_PASSWORD,
):
time.sleep(1)
timeout -= 1
if wlan.isconnected():
Config.wlan = wlan # Hand off active interface to Config
import ota
if ota.check_and_update():
time.sleep_ms(200)
machine.reset()
else: # if offline, skip OTA and boot normally
pass
except Exception as e:
# Keep wlan attached if it is still connected so hestia.py can use it
if wlan.isconnected():
Config.wlan = wlan
finally:
# Unload modules no longer needed to save memory
for mod in ('ota', 'urequests', 'requests'):
sys.modules.pop(mod, None)
gc.collect()
run_ota_boot()
# Hand over control to the main application
import hestia # noqa: E402, F401Other than the way it imports config.py, there's really nothing project-specific in there and i can use this same main.py file for pretty much any application. The only thing that needs adjusting for each project is the name of the file it imports at the very end, and you could always standardise on something for that (perhaps app.py).
Handing over control
What if the initial connection to wifi failed? We still hand control to hestia.py because in this project that code (via the WebSocket server) will have another crack at it.
When I originally created this OTA updating functionality, I made no changes to the main application code at all. Instead, I had the new main.py tear down the wifi connection it had created so that hestia.py could start it up again cleanly. This wasted a few seconds on initial boot, but it meant that the primary code would need no changes if I ever decided to remove the OTA stuff.
But then I realised there was another way. I made one small change to the WebSocket library so that it checks to see if there is already a valid wifi connection. If so, it uses that. If not, it creates one. The library remains functional with or without this OTA functionality. That's a detail I'll cover more fully when I write about the Hestia project specifically.

Over the air
Now let's take a look at what happens inside that ota.py file that gets imported into main.py. Here's the whole thing:
import gc
import hashlib
import json
import os
from binascii import hexlify
import urequests
from config import Config
REMOTE_DIR: str = f'{Config.OTA_SERVER_ADDR}/{Config.OTA_DIR}/'
def _sha256_file(path: str) -> str | None:
"""
Stream-hashes a local file in 1KB chunks to avoid large RAM spikes.
"""
try:
h = hashlib.sha256()
with open(path, 'rb') as f:
while True:
chunk = f.read(1024)
if not chunk:
break
h.update(chunk)
return hexlify(h.digest()).decode()
except OSError:
return None
def _get(name: str) -> bytes:
r = urequests.get(REMOTE_DIR + name, timeout=5)
try:
if r.status_code != 200:
raise OSError(f'HTTP {r.status_code} for {name}')
return r.content
finally:
r.close()
def _safe_replace(src_new: str, dst: str) -> None:
"""
Safely replaces dst with src_new on LittleFS where os.rename()
fails if dst already exists.
"""
bak: str = dst + '.bak'
has_bak = False
try: # remove any existing backup file. Will fail if there is no file.
os.remove(bak)
except OSError:
pass
try:
# Rename the existing file to a backup file. Will fail if no such file.
os.rename(dst, bak)
has_bak = True # If we got here, it worked
except OSError:
pass # dst didn't exist yet (new file)
try:
# Rename the new file to take the place of the old one.
os.rename(src_new, dst)
if has_bak:
# If the renaming succeeded, remove the backup file, it's not needed
os.remove(bak)
except Exception:
# Roll back if moving the new file into place failed
if has_bak:
try:
os.rename(bak, dst)
except OSError:
pass
# This is a failure to update, to raise an exception for main.py to
# deal with.
raise
def check_and_update() -> bool:
"""
Get the manifest file, check if any files need updating and, if so,
update them.
"""
manifest: dict[str, str] = json.loads(_get('manifest.json'))
staged: list[str] = []
try:
for name, want_hash in manifest.items():
if _sha256_file(name) == want_hash:
continue
data: bytes = _get(name)
actual_hash: str = hexlify(hashlib.sha256(data).digest()).decode()
if actual_hash != want_hash:
raise OSError(f'SHA-256 mismatch for {name}')
tmp_name: str = name + '.new'
with open(tmp_name, 'wb') as f:
f.write(data)
staged.append(name)
del data
gc.collect()
except Exception:
# Roll back any staged .new files on partial failure
for name in staged:
try:
os.remove(name + '.new')
except OSError:
pass
# Even if we succeed in rolling back, this is an update failure so
# raise an exception for main.py to deal with
raise
# Commit all verified files
for name in staged:
_safe_replace(name + '.new', name)
return bool(staged)As you can see, there is just one main function and a bunch of little helpers. Comments in the code explain what they do, but the key concepts are that the code fetches the manifest.json file and iterates through the entries in its array.
for name, want_hash in manifest.items():
if _sha256_file(name) == want_hash:
continueThis code extracts the filename and SHA-256 hash (as name and want_hash) from each entry and compares the latter with a hash of the file with the same name that it already has. If the hashes are identical then there has been no change and so the code goes on to the next item in the list.
Otherwise, it downloads the file into memory (data: bytes = _get(name)) and compares a hash of the downloaded bytes to the hash provided by the manifest file. If they are different then there was either an issue with the download or a fault in the manifest file. Either way, that's a problem so we raise an exception.
By the way, the hashing of the new code is done in stream fashion rather than one big operation in order to be kind to the microcontroller's memory.
If all is fine, the bytes are written out as a new file with '.new' appended to the filename. We're not directly overwriting the old file, but 'staging' the new files first. This is a more robust solution should there be any glitches. The filename is added to the staged array, the bytes are deleted (to save memory) and garbage collection invoked.
Then we iterate through the staged file list (which will contain only those files that need replacing) and call _safe_replace()on them. This function backs up any existing file, renames the '.new' version to the proper filename (overwriting the old version) and then deletes the backup.
You'll notice the liberal use of try...except blocks. With the LittleFS file system used by MicroPython, some of the actions we're performing can raise exceptions in certain circumstances. For example, let's say we have a new file called library.py that doesn't yet exist on the Pico. Attempting to run os.rename() on a non-existent file will cause an error, so we need to deal with these cases even though they aren't really faults as such.
There are, however, some situations that represent a failure in the process. In these cases, we use raise to raise an exception that will be caught by main.py.
Separate and isolated
One question you may have is this: if the whole of the ota.py file is imported into main.py and its one function executed there, why not just put all this code into main.py itself and have done with it?
And the answer is that you could do that. However, there are certain advantages to keeping the files separate.
Arguably the most important of these is that OTA updates can update ota.pyitself. When ota.py is running, it's already in memory so it's fine to overwrite the stored code. However, because main.py is the hardware boot entry point, overwriting it over the air is risky: if power drops mid-write or a syntax error slips into main.py, the board can lose its boot/recovery path until plugged into USB. Keeping main.py minimal and immutable while putting the update logic in ota.pylets us safely include ota.py in manifest.json and update the OTA logic remotely.
Second, there are RAM lifecycle benefits to do with reclaiming bytecode memory. In main.py, the import ota instruction happens inside the if wlan.isconnected()branch — so if the Pico boots offline, the ota module is never even compiled or loaded into RAM. Even when online, keeping ota as a module lets us explicitly unload it before import hestia.py, freeing the compiled bytecode and module dictionary from heap RAM before the main program's object buffers spin up.
Third, there's fault isolation. Because import ota sits inside a try...except, if ota.py ever gets corrupted or has a bug introduced during an update, main.pycatches the error cleanly and still boots hestia.py, so the main program remains operational. If merged into main.py, a syntax error anywhere in the OTA functions would prevent main.py from parsing at all.
Not covered
There are two major elements that I've only lightly touched on so far and which are worth reiterating. And it's because they don't matter.
The content of hestia.py (or whatever name you give your main program file) is not affected by this OTA process. So you can use these procedures with anything.
And, as I alluded to earlier, there's nothing special about the website that's hosting the files. So long as your update script can write to its file structure and the Pico can reach it, that's all that matters. In fact, if the server is running on your dev machine (as mine currently is), you don't need to use scp in the update script. A simple copy command would work just as well.
Adaptability
If this feels complex … well, it really isn't. Once you've got it working, the main.py and ota.py files and the update script need very little work to adapt them from one project to another.
There is one slight gotcha. The URL of the server is held in the config.py file. If the server address changes, and that file is modified accordingly, the microcontroller will be working with an out of date configuration. The workaround is to modify the config.py file with the new server address, but upload it (and any other changed files) to the existing server first. The microcontroller will access the old server, get the new config.py file and will switch to the new server on the next update.
Alternatively, you can just upload the new config.py file via USB because you're not going to be doing this very often. Or maybe you can think of a smarter method.
An additional benefit of this approach is flexibility. For example, maybe you have multiple copies of a project. (I have five homemade IoT thermometers that could have benefitted from this technique.) Pushing one set of updated files means all the devices will update, either when you power cycle them or because you've been smarter than me and have built periodic checks into the firmware.
For my robot project, I now have the advantage of being able to work on the code and testing it on a spare Pico while lying on the sofa. (A surprising proportion of my coding activity is sofa-based.) Then, the next time I turn on the robot, it automatically updates. It's akin to magic.
Steve Mansfield-Devine is a freelance writer, tech journalist and photographer. He has written extensively about technology for UK magazines and newspapers and for 15 years was the editor of two professional journals covering cybersecurity. You can follow him on Bluesky or Mastodon.
Steve also writes about photography for Cameralux on Medium, and you can view his photography portfolio or buy his books and e-books at Zolachrome.
Or you can buy Steve a coffee — it helps keep these projects going.