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?

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);
}
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
    – Elchapo
    Nov 11 '16 at 7:20
  • Can you explain what is the serial input used for?
    – dhimaspw
    Nov 11 '16 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
    – Elchapo
    Nov 11 '16 at 7:26
  • I think I got your objective. Answer updated
    – dhimaspw
    Nov 11 '16 at 7:28
  • Thank you. I was complicating it with all the if statements and conditions. Your answer makes much more sense Thank
    – Elchapo
    Nov 11 '16 at 7:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.