How to use STM32 as a KEYBOARD
I have already covered the tutorial on emulating the BluePill (F103C8) as a mouse. This tutorial will cover another HID example, and today we will see how to use STM32F103C8 as a keyboard for the computer.
Well some part of this tutorial will be identical to the mouse one, but we need to modify the rest of it. so let’s start by setting up the CubeMX.
I am creating this project in CubeIDE, and the following is the setup required in CubeMX
In the picture above, I have selected the USB Device HID class. Everything else is kept default. That’s basically all for the Cube setup. Generate the project now
We need to modify some pre generated library files. So go to Middlewares -> ST -> STM32_USB_Device_Library -> Class -> HID -> src and open usbd_hid.c file as shown below
In usbd_hid.c file, locate the function USBD_HID_CfgFSDesc. Here we need to change the Interface Protocol from mouse to keyboard. The CubeMX always generate the protocol for mouse (0x02) by default, and to use it as a keyboard (0x01) , we need to change this to 0x01 as shown below
Now go down to the function HID_MOUSE_ReportDesc. It have the report descriptor for mouse by default, and we need to replace them with the keyboard descriptor. You can download the Keyboard Descriptor from HERE. Check the image below
Locate the HID_MOUSE_REPORT_DESC_SIZE. It must be 74 by default, for the mouse descriptor. Change it to 63 (Keyboard descriptor size).
This completes the setup part for this tutorial. Now let’s see the code now
Some insight into the CODE
First of all I am going to create a structure to store the values for the keyboard.
The above structure is as per the protocol used in keyboard. The picture for the protocol is shown below. You can download the PDF from HERE
Now let’s say I want to send the ‘AB’ to the computer, i will the use code mentioned below
- First press the left shift Modifier
- then press ‘A‘ and ‘B‘
- send the report
- release the Modifier, release ‘A’ and ‘B‘ also
- send the report again
- we can send 6 Key Codes at once, so it’s like pressing 6 keys at the same time. Although I have only used 2 keys here
The keycode for each key in mentioned in the PDF HERE
The code can be downloaded at the bottom of this article, and it contains the Keypad part also. If you are just using the MCU alone to send data as keyboard, you can ignore the Keypad part. To know more about using keypad, see the video mentioned below in the result section
You can see above that the MCU is being detected as STM32 Keyboard, and also the ‘AB‘ is printing every 1 second
- How to communicate between HC-12 using STM32 October 5, 2020
- How to use STM32 as a KEYBOARD September 28, 2020
- Emulate STM32F103 as a MOUSE September 8, 2020
- Send and Receive data from the WebServer using STM32 August 8, 2020
- Interface BMP180 with STM32 July 26, 2020
- STM32 USB HOST HID July 21, 2020