Auto disable USB storage unless key held on boot [keybow2040]

Is there a way we can automatically dismount the CIRCUITPY USB storage unless a particular key is held while when the device is plugged in?

I’ve been looking at doing this myself but am obviously concerned about getting any code wrong as I could lock myself out of the device completely if I permanently disable the USB storage.

I’ve put the following code in a file called boot.py in the root directory of CIRCUITPY:

import board
import time
import storage
import usb_cdc
from keybow2040 import Keybow2040

i2c = board.I2C()
keybow = Keybow2040(i2c)
keys = keybow.keys

#if not keys[0].held: #Use below line while testing to avoid lockout
if keys[0].held:
	storage.disable_usb_drive()  #disable storage
	usb_cdc.disable()  #this method also worked for others on hid keyboards

While testing, the code above should only disable the USB drive if key[0] is held on boot (to prevent lockout).

However, the code doesn’t do anything and the device just mounts as normal.

I’d be very grateful if anyone can point out what the issue with the code is. Thanks!

EDIT: No errors are thrown in boot_out.txt when running the code above. I does automatically add 1 line to this file with “boot.py output:”

I clip and pasted this from another thread, not sure if it was here of not, can’t find it now.
I do believe it was for the Keybow 2040. I haven’t tried it myself, just saved it in case i wanted to try it on my PICO RGB Keypad.

#disable the USB mass storage device from "enumerating"


import board
import digitalio
import storage

button = digitalio.DigitalInOut(board.SW15)
button.pull = digitalio.Pull.UP

if button.value:
    storage.disable_usb_drive()
1 Like

Thanks for the reply. Just tested, this seems to be working for me.

However, it appears to do the reverse of what is expected.

If I hold down key 15 when the device is plugged in the device it mounts. If I plug in normally it doesn’t show.

if button.value:
    storage.disable_usb_drive()

From the above statement shouldn’t the opposite happen?

EDIT: Sorry, got the above the wrong way around. I’ve corrected. This is actually what I need it to do but I’m not sure why.

I guess it’s behaving as it should but I had in mind “keybow.keys” from my original rather than “digitalio.Pull.UP” for the if statement. I think that’s why it appeared (to me) to be doing the opposite. Doh!

I’ve adapted your code so it’s now key[0] that should be held to match my original. Thanks again for your help.

import board
import digitalio
import storage

button = digitalio.DigitalInOut(board.SW0)
button.pull = digitalio.Pull.UP

#disable the USB mass storage device from "enumerating" unless
if button.value:
    storage.disable_usb_drive()

The person that originally posted it did it because they weren’t allowed to plug in USB thumb drives at work. So he had to hide it etc. I had plans to test it but couldn’t find my round 2it. ;)