Search code examples
arduinokeyboard

Keyboard Emulator Typing Without Input


I made a keyboard emulator with my Arduino and hooked it up to some switches, thought I'd test them out in OSU. Osu, while it can be played with one key is best with two so naturally, I tried to add another switch/key to my emulator. This broke my emulator completely and caused it to start spitting out characters without any input. I've rewritten this script twice so forgive me if it's kind of frantic but can anyone tell me what's causing this?

Code:

#include <Keyboard.h>
void setup() {
  // put your setup code here, to run once:
pinMode (2, INPUT_PULLUP);
pinMode (5, INPUT_PULLUP);
Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:
  bool keyL = false;
bool keyR = false;
 
  Keyboard.begin();
 
  if (digitalRead (2) == 0){ //if switch 2 is activated
  keyL = true;
  }  
  else{
  }//do nothing
  if (digitalRead (5) == 0){
  keyR = true;
  }
  else{
  }//do nothing
  
  
  if (keyR = true){
  Keyboard.press ('c');
  delay (50);
  if (digitalRead (5) == 1){
    keyR = false;
   Keyboard.releaseAll(); 
  }
  }
  
  
  
  if (keyL = true){
  Keyboard.press ('z');
  delay (50);
  if (digitalRead (2) == 0){
    keyL = false;
   Keyboard.releaseAll(); 
  }
  }
  
}

Solution

  • It happens because the = operator is used for assignment only, and it returns the value of the assignment. so the expressions (keyR = true) inside if (keyR = true){ and (keyL = true) inside if(keyL = true){ always return true.

    To compare the value of 2 variables you have to use the == operator:

    #include <Keyboard.h>
    void setup() {
      // put your setup code here, to run once:
    pinMode (2, INPUT_PULLUP);
    pinMode (5, INPUT_PULLUP);
    Serial.begin(9600);
    
    }
    
    void loop() {
      // put your main code here, to run repeatedly:
      bool keyL = false;
    bool keyR = false;
     
      Keyboard.begin();
     
      if (digitalRead (2) == 0){ //if switch 2 is activated
      keyL = true;
      }  
      else{
      }//do nothing
      if (digitalRead (5) == 0){
      keyR = true;
      }
      else{
      }//do nothing
      
      
      if (keyR == true){
      Keyboard.press ('c');
      delay (50);
      if (digitalRead (5) == 1){
        keyR = false;
       Keyboard.releaseAll(); 
      }
      }
      
      
      
      if (keyL == true){
      Keyboard.press ('z');
      delay (50);
      if (digitalRead (2) == 0){
        keyL = false;
       Keyboard.releaseAll(); 
      }
      }
      
    }