I would like to move my servo motor (SM-S2309S) between random angles. In order to do so, I used this simple code:
#include <Servo.h>
Servo servoMain; // Define our Servo
// SM-S2309S angular speed
float speed = 0.12/60;
void move(int from, int to)
{
// initiate the move to the new angle
servoMain.write(to);
// wait for the movement to actually happen over the actual angle to move through
delay(1000 * speed * int(from-to));
}
void setup()
{
servoMain.attach(10); // servo on digital pin 10
Serial.begin(115200);
// move to center as a start
servoMain.write(90);
delay(1000);
}
void loop()
{
// the previous angle, initially set as center (per the setup() call)
static int oldangle = 90;
// apparently 15 to 165 deg is a safe range
int newangle = random(15,165);
Serial.println(newangle);
move(oldangle,newangle);
oldangle = newangle;
}
It starts by placing the arm in the center (in the setup()
function) and then should generate a random number (the new angle to go to), in a loop.
What I get is the initial position, then two moves (counterclockwise, then clockwise). The output on the serial console shows 22
and 64
, which is consistent with the two moves.
Then everything stops. There is no error message on the console (I do not expect one to be, but I am not sure if there could be any feedback from the Arduino, being a complete beginner). What can be the reason for this stop, after two successful loops?
loop()
(I guess that this is what you meant, otherwise the output of the new angles on the console would have been enough, no matter of the servo moves or not) – WoJ Dec 29 '16 at 16:31