🛠 Souris USB : déplacer le curseur avec la bibliothèque Mouse

Arduino Leonardo — Board Fiche · intermediaire · Schéma : IMG-leonardo-intermediaire-5-leonardo-hid-souris.svg — Leonardo émulant une souris USB : potentiomètre sur A0 pour l'axe X, bouton de clic sur la broche 4, curseur bougeant à l'écran

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials