Restart void loop(){ every time a switch is pressed

Hello All,

I'm trying to get my code to restart every time a switch is pressed. I have the switch signal wire connected to pin12 that I defined as switchSignal . The switch ground wire is connected to GND, and the switch HIGH wire is connected to pin13 that I defined as switchHigh

//Define constants for the switch pins
const int switchSignal = 12;
const int switchHigh = 13;```

I made functions to set the pinMode for each of these pins and the output level as below.

//Initialize switchHigh pin as an OUTPUT and digitalWrite HIGH
void initSwitchHigh() {
  pinMode(switchHigh, OUTPUT);
  digitalWrite(switchHigh, HIGH);
}
//Initialize switchSignal pin as an INPUT
void initSwitchSignal() {
  pinMode(switchSignal, INPUT);
}

I then created a function to place in void loop() to have the loop wait for the switch to be pressed and released as shown below.

void waitForTrigger(void) {
  initSwitchHigh();
  initSwitchSignal();
  while (digitalRead(switchSignal) == LOW) {
  }
  while (digitalRead(switchSignal) == HIGH) {
  }
}

The problem I am having is the code seems to start randomly, but when I press the switch it stops. Then when it is released again it may or may not run my code. I am certain it is a problem with my "waitForTrigger" function, but I'm not sure how to fix it. Below is a copy of my entire void loop code. By the way, the code works perfectly in a continuous loop without the "waitForTrigger", but I need it to restart every time the switch is pressed.

void loop() {

  waitForTrigger();
  // 5.3.4 Display the image
  // TODO 5.3.4 #8: Complete the 3 nested for() loops to cycle through column, rows and colors
  for (int column = 0; column < image.width ; column++) {
    for (int row = 0; row < nRows; row ++) {
      turnOnRow(row);

      for (int color = 0; color < nColors; color++ ) {
        // turn on each color to the correct intensity
        turnOnColorPWM ( color, getPixel(row, column, color) );
      }

      // delay as long as necessary for your picture to display for about 1/2 revolution
      delayMicroseconds(500);  // adjust this to work with your picture

      // turn off all color pins
      for (int color = 0; color < nColors; color++ ) {
        turnOffColor(color);
      }

      // turn off row
      turnOffRow(row);
    }
  }
}

Isn't that enough time to check your buttons instead?

Exit from loop() using return.

BTW void means nothing. A function is recognized by the (possibly empty) parameter list in parentheses like with setup() or loop().

Put the code to be run when the switch becomes pressed in its own function

In loop(), when the switch becomes pressed rather than when it is pressed (see the StateChangeDetection example in the IDE), call the function to run the code

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