原文地址::http://www.stm32cube.com/article/143
最常见的USB设备要数鼠标和键盘了,STM32F042F6P6这块小板(这里可购买,留言有优惠:购买链接)的鼠标示例已经写了,现在来写下模拟键盘的示例.
不多说,开始配置,打开STM32CubeMX,选择STM32F042F6P6芯片,开启pin脚映射,打开USB设备,选择USB设备为HID,设置按键和LED对应引脚的输入输出模式:
配置按键和LED引脚的状态及备注名:
可以在此修改USB设备名称、厂家、PID\VID等:
配置工程输出参数,然后生成并打开工程:
按图中所示打开usbd_hid.c文件,找到HID_MOUSE_ReportDesc数组定义处(默认生产HID设备为Mouse,这里数组名不影响,只要里面的描述符是键盘的就行),修改成如下数据:
0x05, 0x01, // USAGE_PAGE (Generic Desktop) //63 0x09, 0x06, // USAGE (Keyboard) 0xa1, 0x01, // COLLECTION (Application) 0x05, 0x07, // USAGE_PAGE (Keyboard) 0x19, 0xe0, // USAGE_MINIMUM (Keyboard LeftControl) 0x29, 0xe7, // USAGE_MAXIMUM (Keyboard Right GUI) 0x15, 0x00, // LOGICAL_MINIMUM (0) 0x25, 0x01, // LOGICAL_MAXIMUM (1) 0x75, 0x01, // REPORT_SIZE (1) 0x95, 0x08, // REPORT_COUNT (8) 0x81, 0x02, // INPUT (Data,Var,Abs) 0x95, 0x01, // REPORT_COUNT (1) 0x75, 0x08, // REPORT_SIZE (8) 0x81, 0x03, // INPUT (Cnst,Var,Abs) 0x95, 0x05, // REPORT_COUNT (5) 0x75, 0x01, // REPORT_SIZE (1) 0x05, 0x08, // USAGE_PAGE (LEDs) 0x19, 0x01, // USAGE_MINIMUM (Num Lock) 0x29, 0x05, // USAGE_MAXIMUM (Kana) 0x91, 0x02, // OUTPUT (Data,Var,Abs) 0x95, 0x01, // REPORT_COUNT (1) 0x75, 0x03, // REPORT_SIZE (3) 0x91, 0x03, // OUTPUT (Cnst,Var,Abs) 0x95, 0x06, // REPORT_COUNT (6) 0x75, 0x08, // REPORT_SIZE (8) 0x15, 0x00, // LOGICAL_MINIMUM (0) 0x25, 0x65, // LOGICAL_MAXIMUM (101) 0x05, 0x07, // USAGE_PAGE (Keyboard) 0x19, 0x00, // USAGE_MINIMUM (Reserved (no event indicated)) 0x29, 0x65, // USAGE_MAXIMUM (Keyboard Application) 0x81, 0x00, // INPUT (Data,Ary,Abs) 0xc0, // END_COLLECTION
再打开usbd_hid.h文件,修改HID_MOUSE_REPORT_DESC_SIZE的值为63.
编译工程,下载到板子上,插上USB线连接到电脑上,是不是识别出为键盘设备了呢?
继续修改main.c文件,添加头文件
#include "usbd_hid.h"
添加一个数组变量,用于传输键盘参数的,byte0是传控制键;byte1是保留键,不用改;byte3~byte7都可以存放传输的按键值
/* * buffer[0] - bit0: Left CTRL * -bit1: Left SHIFT * -bit2: Left ALT * -bit3: Left GUI * -bit4: Right CTRL * -bit5: Right SHIFT * -bit6: Right ALT * -bit7: Right GUI * buffer[1] - Padding = Always 0x00 * buffer[2] - Key 1 * buffer[3] - Key 2 * buffer[4] - Key 3 * buffer[5] - Key 4 * buffer[6] - Key 5 * buffer[7] - Key 6 */ uint8_t buffer[9] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
添加按键检测及传输键值到电脑的代码:
if(HAL_GPIO_ReadPin(KEY_GPIO_Port,KEY_Pin) == 0) { HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET); buffer[0] = 0x02; //shift buffer[2] = 0x04; // a USBD_HID_SendReport(&hUsbDeviceFS, buffer, 8); //send HAL_Delay(15); //delay buffer[0] = 0x00; buffer[2] = 0x00; USBD_HID_SendReport(&hUsbDeviceFS, buffer, 8); HAL_Delay(15); while(HAL_GPIO_ReadPin(KEY_GPIO_Port,KEY_Pin) == 0) HAL_Delay(15); } else HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET);
对应键值可和此文件中的HID Usage ID对应,是16进制(如字符‘a’对应键值为0x04),pdf文件在附件中有(USB_HIDtoKBScanCodeTranslationTable.pdf):
再编译文件下载到板子上,试试按下按键时是不是在电脑上就输入了一个大写的‘A’呢?