STM32 USB HOST HID
This is another tutorial in STM32 USB series, and today we will see How to use STM32 as a USB HOST to interface Human Interface Devices (HID). I will use both the Mouse and the Keyboard for this tutorial, and their results will be printed on the serial console.
Let’s start by setting up the cubeMX
CubeMX Setup
First of all we need to select the USB_OTG_FS in Host Only mode. Also make sure you activate the VBUS, as the USB devices mostly don’t have the Power supply, and that’s why VBUS will provide the required power to such devices.
Next, select the USB_HOST and select the class as HID CLASS. Leave everything here to default.
Setup the Uart so that we can see the data output on a serial console.
And now we need to enable the voltage supply to the VBUS pin. To do that you need to look at the user manual for your board. I am using STM32F4 discovery board, and it have the following diagram for the USB
As you can see above, the VBUS is powered from the PC0 pin. But PC0 is connected to the EN Pin, which is an active Low pin. This means in order to supply the voltage to the VBUS, we must Pull down the PC0 Pin, or basically Set it LOW.
The final PINOUT is as shown above
- UART2 is connected to PC, so that we can see the output for the debugging purpose
- PC0 is set as output, to enable the voltage to the VBUS
- USB Pins are automatically selected, when you select the USB HOST
Some insight into the CODE
void USBH_HID_EventCallback(USBH_HandleTypeDef *phost)
{
if(USBH_HID_GetDeviceType(phost) == HID_MOUSE) // if the HID is Mouse
{
HID_MOUSE_Info_TypeDef *Mouse_Info;
Mouse_Info = USBH_HID_GetMouseInfo(phost); // Get the info
int X_Val = Mouse_Info->x; // get the x value
int Y_Val = Mouse_Info->y; // get the y value
if (X_Val > 127) X_Val -= 255;
if (Y_Val > 127) Y_Val -= 255;
int len = sprintf (Uart_Buf, "X=%d, Y=%d, Button1=%d, Button2=%d, Button3=%d\n", X_Val, Y_Val, \
Mouse_Info->buttons[0],Mouse_Info->buttons[1], Mouse_Info->buttons[2]);
HAL_UART_Transmit(&huart2, (uint8_t *) Uart_Buf, len, 100);
}
if(USBH_HID_GetDeviceType(phost) == HID_KEYBOARD) // if the HID is Mouse
{
uint8_t key;
HID_KEYBD_Info_TypeDef *Keyboard_Info;
Keyboard_Info = USBH_HID_GetKeybdInfo(phost); // get the info
key = USBH_HID_GetASCIICode(Keyboard_Info); // get the key pressed
int len = sprintf (Uart_Buf, "Key Pressed = %c\n", key);
HAL_UART_Transmit(&huart2, (uint8_t *) Uart_Buf, len, 100);
}
}
Whenever a HID Data event is detected, HID_EventCallback function will be called, and our entire program lies inside it
- In case if the device is HID MOUSE, we will print it’s movement on the serial console. Along with the buttons we press.
- If the device is HID keyboard, then the key pressed will be sent to the serial console
Result