I'm trying to build a device that controls a program on my computer using a Leonardo and a few pushbuttons. I'm currently in the experimenting phase of my build and my sketch uses commands from the Keyboard library (since that program can also be controlled from the keyboard). Here is my code:
int val = 0;
void setup() {
pinMode(2, INPUT);
Keyboard.begin();
}
void loop() {
if(digitalRead(2)==HIGH) {
val=0;
}
if(digitalRead(2)==LOW) {
Keyboard.press('d');
}
while(digitalRead(2)==LOW)
{
val = val + 1;
}
delay(val);
Keyboard.release('d');
Keyboard.end();
}
What I'm expecting it to do:
I want it to keep the keyboard key pressed for as long as I keep the button connected to my Arduino pressed (I want it to press "d" and keep it pressed as long as I keep my finger on the button).
What it's actually doing:
Just what I want it to do, but ONLY ONCE. I want it to do that every time i push the button, just like a real keyboard.
What I've tried:
- other commands from the library
- putting the Keyboard.begin inside the void loop()
- reseting val after executing one loop (in the if with HIGH)
- adding the Keyboard.end()
- using INPUT_PULLUP instead of INPUT
But all of those turned out to be useless as I got the same result with or without them.
Can anyone help me? Maybe fix the code or think of another way to get to the result I need?
Thanks in advance.