I built a 3 axis skull for Halloween, the skull can: nod, spin and tilt side to side using servos.
The sketch I made will sweep a servo a random number of degrees; it then will pause for a random amount of time and then sweep back a random numbers of degrees again. I define the allowable travel range (for example, between 45 and 135 degrees). I also control the speed of the servo to keep the movements looking realistic.
I am very happy with how the sketch works; the problem is that I cannot figure out how to run 3 servos at the same time. I am using a “for loop” to control the speed and I cannot figure out how to get 3 random movements at the same time (e.g. Servo 1 moves 35 degrees while Servo 2 moves 95 degrees). I also need to be able to set the allowable range for each servo independently (e.g. Servo 1 can move from 45 to 135 degrees and Servo 2 can move from 25 to 155 degrees).
This is the most complicated sketch I have made to date to give you a understanding of my skill (or lack thereof) level.
#include <Servo.h>
Servo nServo; // create servo object to control a servo
int target; // where servo arm is to move
int last = 90; // servo are starting point
int now = 90; // current servo are location
void setup() {
nServo.attach(9);
nServo.write(now);
}
void loop() {
delay(random(1500, 3500)); //sets time between movements
target = random(25, 155); //sets value to move servo arm to and define allowable range
if (now <= target) { // if-else decides what direction arm needs to move
for (now = last; now <= target; now++) { // for loop moves servo 1 degree at a time and controls speed
nServo.write(now);
delay(20);
}
}
else {
for (now = last; now > target; now--) {
nServo.write(now);
delay(20);
}
}
last = target; // resets starting point of servo arm
}