Is my Arduino skipping a statement? So, I made this code (I'm rather new to this). The only thing that the Arduino should do, is when I press the button on pin 2, turn on the LED on pin 4 and emulate CTRL + R on the keyboard for the computer. Then, if the LED is on and I hit the button again, turn it off and hit the spacebar on my computer. But as soon as I hit the button for the first time, it does indeed press CTRL + R and the LED turns on, but after the delay, it immediately skips checking if I am pressing the button and assumes that I am pressing the button. Thereby it only sees that the LED is on and it turns it off while hitting the spacebar. Any suggestions?



#include &lt;Keyboard.h&gt;

int buttonPin = 2;
int ledPin    = 4;
int val = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  val = digitalRead(buttonPin);
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if ((val == LOW) &amp;&amp; (digitalRead(ledPin) == LOW)) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
    Keyboard.press(KEY_LEFT_CTRL);
    Keyboard.press('r');
    delay(100);
    Keyboard.release(KEY_LEFT_CTRL);
    Keyboard.release('r');
    delay(500);
  }
  if ((val == LOW) &amp;&amp; (digitalRead(ledPin) == HIGH)) {
    digitalWrite(ledPin, LOW);
    Keyboard.write(32);
  }
  if ((val == HIGH) &amp;&amp; (digitalRead(ledPin) == LOW)) {
    digitalWrite(ledPin, LOW);
  }
  if ((val == HIGH) &amp;&amp; (digitalRead(ledPin) == HIGH)) {
    digitalWrite(ledPin, HIGH);  
  }
}
Your code isn't checking for a button.  It's checking the value in val.  That only gets updated once per loop.  Let's say the code enters the first if statement because the val is LOW and the LED is also LOW.  This sets the LED to HIGH.  Now the next if statement, val is still LOW and now LED is HIGH so that one is true as well.  

I think what you want is to use "else if" so it will skip the rest once it finds a true one.  

void loop() {
  val = digitalRead(buttonPin);
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if ((val == LOW) &amp;&amp; (digitalRead(ledPin) == LOW)) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
    Keyboard.press(KEY_LEFT_CTRL);
    Keyboard.press('r');
    delay(100);
    Keyboard.release(KEY_LEFT_CTRL);
    Keyboard.release('r');
    delay(500);
  }
  else if ((val == LOW) &amp;&amp; (digitalRead(ledPin) == HIGH)) {
    digitalWrite(ledPin, LOW);
    Keyboard.write(32);
  }
  else if ((val == HIGH) &amp;&amp; (digitalRead(ledPin) == LOW)) {
    digitalWrite(ledPin, LOW);
  }
  else if ((val == HIGH) &amp;&amp; (digitalRead(ledPin) == HIGH)) {
    digitalWrite(ledPin, HIGH);  
  }
}