Arduino Due Keyboard Controller
This example demonstrates the use of the KeyboardController library.
Keyboard Controller
The Arduino Due has the ability to act as a USB host for peripherals such as a keyboard connected to the SerialUSB port. This example demonstrates the use of the KeyboardController library.
Hardware Required
- Arduino Due Board
- USB keyboard (note that keyboards that connect through an internal USB hub, like Apple keyboards, will not work)
- Arduino IDE (online or offline).
- USBHost library
Code
1/*2
3 Keyboard Controller HID Example4
5 Shows the output of a USB Keyboard connected to the USB6
7 controller of an Arduino Due Board.8
9 created 8 Oct 201210
11 by Cristian Maglie12
13 */14
15// Require keyboard control library16#include <KeyboardController.h>17
18// Initialize USB Controller19
20USBHost usb;21
22// Attach keyboard controller to USB23
24KeyboardController keyboard(usb);25
26// This function intercepts key press27void keyPressed() {28
29 Serial.print("Pressed: ");30
31 printKey();32}33
34// This function intercepts key release35void keyReleased() {36
37 Serial.print("Released: ");38
39 printKey();40}41
42void printKey() {43
44 // getOemKey() returns the OEM-code associated with the key45
46 Serial.print(" key:");47
48 Serial.print(keyboard.getOemKey());49
50 // getModifiers() returns a bits field with the modifiers-keys51
52 int mod = keyboard.getModifiers();53
54 Serial.print(" mod:");55
56 Serial.print(mod);57
58 Serial.print(" => ");59
60 if (mod & LeftCtrl)61
62 Serial.print("L-Ctrl ");63
64 if (mod & LeftShift)65
66 Serial.print("L-Shift ");67
68 if (mod & Alt)69
70 Serial.print("Alt ");71
72 if (mod & LeftCmd)73
74 Serial.print("L-Cmd ");75
76 if (mod & RightCtrl)77
78 Serial.print("R-Ctrl ");79
80 if (mod & RightShift)81
82 Serial.print("R-Shift ");83
84 if (mod & AltGr)85
86 Serial.print("AltGr ");87
88 if (mod & RightCmd)89
90 Serial.print("R-Cmd ");91
92 // getKey() returns the ASCII translation of OEM key93
94 // combined with modifiers.95
96 Serial.write(keyboard.getKey());97
98 Serial.println();99}100
101void setup()102{103
104 Serial.begin(115200);105
106 Serial.println("Program started");107
108 delay(200);109}110
111void loop()112{113
114 // Process USB tasks115
116 usb.Task();117}
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.