Saturday, July 23, 2022

Micropython - Safety pin to avoid soft-bricking

 I ran into an issue on an Arduino Connect Nano RP2040 board this last week where I got some code in main.py that caused micropython to hang without functional serial or shared drive, so I had no way to change the code and fix it. 

It was a little difficult to fix this.  A few things I tried:

  • Re-flash the micropython uf2 - this doesn't wipe the main.py and other code, so the problem remains.
  • Flash circuitpython uf2 - circuitpython stores code at a different addr and works perfectly when flashed, but when you put micropython back, the old broken main.py remains.  I even tried to dd a large random data file to the circuitpython shared folder, but somehow it didn't overwrite the micropython content!
  • Flash the various nuke uf2 files - It seems that these are all set up for the pi pico, which has 4MB of storage.  The arduino board has 8MB of storage and the area micropython uses is unaffected. 
What did finally work!
  • Flash the OpenMV customized version of Micropython.  It didn't load the main.py and exposed the same memory/file share that micropython uses so I was able to rename the broken main.py and flash standard Micropython back onto the board to resume working on it!
  • https://github.com/openmv/openmv/
And how to avoid this in the first place - It's surprisingly easy to hang micropython when experimenting with PIO and other stuff with blocking functions. The solution I'm using now is to source a file that checks if a pin is grounded.  If it is, it calls sys.exit() so the program quits instead of continuing and triggering another hang. 

main.py:

import saftey_pin
...
...


safety_pin.py:

from machine import Pin
import time
import sys

PIN_NUM = 25
SAFETY_PIN = Pin(PIN_NUM, Pin.IN, Pin.PULL_UP)

print(f"Checking Safety Pin {PIN_NUM}...")
time.sleep(.1)
if not SAFETY_PIN.value():
    print("PIN Shorted to Ground!")
    print("Aborting loading and quitting.")
    sys.exit()


 To use it, I put a key between the two pins shown here and plug the board into the usb port:



No comments: