1

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?

asked Nov 11, 2016 at 7:10

1 Answer 1

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);
}
answered Nov 11, 2016 at 7:18
5
  • 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 0 Commented Nov 11, 2016 at 7:20
  • Can you explain what is the serial input used for? Commented 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 servo Commented Nov 11, 2016 at 7:26
  • I think I got your objective. Answer updated Commented 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 Thank Commented Nov 11, 2016 at 7:31

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.