Help with arduino and button

Hello. How can we make it so that when a single button is pressed, the program enters the function and executes it until we press the button again? I can't figure out how to do this, please help

boolean butt;
boolean butt_flag = 0;
byte val = 0;
boolean val1 = 0;
int timing = 0;
void setup() {
  Serial.begin(9600);
  pinMode(A0, INPUT_PULLUP);
  pinMode(13, OUTPUT);

}

void loop() {
  butt = !digitalRead(A0);
  
  if(butt && !butt_flag && millis() - timing > 100){
    timing = millis();
    butt_flag = 1;
    val = !val;
    if(val == 1){
      led_blink();
    }
  }
  if(!butt && butt_flag && millis() - timing > 100){
    timing = millis();
    butt_flag = 0;
  }
}


void led_blink(){
  digitalWrite(13, 1);
  delay(1000);
  digitalWrite(13, 0);
  delay(1000);
}

look this over

const byte PinLed = 13;
const byte PinBut = A0;
      byte butState;

boolean run;

const unsigned long OneSec = 1000;
      unsigned long msec0;

void loop () {
    unsigned long msec = millis ();

    if (run && msec - msec0 >= OneSec) {
        msec0 = msec;
        digitalWrite (PinLed, ! digitalRead (PinLed));
        Serial.println ("run");
    }

    byte but = digitalRead (PinBut);
    if (butState != but)  { // changed
        butState = but;
        delay (20);         // debounce

        if (LOW == but)     // pressed
            run = ! run;
    }
}

void setup ()
{
    Serial.begin (9600);

    pinMode (PinLed, OUTPUT);
    pinMode (PinBut, INPUT_PULLUP);
    butState = digitalRead (PinBut);
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.