Hi all,
I'm trying to make a simple servo go slow, by putting a delay in a 'for' loop (as suggested in the forums) - but it doesn't seem to work. My sketch is turning a pan/tilt head with two servos either left, right or back at random, then returning to the centre (90 for the horizontal servo) at a slower speed using the 'returnspeed' variable, also determined in random microseconds.
I've tried to make this work, but to no avail - is there a basic mistake I'm missing? Any help greatly appreciated, so I can move on to the next stage of the project...
Cheers,
Jonathan.
Here's the code:
#include <Servo.h>
Servo hservo; // horizontal servo
Servo vservo; // vertical servo
int hposval = 90; // starting value for position info
int vposval = 180; // v servo forwards
void setup()
{
vservo.attach(11); // vertical servo pin 11
hservo.attach(3); // horizontal servo pin 3
randomSeed (analogRead(5)); // reset random numbers
Serial.begin(9600);
vservo.write (vposval); // set vertical servo to front position
hservo.write (hposval); // set horizontal servo to middle position
}
void loop()
{
long turndirection = random (30); // pick random number between 0 and 29
if (turndirection < 10) {
hposval = 0;
hservo.write (hposval); // turn left
Serial.println ("Turn Direction is LEFT");
}
else if ((turndirection > 9) && (turndirection <20)) {
hposval = 180;
hservo.write (hposval); // turn right
Serial.println ("Turn Direction is RIGHT");
}
else {
vposval = 0;
vservo.write (vposval); // vertical servo turns back
Serial.println ("Turn Direction is BACK");
}
Serial.print ("Horizontal position is: ");
Serial.println (hposval);
Serial.print ("Vertical position is: ");
Serial.println (vposval);
long wait = random (2000,5000);
Serial.print ("Wait time is: ");
Serial.print (wait / 1000);
Serial.println (" seconds.");
delay (wait); // pause before turning back to centre
long returnspeed = random (10,101); // set random speed for servo to return to centre
Serial.print ("Return speed is: ");
Serial.println (returnspeed);
if (hposval == 0) { // if horizontal position is left
for (hposval = 0; hposval <= 90; hposval +=1); // turn back to centre
{hservo.write (hposval);
delay (returnspeed);}
}
else if (hposval == 180) { // if horizontal position is right
for (hposval = 180; hposval >= 90; hposval -=1); // turn back to centre
{hservo.write (hposval);
delay (returnspeed);}
}
else { // if vertical position is back
for (vposval = 0; vposval <= 180; vposval +=1); // turn back to front
{vservo.write (vposval);
delay (returnspeed);}
}
delay (wait); // long random wait, then loop to start
}