USB Class In Function: Sending Keycodes to Host
The usb_class_in() function handles sending keycodes from a USB device to a host after the device is properly configured and the USB is ready.
Steps:
-
Configuration Check: The function first verifies if the USB device is configured using the
DeviceStatevariable. If not, it returns immediately. -
Idle State and Key Press Check: It then checks if the USB is idle (
UsbInBusy) and if a key press event has occurred (fKeyOK). -
Initialization:
fKeyOKis set to 0 to indicate that the key press has been processed.- The
keyarray is cleared, ensuring a clean transmission buffer.
-
Keycode Mapping: Based on the
bKeyCodevalue, which represents the combination of pressed keys on pins P3.2 to P3.5, thekeyarray is populated with the corresponding keycodes. This mapping is essential to translate the device's physical button presses into standardized keycodes recognized by the host.- For example, if
bKeyCodeis 0x0e (P3.2 and P3.3 pressed),key[2]is set to 0xE0 (Ctrl keycode) andkey[3]is set to 0x06 (C keycode).
- For example, if
-
Transmission:
- The USB is temporarily disabled (
EUSB = 0). UsbInBusyis set to 1, indicating that the USB is now transmitting data.- The
usb_write_reg()function is used to write data to specific registers: INDEX, FIFO1, and INCSR1. This function is crucial for controlling the USB communication. - The keycodes are sent to the host via the FIFO1 register in a loop.
- The INCSR1 register is set to INIPRDY, signaling that the data is ready to be sent.
- Finally, the USB is re-enabled (
EUSB = 1).
- The USB is temporarily disabled (
The scan_key() function continuously monitors the state of P3.2 to P3.5, triggering a key press event when a change is detected.
Steps:
-
Key Status Acquisition: The function obtains the current state of P3.2 to P3.5 pins using bitwise operations and stores the value in the
keysvariable. -
Change Detection: It compares the current key state (
keys) with the previous state (prevKeys). If there's a difference, it signifies a key press event. -
Key Press Handling:
- The
prevKeysvariable is updated with the current key state. - The
bKeyCodevariable is set to the current keycode. - The
bKeyDebouncevariable is initialized to 20, establishing a 20ms debounce delay to filter out spurious button press events.
- The
-
Debouncing:
- If
bKeyDebounceis not zero, it indicates that the debounce delay is still active. The value is decremented until it reaches 0, after which thefKeyOKflag is set to 1, signifying that a valid key press event has occurred.
- If
原文地址: https://www.cveoy.top/t/topic/PJV 著作权归作者所有。请勿转载和采集!