🛠 Souris USB : déplacer le curseur avec la bibliothèque Mouse
Objectives
Take the Leonardo's native USB capabilities further by using it as an HID mouse: a potentiometer on A0 controls the horizontal movement of the computer cursor, and a button sends a left click. You will understand the principle of periodic HID reports (Mouse.move = relative movement) and the pitfall of pin A6 being shared with digital pin 4.
Hardware
- 1 Arduino Leonardo + micro-USB cable
- 1 potentiometer on A0 (5V/GND)
- 1 push button between pin 4 and GND (internal pull-up)
Complete code
#include <Mouse.h>
const uint8_t POT_PIN = A0; // A0-A5 : entrees analogiques classiques
const uint8_t CLICK_PIN = 4; // attention : A6 est aussi sur la broche 4
void setup {
pinMode(CLICK_PIN, INPUT_PULLUP);
Mouse.begin;
delay(3000); // fenetre de garde : reprendre la main sur la souris hote
}
void loop {
int pot = analogRead(POT_PIN); // 10 bits : 0..1023
int dx = map(pot, 0, 1023, -10, 10); // vitesse par rapport HID
if (dx != 0) {
Mouse.move(dx, 0, 0); // deplacement X (Y, molette = 0)
}
if (digitalRead(CLICK_PIN) == LOW) {
if (!Mouse.isPressed(MOUSE_LEFT)) Mouse.press(MOUSE_LEFT);
} else {
if (Mouse.isPressed(MOUSE_LEFT)) Mouse.release(MOUSE_LEFT);
}
delay(20); // cadence ~50 Hz, largement suffisante
}
Expected verification
After the 3-second guard time, turn the potentiometer: the computer cursor moves faster the further you move away from the neutral point (median value ~512). The button sends a held/released left click. Keep an eye on the neutral zone to avoid sending the cursor off-screen endlessly.
Common errors
- Runaway cursor (runaway HID): If the code runs in a loop without a neutral point, the cursor constantly crosses the screen, making it difficult to reprogram the board. Arduino recommends testing first with
Serial.printand keeping a stop button; if you lose control, press reset (the Caterina bootloader remains active for ~8 s) then unplug. - Pin 4 also used as analog: A6 is multiplexed on pin 4; do not use both functions simultaneously.
- Mistaking
Mouse.movefor absolute positioning: It is a relative delta; the potentiometer's neutral point is essential. - Confusing
Serial(USB) andSerial1(pins 0/1) for debugging: On the Leonardo, the serial monitor goes through the CDC port, which may be absent from a purely HID descriptor.
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
- Clavier USB : taper du texte avec la bibliothèque Keyboard
- 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