🛠 Clavier USB : taper du texte avec la bibliothèque Keyboard

Arduino Leonardo — Board Fiche · intermediaire · Schéma : IMG-leonardo-intermediaire-4-leonardo-hid-clavier.svg — Leonardo branchée en USB émettant des frappes vers un ordinateur, bouton sur la broche 2, fenêtre de garde de 3 s

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials