# Sweep function N times with a step X

Hello lads, my task is to make sweep(servo ) function repeat N times with a step X only if 180(degrees) can be divided by X(step) without reminder (example : if step is 5 (180/5=30, reminder=0)it asks how many times to do sweep) if step is 7 (180/7 = 25 ,reminder=5 so it just prints out reminder). My problem is that i don’t know how to input N and X i somehow get stuck in infinity loop here is my code:
#include <Servo.h>

const int trigPin=3;
const int echoPin=4;
long time;
int distance;
Servo Servomot;
String n;
String x;
int i;

int calcdistance(){
digitalWrite(trigPin,LOW);
delayMicroseconds(2);
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin,LOW);
time=pulseIn(echoPin,HIGH);
distance=time*0,034/2;
return distance;
}

void sweep(int k,int z){
for(int j=0;j<=k;j++)
{

for( i=0;i<=180;i=i+z)
Servomot.write(i);
delay(30);
distance=calcdistance();
Serial.println();
Serial.print(“stepen:”);
Serial.print(i);
Serial.print(“°”);
Serial.println();
Serial.print(“udaljenost”);
Serial.print(udaljenost);
Serial.print(“cm”);
}
for( i=180;i>0;i=i-z){
Servomot.write(i);
delay(30);
distance=calcdistance();
Serial.println();
Serial.print(“stepen:”);
Serial.print(i);
Serial.print(“°”);
Serial.println();
Serial.print(“udaljenost”);
Serial.print(udaljenost);
Serial.print(“cm”);

}
}

void setup(){
pinMode (trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
Servomot.attach(10);
Serial.println(“Insert step”);

}
void loop(){
if(Serial.available()){
int f = x.toInt();

if(180 % f==0){
Serial.println(“insert N”);

if(Serial.available()){
int l=n.toInt

sweep(l,f);
}
}
else {
Serial.println("");
}
}
}
Sorry if the question may seem stupid, but im new to programming and arduino overall, and thanks.

In the loop function, there isn't much time between when you ask for N and when you try to read from serial to get it. Since nothing is available yet, that if fails, loop ends and then repeats. We lost the value of f since it was local to that if block and after loop repeats about ten thousand times the user has finally entered a number. It gets seen and stored to f and then it asks for an N but doesn't wait on it and we repeat the whole deal.

So.. making f global variable and delaying the read from serial shall fix my problem?

gamakachi:
So.. making f global variable and delaying the read from serial shall fix my problem?

What happened when you tried that?