deckle studioIm Editor öffnen

Pro Micro: USB-Makrotastatur

Vier Taster tippen Text und Tastenkürzel am PC.

  • Pro Micro (ATmega32U4)
Im Simulator öffnenOhne Konto: Simulieren drücken, und es läuft.

So funktioniert es

Der ATmega32U4 des Pro Micro hat USB eingebaut: Der Sketch macht ihn zu Tastatur und Maus für den PC (Keyboard.h, Mouse.h). Taster SW1 an D2 tippt einen Gruß, SW2 an D3 sendet Strg+C, SW3 an D4 Strg+V, SW4 an D5 fährt mit der Maus ein Quadrat und klickt. Drück die Taster während der Simulation: Der serielle Monitor zeigt, was am PC ankommt (Keyboard / Mouse), und über die USB-Schnittstelle, welcher Taster gedrückt wurde. Das Board hängt mit Strom und Daten am USB.

Verdrahtung

Jede Zeile ist eine Verbindung (Netz) mit den Pins, die sie verbindet.

NetzPins
GNDA1 GNDSW1 2SW2 2SW3 2SW4 2
B1A1 D2/SDASW1 1
B2A1 ~D3/SCLSW2 1
B3A1 D4SW3 1
B4A1 ~D5SW4 1

Bauteile

Firmware

sketch.ino · 51 Zeilen

// Pro Micro (ATmega32U4) as a macro keyboard: the board is a USB keyboard and mouse for the PC.
//  - button on D2: types a greeting
//  - button on D3: Ctrl+C, button on D4: Ctrl+V
//  - button on D5: moves the mouse in a small square and clicks
// The buttons switch to GND (internal pull-ups). The console shows what the PC receives
// ("Keyboard ▸" / "Mouse ▸") and, over the USB serial port, which button was pressed.
#include <Keyboard.h>
#include <Mouse.h>

const byte BUTTONS[4] = { 2, 3, 4, 5 };
bool was[4];
unsigned long lastChange[4];

void setup() {
  for (byte i = 0; i < 4; i++) { pinMode(BUTTONS[i], INPUT_PULLUP); was[i] = HIGH; }
  Keyboard.begin();
  Mouse.begin();
  Serial.begin(9600);
}

void shortcut(char key) {
  Keyboard.press(KEY_LEFT_CTRL);
  Keyboard.press(key);
  delay(20);
  Keyboard.releaseAll();
}

void square() {
  const int dx[4] = { 40, 0, -40, 0 }, dy[4] = { 0, 40, 0, -40 };
  for (byte side = 0; side < 4; side++)
    for (byte step = 0; step < 4; step++) { Mouse.move(dx[side] / 4, dy[side] / 4); delay(10); }
  Mouse.click();
}

void loop() {
  for (byte i = 0; i < 4; i++) {
    bool now = digitalRead(BUTTONS[i]);
    if (now != was[i] && millis() - lastChange[i] > 30) {      // debounce
      lastChange[i] = millis();
      was[i] = now;
      if (now == LOW) {                                        // pressed
        Serial.print("button on D");
        Serial.println(BUTTONS[i]);
        if (i == 0) Keyboard.println("Hello from the Pro Micro!");
        if (i == 1) shortcut('c');
        if (i == 2) shortcut('v');
        if (i == 3) square();
      }
    }
  }
}
Im Simulator öffnen

Weitere Beispiele: Arduino