Recently I'm making a hardware hotkey macro program using Python & Arduino Leonardo.
I just successfully ran the program as I intended, but there is still a problem, that is latency.
Is this what it meant to be? Or is there any way to fix this problem?
My code is below :
#include <Keyboard.h>
char upArrow = KEY_UP_ARROW;
char downArrow = KEY_DOWN_ARROW;
char receivedChar; //a vairable for saving a letter transmitted by python
unsigned long lastDebounceTime; //declare a variable for debouncing
volatile int state = false; //declare a variable for using switch
void setup() {
Serial.begin(115200);
Keyboard.begin();
pinMode(2, INPUT_PULLUP); //set pin2 as input
pinMode(13, OUTPUT); //activate built-in LED
attachInterrupt(digitalPinToInterrupt(2), isr, FALLING); //operate isr when pin2 gets falling edge signal
}
void loop() {
while(!state); //wait until state == true
recieveChar();
}
void isr() { //activate/deactivate Arduino by using switch
if ( (millis() - lastDebounceTime) < 200 ) return; //ignore bouncing occurred within 0.2sec from initial input
if (state == false) {
state = true; //activate Arduino
digitalWrite(13, HIGH); //turn on built-in LED
}
else {
state = false; //deactivate Arduino
digitalWrite(13, LOW); //turn off built-in LED
}
lastDebounceTime = millis(); //set the reference point of debouncing as current time
}
void recieveChar() { //a function recieves a letter from python thru serial communication
if (Serial.available()) {
receivedChar = Serial.read();
pressKey();
}
}
void pressKey() { //a function operates hotkey based on transmitted letter in recievechar()
if(receivedChar =='a') {
Keyboard.press(upArrow);
delay(25);
Keyboard.release(upArrow);
delay(25);
Keyboard.press(downArrow);
delay(25);
Keyboard.release(downArrow);
delay(25);
Keyboard.press('c');
delay(25);
Keyboard.release('c');
delay(25);
}
}