problem with stopping a program

hi i am new to both coding and arduinon. i am trying to make a stepper motor run in different directions using 2 photogates. in the beginning the motor keeps running and when i block one photogate the direction of rotation must change. when i use the break function it can be seen in the code below i keep getting an error saying "break statement not within loop or switch". can i get some help here please?

int s1;
int s2;
float v1;
float v2;
void setup() {
 pinMode(1,OUTPUT);
 pinMode(2,OUTPUT);
 pinMode(3,OUTPUT);
 pinMode(4,OUTPUT);
Serial.begin(9600);
}

void spin(){
 for(int j=4; j>0; j--){
      digitalWrite(j,HIGH);
      delay(10);
      digitalWrite(j,LOW);
 } }

 void sensor(){
  s1 = analogRead(A1);
  s2 = analogRead(A2);
  v1 = s1 * (5.0 / 1023.0);
  v2 = s2 * (5.0 / 1023.0);
  Serial.print("v1    ");
  Serial.println(v1);
  Serial.print("v2    ");
  Serial.println(v2);
  
   }
 
  void loop(){
  spin();
  sensor();
  
   
  if(v1<v2)
 {
  break;
  sensor();
  
  for(int j=1; j<5; j++){
    digitalWrite(j,LOW);
 }
 }
  if(v2<v1){
  break;
  sensor();
  
 
  spin();}
 }

You can only 'break;' out of a for/while/do-while statement or switch-case. You can exit from a function with 'return;' but loop() will just get called again. If you want loop() to stop executing you can use an infinite loop:

     while(true) /* Do Nothing */ ;

Your sketch will do nothing further until you reset the processor.

Hi,
Welcome to the forum.

Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?

Thanks.. Tom... :slight_smile:
Be careful, you are almost cross posting.
http://forum.arduino.cc/index.php?topic=415666.new#new

Please don't double post - it just wastes time answering the same thing twice.

I am suggesting to the Moderator to merge your Threads.

...R

I couldn't be bothered to merge across forum sections, so I deleted the other thread.

dd2509:
when i use the break function it can be seen in the code below i keep getting an error saying "break statement not within loop or switch". can i get some help here please?

Compiler has already told you, your use of 'break' is invalid.

To help you with your code you have to tell us what you expected from 'break'?

And I think it is a bad idea to use pin 1 as output. Pin 0 and pin 1 is used for serial communication and you do use serial communication in your code so it will interfere.

@dd2509, you need to tell us in English (not code) how you expect your program to work. I don't understand the logic of what you think might be happening.

For example if this was valid

 if(v1<v2)
 {
  [b]break[/b];
  sensor();

how could the lines after break ever be implemented?

In general you never try to stop the program. You just get it to stop doing what you don't want it to do.

...R