In this example, when the button is pressed, a text string is sent to the computer as keyboard input. The string reports the number of times the button is pressed. Once you have the Leonardo programmed and wired up, open your favorite text editor to see the results.
Warning − When you use the Keyboard.print() command, the Arduino takes over your computer's keyboard. To ensure you do not lose control of your computer while running a sketch with this function, set up a reliable control system before you call Keyboard.print(). This sketch includes a pushbutton to toggle the keyboard, so that it only runs after the button is pressed.
You will need the following components −
Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below.
Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New.
/* Keyboard Message test For the Arduino Leonardo and Micro, Sends a text string when a button is pressed. The circuit: * pushbutton attached from pin 4 to +5V * 10-kilohm resistor attached from pin 4 to ground */ #include "Keyboard.h" const int buttonPin = 4; // input pin for pushbutton int previousButtonState = HIGH; // for checking the state of a pushButton int counter = 0; // button push counter void setup() { pinMode(buttonPin, INPUT); // make the pushButton pin an input: Keyboard.begin(); // initialize control over the keyboard: } void loop() { int buttonState = digitalRead(buttonPin); // read the pushbutton: if ((buttonState != previousButtonState)&& (buttonState == HIGH)) // and it's currently pressed: { // increment the button counter counter++; // type out a message Keyboard.print("You pressed the button "); Keyboard.print(counter); Keyboard.println(" times."); } // save the current button state for comparison next time: previousButtonState = buttonState; }
Attach one terminal of the pushbutton to pin 4 on Arduino. Attach the other pin to 5V. Use the resistor as a pull-down, providing a reference to the ground, by attaching it from pin 4 to the ground.
Once you have programmed your board, unplug the USB cable, open a text editor and put the text cursor in the typing area. Connect the board to your computer through USB again and press the button to write in the document.
By using any text editor, it will display the text sent via Arduino.