0

I'm working on my first arduino project and i have my first problem dealing with servo motor , i'm trying to control the servo from my pc with this code but it just spining :

  #include <Servo.h>

Servo servo1;  
long num;     

void setup()
{
   servo1.attach(7);
   Serial.begin(9600); 
   Serial.print("Enter Position = ");
}

void loop() 
{ 
  while(Serial.available()>0)
  { 
    num= Serial.parseInt();   
    Serial.print(num);  
    Serial.println(" degree");
    Serial.print("Enter Position = ");
  }
  servo1.write(num);
  delay(15);
}

this is my setup enter image description here

0

I have reformatted your code and the problem becomes very clear (to me).

void loop() 
{ 
  while(Serial.available()>0)
  { 
    num= Serial.parseInt();   
    Serial.print(num);  
    Serial.println(" degree");
    Serial.print("Enter Position = ");
  }
  servo1.write(num);
  delay(15);
}

You are getting some input from the user and then setting the servo to that point.

When there is no data in the Serial buffer you set the servo to the value of write and delay 15ms before checking the buffer again.
I think what you want to do is if there is no data then you don't want to change the Servo position. In short move the servo1.write(num); line inside the } of the while loop.

Now much more importantly the first time you enter loop() you won't have any data there so the servo will be moved to the number held in num which is? Undefined, it could be anything at all from 0 to 4294967295 and if its the upper end of that it will take a while for the servo to get there, it might seem like all it does is spin. ALWAYS INITIALIES VARIABLES BEFORE USE :)

A minor point, your while loop could be, probably should be an if statement. That will prevent a cat sitting on the keyboard and blocking the servo movement.

| improve this answer | |
  • i changed the while with if and moved servo1.write(num) and initiales num but as soon as i upload it it starts moving slowly and when i enter a position it just spins faster... – Radu Mihai Aug 17 '16 at 12:51
  • What about long num = 0; – Code Gorilla Aug 18 '16 at 12:19
  • What happens if you take the wire out of pin 7 and leave it disconnected? – Code Gorilla Aug 18 '16 at 12:21

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.