Project 12.00 Using the Board as a Keyboard
The MCU trainer can also act like a keyboard!
Project Code:
////////////////////////////////////////////////////// // 12.00 - Using the Board as a Keyboard #include "Keyboard.h" byte SW1 = 1; bool pressed = LOW; int pressCounter = 0; void setup() { pinMode(SW1, INPUT); Keyboard.begin(); } void loop() { while (digitalRead(SW1) != pressed) { ; } pressCounter++; Keyboard.print("You have pressed the button: "); Keyboard.print(pressCounter); Keyboard.println(" times!"); delay(500); } //////////////////////////////////////////////////////
*If you’re copying and pasting the code, or typing from scratch, delete everything out of a new Arduino sketch and paste / type in the above text.
Just like the previous project, we need to put the keyboard on some kind of control. We don’t want thousands of keypresses being sent to the computer at a time!
Also like the other project, to use the keyboard functionality we need to include a library that comes with the Arduino IDE by default. We can do that by simply typing in “ #include "Keyboard.h".
#include "Keyboard.h"
We then use some standard variables to represent the button.
byte SW1 = 1; byte pressed = LOW;
In this program we are also going to use a variable to keep track of the number of times the button has been pressed.
int pressCounter = 0;
Then in the setup() function, all we need to do is set the correct pinMode for the button pin and initialize the keyboard with the Keyboard.begin() function.
void setup() { pinMode(SW1, INPUT); Keyboard.begin(); }
In the loop() function, the first thing we do is wait until the button is pressed.
void loop() { while (digitalRead(SW1) != pressed) { ; }
When the button is pressed, the program moves on from the while-loop. Since the button has been pressed, we increment the pressCounter variable.
pressCounter++;
After that we can use the MCU Trainer to type that information out onto the screen. The print and println functions here work exactly the same as the Serial versions.
Keyboard.print("You have pressed the button: "); Keyboard.print(pressCounter); Keyboard.println(" times!");
A crude debounce is then implemented to keep the button from being read too many times.
delay(500); } //////////////////////////////////////////////////////
To see the text being printed out open a text editor, click on the screen, and press the button.
You have pressed the button: 1 times!
You have pressed the button: 2 times!
You have pressed the button: 3 times!
You have pressed the button: 4 times!
You have pressed the button: 5 times!
You have pressed the button: 6 times!
You have pressed the button: 7 times!
You have pressed the button: 8 times!
You have pressed the button: 9 times!
You have pressed the button: 10 times!