Hardware Reference
In-Depth Information
39 String sentence = "";
40 bool waitforkey = true;
41
42 while (waitforkey == true)
43 {
44 // Process USB tasks
45 usb.Task();
46
47 // Look for valid ASCII characters
48 if (curkeycode >= 97 && curkeycode <= 122)
49 {
50 sentence += char(curkeycode);
51 Serial.write(curkeycode);
52 }
53
54 // Check for Return key
55 else if (curkeycode == 19)
56 {
57 Serial.println();
58 sortSentence(sentence);
59 waitforkey = false;
60 }
61
62 curkeycode = 0;
63 }
64 }
On the i rst line, the sketch loads the Keyboard controller library. This is the
only library that will be required for this example.
The sketch dei nes an int , curkeycode . This variable holds the keycode from
the keyboard; in most cases, it maps to ASCII, but it cannot be called ASCII
because some keyboards can return non-ASCII characters. The return code
will be checked later to see if it is ASCII. Until then, it is known as a keycode .
On line 7, the USB host is initialized, and on line 10, a KeyboardController
object is created, and the previous USB object is passed to it. The USB host can
now connect a keyboard to the USB subsystem.
On line 12, setup() is created, but all this does is coni gure the serial line. On
line 19, loop() is created and is even simpler. It calls one function, keyloop() ,
over and over again.
There is only one keyboard event that will be of interest for this sketch: when
a key is pressed. The sketch has no interest in when a key is released, so only
one callback function is created: keyPressed() . This function simply updates
the global variable curkeycode with the contents of the USB event.
On line 37, keyloop() is dei ned. This function is run whenever the sketch
expects a keyboard input. First, an empty String is created, and then a boolean
variable called waitforkey is set to true . While this variable is set to true, the
USB subsystem waits for events. A while loop is created on line 42, and on line
Search WWH ::




Custom Search