Using a button to start and stop data logging to SD card

Hello all! I'm trying to implement state change detection into my sketch so that, when a button is pressed, data logging to an SD cards begins and, when the button is pressed again, data logging stops and so on.

I've been looking through different posts regarding state change and have tried to implement some of those methods to my code, but, so far, nothing has worked quite right.

At the moment, my sketch works partially; it does not log data when the system is not fully calibrated and doesn't log data even after it does reach full calibration. However, pressing the button only seems to log one data point rather than all of the data being collected.

Can someone point me in the right direction on how to implement state change detection correctly?

Edit: See reply with my solution.

I would attach the button to an interrupt and have the ISR flip a boolean.

Then use that in your loop code with a ‘while’ to determine if logging occurs or not.

I managed to get my version to work. I'll include the code below just in case anyone else wants to use it.

// read the pushbutton input pin
    reading = digitalRead(buttonPin);

    // determine if the button is pressed and assign button state
    if (reading == HIGH && previous == LOW && millis() - stateTime > debounce)
    {
      if (state == HIGH)
        state = LOW;
      else
        state = HIGH;

      stateTime = millis();
    }

    // start/stop writing data to SD card when button is pressed
    if (state == LOW)
    {
      // write to SD card
      myImuData.print(time);
      myImuData.print(",");
      myImuData.print(valuesX);
      myImuData.print(",");
      myImuData.print(valuesY);
      myImuData.print(",");
      myImuData.println(valuesZ);
    }

    // update previous button state reading
    previous = reading;

This method will start/stop data being written to the SD card each time the button is pressed.

Thanks for share! Googled and writhe for a half day till find this :)