Pushbutton To Start and Stop a Script

Hi Everyone,

Im a student artist and somewhat new to Arduino, and very new to coding. I'm using an uno to run a sculpture of mine. It simply just has to turn a motor on and off at timed intervals. I have that part figured out but I would like it to begin an infinite loop of this at the push of a momentary switch, and then stop that loop whenever the momentary switch is pressed again.

I have been experimenting with a boolean state variable that reverses anytime the button is pushed. I am able to start the loop but I am un-able to stop it. I think the issue is that it is only looking for the button state change momentarily when the script is running. Any comments you might have would help.

All that needs to happen here is for the script to start when the button (pin 2) and stop when its pushed again. The motor circuitry runs independently through a relay tripped by pin 6, so it can run as if to turn on an LED connected to pin 6.

Code is below.

boolean state = false;
const int buttonPin = 2;     // the number of the pushbutton pin
const int rPin =  6;      // the number of pin that drives the relay

void setup()
{ 
  // initialize the LED pin as an output:
  pinMode(rPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop()
{
 
 while (state == false)     // while the state is false, do nothing except for wait for the button to be pushed again
 {
   if (digitalRead(buttonPin) == HIGH)
   {
      state = true;               
    }
 }
  while (state == true)  // while the state is true, run loop infinitely
 {
  digitalWrite(rPin, HIGH);  
  delay(2000);     
  digitalWrite(rPin, LOW); 
  delay(5000);
if (digitalRead(buttonPin) == HIGH)  // check to see if button is pushed again, then change state
   {
      state = false;               
    }
  
   }
 }

nvm got it. blink without delay tutorial is key.

Welcome to the wonderful World of BWOD