Today I got my hands onto the Arduion Leonardo to actually use it as a keyboard emulator.

Basically, it’s a sketch that emulates typing on the keyboard of the computer which the Leonardo is connected to.

Without further ado, let’s jump right into the water by looking at the code bellow:
This basic program prints the line “Hello kitty” 10 times with the line number at the beginning, thus, the output looks something like this:

0 - Hello kitty
1 - Hello kitty
2 - Hello kitty
3 - Hello kitty
4 - Hello kitty
5 - Hello kitty
6 - Hello kitty
7 - Hello kitty
8 - Hello kitty
9 - Hello kitty


/* Initializing the Keyboard feature.*/
void setup() {
bool flag = true;

void loop() {
  if(flag == true) {
    for(int i = 0; i < 10; i++) {
      Keyboard.println(" - Hello kitty");
    flag = false;

Above is the full program! No libraries to include!
Let’s examine this code line by line…
Starting at line 3 with the command Keyboard.begin(), this actually initializes the Keyboard just like when you’ve been typing Serial.begin().
Followed by delay(3000), this is actually to give enough time for the previous command to initialize the Keyboard. As a case in point, the initialization require much less time(~2000ms) but I put 3000 to guarantee, however, you can play with gauging the right time.

Now, I will jump right into the loop() so you can understand why I needed the flag
As you already know, the loop() is a function keeps running as long as you’re giving power to the Arduino, hence the code in the loop‘s body keeps running as a result.
Since we’re printing the line “Hello kitty” only 10 time, we need some kind of mechanism that stops the loop() after printing the 10 lines. That where the bool flag comes into play.
Notice that the loop() keeps running!! but the printing stops after only 10 lines!

Say, Where does it print all this, anyway?


Answer: anywhere! it’s like you’re actually typing! in my case, I simply opened the notepad and let it type there(see screenshot above)!
However, if I kept the Arduino IDE open(means, the typing cruiser in the IDE), then it’ll print in the IDE itself! Or if I opened the Office Word, it’ll print there…Well, you got the idea.

Suppose I didn’t put the <code>bool flag</code>, what might happen?
The line “Hello kitty” will be printed over and over again until i reach the maximum size which a <code>.txt</code> could manage, in other words, an infinite number of times(well, not actually infinite..)

Therefore, it’s very important to include a “Stopping Mechanism”, or else your code might cause you some headache, especially when you open new window or  do some of the cool stuff, but on that, I might dwell in a future post.

Also, you might notice some weird behavior in your keyboard like some shortcuts ceased to function or behave differently, like CTRL+A shortcut, but don’t worry, when you reboot/restart your computer it’ll be resolved.

Note before you go…Thanks for reading.