Emulate STM32F103 as a MOUSE
This is another tutorial in the USB Series of STM32, and today we will see how to use STM32F103C8 as a mouse. This is not limited to F103C8, you can use any other STM32 Device, which have the user USB port available. Basically this tutorial is an example of USB HID DEVICE.
I will be using the ADXL345 accelerometer sensor to get the acceleration in x and y axis, and based on these acceleration values the mouse will move. I am going to attach one button on the breadboard, so that we can get the left click functionality. You can attach one more button for the right click if you want to. You can see the connections below
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.
I2C Setup for ADXL345
I2C1 is selected for ADXL345, and rest is default setup
I have selected Pin PA7 for the button, and so using external interrupt here. Button is also connected to 3.3V supply, and that’s why I am using a pull down here.
Above are the ADXL related functions, and i have already covered them before. You can read more about them here
Calibration is needed so that we can use the mouse in different orientations. Basically it will sample 50 values in 5 seconds, and then set the max and the min values. Once the calibration is complete, the LED on BluePill will turn ON.
USB MOUSE RELATED
I have created a structure here, to save the mouse parameters.
In the EXTI Callback function, we will just update the flag. The rest of this processing will be done in the while loop.
Here is our while loop
Basically we read the RAW acceleration values from the sensor and then do the processing
- if the value is higher than the max value, or lower than the min value, we save it to the mouse structure
- in the end we send this structure as a part of the HID report.
- The sensitivity can be controlled by dividing the newval (newval/3). The higher the divisor, the less sensitive will be the mouse
- if the button is clicked, we send the button =1 report, and 50 ms later button =0 report to indicate the release of the button.
- you can modify this button to send button =2 for the right click.