Hi
I am trying to control a servo to turn between two angles by turning the potentiometer between 0 and 180 .
so if the potentiometer is over 100 for 3 sec the servo will turn to angle 1, if the potentiometer is turned again to 0 and then again to 180 for another 3 sec(starting from the point were the potentiometer is over 100) the servo should turn to angle 2.
The code I wrote worked correctly for the first part only so the servo will turn to angle 1 after 3 sec but the second part has an issue that the servo will immediately turn to angle 2 without waiting for 3 sec (I guess its measuring the time even before the 100 point ).
I tried to separate the two actions by adding a 50ms time interval but it didn't work .
here is my code :
#include <Servo.h>;
Servo servo1 ;
#define pos_ini 0
int winkel=1000;
int p1;
unsigned long previus_millis1 = 0;
unsigned long previus_millis2 = 0;
unsigned long seconds1=3000;
unsigned long seconds2=3000;
const int inbetween_Time=50;
unsigned long currentMillis1;
unsigned long currentMillis2;
int x=0;
int b=0;
bool timerstart1= false;
bool timerstart2= false;
void setup() {
// put your setup code here, to run once:
Serial.begin (9600);
servo1.attach(11);
servo1.write(pos_ini);
}
void loop() {
p1=analogRead(1);
p1=map(p1,0,1023,0,180); // potentiometer turnes between 0 and 180
currentMillis1 = millis();
Serial.println (p1);
Serial.print ("x=");
Serial.println (x);
if( currentMillis1-previus_millis1>inbetween_Time){ // wait 50 ms
if ((p1<100)&&(x==0)){x=1; // potentiometer is not turned yet
}
while (p1>100){ //potentiometer is turned to 180
Serial.println( timerstart1);
if ( timerstart1== false){
previus_millis1=currentMillis1;
timerstart1=true;
}
if( timerstart1==true){
if ( (x==1) &&(currentMillis1-previus_millis1>=seconds1)){ // servo will turn after 3000ms
winkel=2000;
Serial.println(currentMillis1-previus_millis1);
Serial.println("Done");
servo1.writeMicroseconds(winkel);
timerstart1=false;
// currentMillis = previus_millis ;
x=2;
}
}
break;
}
}
currentMillis2=millis();
if ((p1<100)&&(x==2)&&(b==0)){ // potentiometer turned back to 0
x=3;
b=1;
}
if( currentMillis2-previus_millis2>inbetween_Time){ // wait 50 ms
while (p1>100){// potentiometer turned to 180
Serial.println( timerstart1);
if ( timerstart2== false){
previus_millis2=currentMillis2;
timerstart2=true;
}
if( timerstart2==true){
if ( (x==3)&&(b==1) &&(currentMillis2-previus_millis2>=seconds2)){ //servo should turn after 3000ms but its turning instantly after turning the potentimeter
Serial.println(currentMillis2-previus_millis2);
Serial.println("Done");
servo1.writeMicroseconds( 1000);
timerstart2=false;
x=4;
b=2;
}
}
break;
}
}
if ((p1<100)&&(x==4)&&(b==2)){b=0;// potentiometer turned back to 0
x=0;}
}