Button programming issue

Hi guys,

I want to use a simple button to light up a LED but I have no idea how to program this.

Lets say that my LED is not lighting.
I want that when I press the button and release it my LED lights and when I press the button one more time the LED goes out.

The only this I managed to do is that when I hold the button pressed, the LED lights...


Have a look at the StateChangeDetection example in the IDE

Thanks, but this technique uses the modulo 4. How can I change this so that the state of the LED change every time I press the button and not every four times ?

Simple use a boolean variable, (call it ledState) in your program. Whenever you detect a button press, then if the boolean variable ledState is false then set it true, else set it false. At the same time, write HIGH or LOW to you led pin.

sample coding approach ...

if (button pressed) 
  if (ledState)
  {  //led is already on, so turn it off
     ledState = false;
     digitalwrite(ledPin, LOW);
  {//led is already off, so turn it on
     ledState = true;
     digitalwrite(ledPin, HIGH);

You will most likely quickly notice odd or erratic behavior when pressing the button and how the light sometimes goes on or off. Time then to google "button debouce".