Why is my switch not working? I'm trying to have a common light switch turn a LED on and off.

When I connect the light switch directly to a LED, it works like it should - the LED turns on and off with the switch.

When I connect the light switch back to the board, changing the switch does nothing - I get the exact same signals regardless of whether the switch is on or off.

Why?
How do I make the board recognize whether the switch is on or off?



The diagram I followed:


const int  buttonPin = 2;

const int ledUt = 13;
const int ledTest = 12;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;

int tilstand = 0;

int buttonStateForrigeForrige = 0;

boolean light = false;

void setup() {
  Serial.println("Hello World");
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
  pinMode(ledUt, OUTPUT);
  pinMode(ledTest, OUTPUT);

}

void loop() {

  digitalWrite(ledTest, HIGH);
  buttonState = digitalRead(buttonPin);
  Serial.println("Sjekk");

  tilstand = LOW;
  if ( buttonState == HIGH ) {
    Serial.println("buttonState HIGH");
    if ( lastButtonState == HIGH ) {
      Serial.println("lastButtonState HIGH");
      tilstand = HIGH;
    } else {
      Serial.println("lastButtonState LOW");
    }
  } else {
    Serial.println("buttonState LOW");
  }

  if (buttonState != lastButtonState) {

    if (buttonState == HIGH) {
      buttonPushCounter++;
      Serial.println("on");
      Serial.println(buttonPushCounter);
    } else {
      Serial.println("off");
    }
  }
  buttonStateForrigeForrige = lastButtonState;
  lastButtonState = buttonState;

  if (tilstand == HIGH) {
    digitalWrite(ledUt, HIGH);
  } else {
    digitalWrite(ledUt, LOW);
  }
  }
See my page about switches. Judging by your very-hard-to-read diagram, you have just connected the switch to an input pin like this:





That will not give a positive reading either way because it is "floating". You should connect a pull-up or pull-down resistor, like this:



Now if the switch is open, it is pulled-up to 5V by the resistor and the input will read HIGH. When the switch is closed the switch conducts and "overpowers" the resistor, and it would read LOW.



An alternative is to use a pull-down resistor like this:



That reverses the sense of the switch. When open it will read LOW and when closed it will read HIGH.



I hope you have a resistor in series with the LED.