🛠 Clavier USB : taper du texte avec la bibliothèque Keyboard
Objectives
Leverage the feature that defines the Leonardo: the ATmega32u4 integrates the USB transceiver, so the board can pretend to be a HID keyboard to the host computer, without any auxiliary USB processor. You will send a sentence when a button is pressed, with the two official precautions: a startup guard window and a call only on the rising edge.
Hardware
- 1 Arduino Leonardo + micro-USB cable
- 1 push button between pin 2 and GND (internal pull-up)
- A deliberate keyboard focus in a text editor for testing
Complete code
#include <Keyboard.h>
const uint8_t BUTTON_PIN = 2;
bool wasPressed = false;
void setup {
pinMode(BUTTON_PIN, INPUT_PULLUP);
Keyboard.begin; // énumère la carte en clavier HID standard
delay(3000); // fenêtre de garde : le temps de placer le focus
}
void loop {
bool pressed = (digitalRead(BUTTON_PIN) == LOW);
if (pressed && !wasPressed) { // front montant uniquement
Keyboard.print("Hello, Leonardo!"); // les frappes partent vers l'OS hôte
Keyboard.releaseAll; // aucun key remain held
}
wasPressed = pressed;
}
Expected verification
Place the cursor in a text editor during the first 3 seconds, then press the button: the sentence “Hello, Leonardo!” is typed once in the focused application. In the IDE, the serial monitor will show nothing here: Serial is not used, and the current USB device is a keyboard.
Common errors
- Runaway HID: calling
Keyboard.printin a tight loop floods the computer with keystrokes and can make the board very difficult to reprogram. Arduino explicitly warns: test first withSerial.printand only trigger HID calls behind a button or a condition. - Forgetting
Keyboard.releaseAll: a key left pressed causes a character to repeat indefinitely. - No guard window: the board types immediately into the focused window upon enumeration, sometimes the IDE itself.
- Wrong component selected: “Pro Micro” clones share the chip but require their own board entry in the IDE.
- Waiting for the serial monitor: once enumerated as HID, the board may no longer expose a CDC port if the sketch only declares the keyboard.
Other tutorials for this board
- Faire clignoter la LED intégrée (broche 13)
- Bouton et console série : Serial (USB) vs Serial1 (broches 0/1)
- Lire un capteur analogique : potentiomètre et ADC 10 bits
- Souris USB : déplacer le curseur avec la bibliothèque Mouse
- Asservir un servo moteur avec un potentiomètre (PWM)
- Programmer aux registres : interruption Timer/Counter1
Code examples for this board
clignotante.inoArduinobouton-led.inoArduinoclavier-auto-tape.inoArduinosouris-cercle.inoArduinotelecommande-media.inoArduinobouton-clic-souris.inoArduino