help with break!

hello. im trying to make a make a blinking light stop when i push a spdt microswitch. i figured using the break function was the way to do it but i cant seem to get it to work.

int highsignal = 9;
int endstop = 10;
int motorstep = 8;
int stopp;

void setup()
{
  pinMode(highsignal, OUTPUT);
  pinMode(endstop, INPUT);
  pinMode(motorstep, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  analogWrite(highsignal, 255);
  delay(10);
  int i;
  for(i = 5; i < 255; i++)
    {
    digitalWrite(motorstep, HIGH);
    delay(100);
    digitalWrite(motorstep, LOW);
    delay(100);
    stopp = analogRead(endstop);   
    if (stopp > 200)
    {
      i=0;
      break;
    }
    Serial.println(i);
    delay(500);
    }
}

anyone know why it doesnt work!?! thanks

How does it "not work"?
Your definition of "work" may not be someone else's.

If you break out of that for loop, then you exit "loop()", end then immediately re-enter the for loop.

anyone know why it doesnt work!?! thanks

Something you don't understand, which is "hidden" by the Arduino, is that the loop() function actually sits inside a looping while() in main().

All C programs start with a main() - this is hidden by the Arduino; it looks similar to this:

void main() {
  setup();

  while (1) {
    loop();
  }
}

Where setup() and loop() are the two functions that you must define for your Arduino code to work, of course.

So - you break out of your for() loop (via the break statement), the loop() function exits back to main() - where it is called again! This is what Groove was getting at.

Hopefully this insight will help you to see how to make the program work properly.

Good luck.

:slight_smile:

cr0sh
I appreciate your explanation.. :slight_smile:
it makes sense to someone new to C, so thanks.
I did have my son ask me how to get a program to stop/terminate/end/quit ie just not do anything more.

I'm not fully sure what he intended to do, but your explanation raises some thoughts.
Obviously in battery powered situations having the processor continually running in a loop doesn't save energy.

I do find generally that the Arduino references really need an understanding of C in order to use them effectively, and are sometimes not that helpful to us neewbies.

Mark