Arduino LED flashes with one button press I want the LED to flash when I press the switch once, but it keeps flashing. I tried the idea of just lighting the LED and keeping it lit with just one button press, so I wrote:

int led=13,button=12;
void setup() {
pinMode(led,OUTPUT);
pinMode(button,INPUT);
}
void loop() {
if (digitalRead(button)==HIGH)
  digitalWrite(led,HIGH);
}


and this worked; it stayed on after I pressed the button once, so for the flashing LED I wrote:

int led=13,button=12;
void setup() {
pinMode(led,OUTPUT);
pinMode(button,INPUT);
}
void loop() {
if (digitalRead(button)==HIGH)
{
  digitalWrite(led,HIGH);
delay(1000);
 digitalWrite(led,LOW);
 delay(1000);

} }


but this didn't work. It stops flashing after I remove my hand from the switch. Why is this happening?
Because the digital writes only apply on if (digitalRead(button)==HIGH). If you don't press the button, then the code goes:

void loop() {
}


Essentially doing nothing. Your code needs a bit more to keep track of the button press. Pseudo Code:

if button == pressed {
    int tracker=1;
}
if tracker == 1 {
    led on;
    wait;
    led off;
    wait;
}
loop