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

Code Gorilla
5,6521 gold badge17 silver badges31 bronze badges
asked Aug 17, 2016 at 12:25

1 Answer 1

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.

answered Aug 17, 2016 at 12:37
3
  • 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... Commented Aug 17, 2016 at 12:51
  • What about long num = 0; Commented Aug 18, 2016 at 12:19
  • What happens if you take the wire out of pin 7 and leave it disconnected? Commented Aug 18, 2016 at 12:21

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.