I am trying to control a servo using keyboard.
void loop() {
if (Serial.available() > 0) {
x = Serial.parseInt();
while(pos < 180){
pos = x + pos;
Serial.println(pos);
myservo.write(pos);
delay(100);
}
}
else if(Serial.available() > 0){
if(pos>=180){
pos = 0;
delay(500);
myservo.write(0);
}
}
}
Right now the servo takes the input correctly. The only thing is that it wont change positions immediately. It will wait until it hits 180 resets to 0 and then use the input I put in. This isnt the behaviour I want. I want it to change immediately. How Do I set this up?
1 Answer 1
I don't understand why you use 2 Serial.available
condition.
I try to rewrote your program based on my imagination, so do not hate me if its wrong.
Why don't you try this and tell the results:
int pos = 0,x=0;
void loop()
{
while (Serial.available() > 0) x = Serial.parseInt();
pos+=x;
if (pos>180) pos = 0;
myservo.write(pos);
Serial.println (pos);
delay(100);
}
-
I should've been more clear. I want to rotate the servo from 0-180, and once the servo goes past 180 I want to reset it back to 0Elchapo– Elchapo2016年11月11日 07:20:58 +00:00Commented Nov 11, 2016 at 7:20
-
Can you explain what is the serial input used for?duck– duck2016年11月11日 07:22:47 +00:00Commented Nov 11, 2016 at 7:22
-
Getting input from the keyboard. I put in a value between 1-90 and It should rotate the servo that much. Once the servo rotates more than 180 degrees then it should reset to 0; I want to set it up so that immediately upon receiving input it rotates that much. Right now it waits until it resets to adjust the amount I rotate the servoElchapo– Elchapo2016年11月11日 07:26:22 +00:00Commented Nov 11, 2016 at 7:26
-
I think I got your objective. Answer updatedduck– duck2016年11月11日 07:28:22 +00:00Commented Nov 11, 2016 at 7:28
-
Thank you. I was complicating it with all the if statements and conditions. Your answer makes much more sense ThankElchapo– Elchapo2016年11月11日 07:31:05 +00:00Commented Nov 11, 2016 at 7:31