I want to design a simple behaviour using Keyboard.press. My goal is to make arduino ables to print the letter I already assigned for three times. To do that I used this code:
It works but there is a little glitch because the delay is settled to print to me 3 letters " W ", the fact is that the first 2 letters are printed smoothly whereas the last one takes few seconds to be printed.
How can make the print part smoother ? The delay is not the appropriate one ?
You are using the operating system's auto-repeat timing to get your three repeats. That won't work if you move to a different system or change OS keyboard settings.
Better would be to press and release the key three times.
My aim is to simulate the natural behaviour of when you keep pressing the letter in your keyboard, because I want to use that mechanisms to automatize some action on FIFA game, for that reason I need to load the shot keeping the letter down for a while example
Oh. Then just ignore what you see in the text input. The game probably uses raw keyboard events and doesn't see character input events generated by the OS.
There are a few things that can go wrong when using Arduinos as a HID but that will never be unrecoverable.
You spam your PC with text; that is problematic because when you try to modify your sketch with the board connected that text will go into the IDE.
You use Keyboard.press() but forget Keyboard.release(); the pressed key will be stuck in the PC.
The below code adds a safety pin to your code and will only send keyboard commands if that pin is connected to ground; if it's not connected to ground it will release the keys that you might have forgotten to release.
#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)
{
// press the left shift key once
if (isPressed == false)
{
Keyboard.press(KEY_LEFT_SHIFT);
isPressed = true;
Serial.println("Key pressed");
}
}
// if the safety pin is not connected to ground
else
{
// release any key that might be stuck
Keyboard.releaseAll();
Serial.println("All keys released");
isPressed = false;
}
delay(500);
}
Your actions can go inside this part
if (digitalRead(safetyPin) != SAFETY_ENABLED)
{
}
There is something more generic that can go wrong; part of the code that you upload provides the USB functionality; if you write crappy code that overwrites variables used by that specific code for the USB, you will experience upload problems; easy to resolve (if you know how).