Hard fault when using USB HID with no USB connection

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
nedkonz
Posts: 24
Joined: Thu Aug 05, 2021 9:58 pm

Hard fault when using USB HID with no USB connection

Post by nedkonz » Thu Dec 23, 2021 1:04 am

I have an application that needs to send HID reports (joystick) when connected to a computer, but still has to work when not connected to a computer.

My Pyboard V1.1 is always powered from an external 5V power supply connected to V+.

However, when I start my program and it tries to send the first HID packet I get a hard fault if the USB isn't connected. If the USB is connected, everything works fine.

I haven't found a way to sense whether USB is connected; the PA9 (USB_VBUS) pin is high whether USB is connected or not (verified with an oscilloscope on R10). I've tried looking at various STM32 USB OTG_FS registers with no success.

My HID initialization code looks like this:

Code: Select all

	pyb.usb_mode('VCP+HID', hid=(1, 2, 3, 8,
		bytes([0x05, 0x01, 0x09, 0x04, 0xa1, 0x01, 0x09, 0x01,
					0xa1, 0x00, 0x09, 0x30, 0x09, 0x31, 0x09, 0x32,
					0x25, 0x7f, 0x15, 0x81, 0x75, 0x08, 0x95, 0x03,
					0x81, 0x02, 0xc0, 0xc0])))
and I send one-byte X, Y, Z HID packets like this:

Code: Select all

# Send joystick report. Values are -127 to +127.
# hid = pyb.USB_HID()
# hid.send((x, y, z))
Is there some way to avoid this hard fault? I don't have time to dig into this with my JLink.

Thanks!

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Hard fault when using USB HID with no USB connection

Post by pythoncoder » Fri Dec 24, 2021 9:15 am

This is how I do it.

Code: Select all

d_series = os.uname().machine.split(' ')[0][:4] == 'PYBD'
usb_connected = False
if pyb.usb_mode() is not None:  # User has enabled VCP in boot.py
    if d_series:
        # Detect an active debugging session
        usb_connected = pyb.USB_VCP().isconnected()
    else:
        usb_connected = pyb.Pin.board.USB_VBUS.value() == 1
Note that USB is configured as VCP. You say that USB_VBUS isn't working for you, so perhaps it doesn't work in HID mode. Is it possible to check the pin, then reconfigure USB as HID? I'm guessing wildly here as I have no experience with HID mode ;)
Peter Hinch
Index to my micropython libraries.

Post Reply