Arduino Leonardo USB HID keyboard doesn't work

Hello, I need help on a recurrent bug.
I try to emulate WASD with a joystick connected to Arduino leonardo board.
Sometimes, when I reinstall Arduino IDE, Keyboard library functions work, and when I upload it several times (for improvement), these keyboard functions stop working while everything else keep working.

First time it disfunctionned, I reinstalled Arduino Uno and restarted windows 10, and magically the same program worked again. Then I uploaded a program for 2 joysticks and the simple joystick program messed again: no keyboard function.
And reinstalling Arduino IDE didn't change anything

Second time, it magically worked again, I had to restart windows 10 for update, uninstall Arduino IDE, restart Windows 10 again, install Arduino IDE.
And after upload the same program, keyboard function stop working again.

I am pretty sure the problem doesn't come from the hardware, my board is leonardo but not an original from Arduino.

I am also pretty sure the problem is not my code :

#include<Keyboard.h>

// Analog input of the horizontal joystick position
const int JoystickX = A0;
// Analog input of the vertical joystick position
const int JoystickY = A1;
//joystick press
const int SW_pin = 2;

void setup()
{
  Serial.begin(9600);
  pinMode(SW_pin, INPUT_PULLUP);
}

void loop()
{
  // Process horizontal joystick position
  int x = analogRead(JoystickX);
  if (1023 == x)
  {
    Keyboard.press('d');
    Serial.print("eaezae");
  }
  else if (0 == x)
  {
    Keyboard.press('a');
    Serial.print("eaezae");
  }
  else
  {
    Keyboard.release('d');
    Keyboard.release('a');
    delay(5);
  }

  // Process vertical joystick position
  int y = analogRead(JoystickY);
  if (0 == y)
  {
    Keyboard.press('w');
    Serial.print("eaezae");
  }
  else if (1023 == y)
  {
    Keyboard.press('s');
    Serial.print("eaezae");
  }
  else
  {
      Keyboard.release('w');
    Keyboard.release('s');
    delay(5);
  }
  int z = digitalRead(SW_pin);
  Serial.print(z);

  if(0==z)
  {
  Keyboard.press('e');  
  }
  else
  {
    Keyboard.release('e');
  }
}

I already tried to upload this program and the connect the arduino board at the exact moment linking everything together was displayed in the console but didn't work.
I also tried to change the port & com number in peripheral device but didn't work either

I am running out of idea

You are missing a Keyboard.begin(). Have a look at the examples.

this program works without keyboard.begin()

Already added it and it doesn't change anything

Get it down to confirming Keyboard operation - make a sketch where it's only typing an 'X', delay(n), 'X', . . .
Have it delay long enough to make Notepad the active window and see it happen there.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.