const int buttonPin = 2; // Pin connected to the button
bool buttonPressed = false; // Variable to track button state
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // Set the button pin as input with internal pull-up resistor
Serial.begin(9600); // Initialize serial communication
}
void loop() {
// Check if the button is pressed
if (digitalRead(buttonPin) == LOW) {
// Button is pressed
if (!buttonPressed) {
// If the button was not previously pressed, print a message and set buttonPressed to true
Serial.println("Button pressed! Exiting loop...");
buttonPressed = true;
}
} else {
// Button is not pressed
buttonPressed = false; // Reset buttonPressed flag
}
// If the button was pressed, exit the loop
if (buttonPressed) {
// Exit loop
return;
}
// Perform other actions in the loop while waiting for the button to be pressed
// For example:
Serial.println("Looping...");
delay(1000); // Delay to avoid continuous looping
}