Toggle a led with a button press

Hi, this is my first project with Arduino and I need some help. I am trying to toggle a led with a button, but it actually just stays on while I hold it down. Could somebody please help me? Thanks in advance.

const int buttonPin = 8;
const int stopButtonPin = 7; 
const int ledB =  12;     // BLUE led pin
const int ledR =  11;     // RED led pin

int button = 0;
int stop = 0;

void setup()

{
  //setting the pin modes
  pinMode(ledB, OUTPUT);
  pinMode(ledR, OUTPUT);
  pinMode(buttonPin, INPUT);
  pinMode(stopButtonPin, INPUT);
}

void loop()

{
  button = digitalRead(buttonPin);  //read button state
  stop = digitalRead(stopButtonPin);      //read stop state
  
  if (button == HIGH) //if button is pressed, light BLUE led and turn off the other
  {
    digitalWrite(ledB, HIGH);
    digitalWrite(ledR, LOW);
  }
  
  else if (button == LOW) //if button is released, light RED led and turn off the other
  {
    digitalWrite(ledB, LOW);
    digitalWrite(ledR, HIGH);
  }
  
  if (stop == HIGH) //if stop is pressed, turn off both leds
  {
    digitalWrite(ledB, LOW);
    digitalWrite(ledR, LOW);
  }

}

The answer to your question is in the state change detection example in the IDE (File, Examples, Didital). The trick is to detect when the button BECOMES pressed (or un-pressed) versus IS pressed.

You need to answer some questions first, so that you can explain your wiring. For example:

  1. Why are you specifying INPUT instead of INPUT_PULLUP ? Do you have your own pullup resistors? Do you have your own pulldown resistors?

  2. How are your LEDs wired? Do you have current limiting resistors?

Also, you need to explain whether you want the LEDs to toggle when you press the button or when you release the button.

There is an example for debouncing a button, or you can just use the Bounce2 library. See Bounce (and Bounce 2) Library Official Question Forum - Sensors - Arduino Forum

There is an example for state change detection, or you can just use the Bounce2 library. See Bounce (and Bounce 2) Library Official Question Forum - Sensors - Arduino Forum