<Keyboard.h> lib question

hello.

I checked that there is no problem with the board with the example 'blink' using Arduino Leonardo.
Then I tested Keyboard.h and it failed, so I ask a question.

The sketch is below.

#include <Keyboard.h>

void setup()
{
  Keyboard.begin();
}

void loop()
{
  Keyboard.println("Hello!");
  delay(2000);
}

After uploading, 'avrdude done. Thank you.'
, and the Tx LED blinks every 2 seconds on the board. But in Notepad, 'Hello!' is not entered.

What is the cause?

Welcome to the forum

Which Arduino board are you using ?

Thank you :slight_smile:
The board is an Arduino Leonardo.

Basically your code works here. I modified it as I want to be able to stop the spamming.

#include <Keyboard.h>

const uint8_t safetyPin = A0;

void setup() {
  Keyboard.begin();
  pinMode(safetyPin, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(safetyPin) == LOW) {
    Keyboard.println("Hello!");
    delay(2000);
  }
}

You will have to connect A0 to GND to send data; disconnect from GND if you want to stop it.

If you start experimenting with HIDs, I advise you to use something like below; you would not be the first one that manages to spam the PC with keypresses (and forgets to release the key) and text. It's an extension of the above.

#include <Keyboard.h>
#define SAFETY_ENABLED HIGH
const uint8_t safetyPin = A1;

void setup()
{
  Serial.begin(115200);
  while (!Serial);

  pinMode(safetyPin, INPUT_PULLUP);
}

void loop()
{
  static bool isPressed = false;
  // check if the safetyPin is connected to ground
  if (digitalRead(safetyPin) != SAFETY_ENABLED)
  {
    // do your stuff here
  }
  // if the safety pin is not connected to ground
  else
  {
    // release any key that might be stuck
    Keyboard.releaseAll();
  }
}

It was an awkward question because it was a translation machine, but thank you for answering.

I think HID needs to study more. I connected A0 and GND in the first way, so I did the desired action well. It's strange, but after a day, I retried the code I asked and it worked. I feel like I'm being played by Arduino :slight_smile: