very noob question about button tutorial

Hi, i’m testing the button code from the examples, and works, obviusly.
Now i’m trying to use only the HIGH state of the button.

If the led is LOW, and the button is HIGH, turn on the led, and keep it on.
If the led if HIGH, and the button is HIGH, turn off the led, and keep it off.

The problem (i think) the 2 cases are simultaneously. Please help me.

First you need to implement an edge detector, that is trigger something when the button changes from being low to being high. That means remembering the previous state of the button, so last thing in the loop function make a copy of the current button state in a variable called something like lastButtonState. Now only change the state of the LED when the last state is low and the current state is high. Have a variable track the last state you set the LED to.

sorry, i know that it's a very low level question but ...

void loop(){
  buttonState = digitalRead(buttonPin);

  if (buttonState == HIGH && lastButtonState == LOW) {
    if (ledState == 0) {    
      digitalWrite(ledPin, HIGH);
      ledState = 1;
    else {
      digitalWrite(ledPin, LOW);
      ledState = 0;
  lastButtonState = digitalRead(buttonPin);

this? it's very aleatory, i need to press several times to change the state of the led :confused: what's the correct code?

lastButtonState = digitalRead(buttonPin);

Should be:-

lastButtonState = buttonState;

Then I would add some contact debounce delay here:-

if (buttonState == HIGH && lastButtonState == LOW) {
       delay(50); // add this line