Hi all,
First time here, just got my new Leonardo and I'm working on a keyboard project.
I'm interested in best practices for holding down SHIFT / CTRL / ALT + KEY.
Here's a demo:
void setup() {
// make pin 2 & 4 inputs and turn on the
// pullup resistor so it goes high unless
// connected to ground:
pinMode(2, INPUT_PULLUP);
pinMode(4, INPUT_PULLUP);
Keyboard.begin();
}
void loop() {
//if the button is pressed
if(digitalRead(2)==LOW){
Keyboard.write('a');
}
//if the button is pressed
if(digitalRead(4)==LOW){
Keyboard.press(KEY_LEFT_SHIFT);
}
if(digitalRead(4)==HIGH){
Keyboard.release(KEY_LEFT_SHIFT);
}
//delay to slow things down a little on screen reading
delay(50);
}
Quite simply:
pin2: Input 'a'.
pin4: Press LEFT SHIFT, so 'a' becomes 'A' when combined with pin2.
I'm concerned about the .press and .release.
Is what I have above the best possible code for that, it doesn't feel write, having both if statements for HIGH vs LOW on pin4.
It feels like having Keyboard.release repeat in that loop would be a waste of resources.
Any advice would be greatly appreciated.
Thank you! 8)
You probably want to look at the state change detection example and press and release the shift key only when there is a change in the state of the switch, not every time the switch state is checked.
buttonState = digitalRead(shiftPin);
if (buttonState != lastButtonState) {
if (buttonState == LOW) {
You have another variable called buttonPin. The state variables associated with the shiftPin variable should be called something like currShiftState and lastShiftState. It's confusing to see mixed names like you have.
But, what would you suggest for a single key press?
The same as you are doing for the shift key. Test for a change in state, then press or release the key, depending on the current switch state (pressed or released).