Servo programing help.

Hi! Can you please help me with my code? I attach a copy below.

I want to generate a random sweep for four servo connected to 5,6,9 and 10, the problem I have is I don’t know enough about the code to figure out where I have gone wrong. Same old story, I have taken the standard code from the examples “sweep” and tried to add a second servo using a random position genorator.

How would it be with four servo?

I would appreciate some advice with the following case and if you can help me to understand where I went wrong I should not make the same mistake next time :slight_smile: (probably!)

Thanks in advance.

Kind regards

Björn

// Sweep
// by BARRAGAN <http://barraganstudio.com>
// This example code is in the public domain.


#include <Servo.h>

Servo xservo; // create servo object to control a servo 
Servo yservo; // a maximum of eight servo objects can be created 

int xpos = 0; // variable to store the servo position 
int ypos; 
int ynew; 

void setup() 
{ 
xservo.attach(9); // attaches the servo on pin 9 to the servo object 
yservo.attach(10); 
ypos = random(180); 
} 
#define change(a,b) if (a>b) a--; else (a 
void loop() 
{ 
for(xpos = 0; xpos < 180; xpos += 1) // goes from 0 degrees to 180 degrees 
{ // in steps of 1 degree 
xservo.write(xpos); // tell servo to go to position in variable 'pos' 
delay(10); // waits 15ms for the servo to reach the position 
} 

for(xpos = 180; xpos>=1; xpos-=1) // goes from 180 degrees to 0 degrees 
{ 
xservo.write(xpos); // tell servo to go to position in variable 'pos' 
delay(10); // waits 15ms for the servo to reach the position 
} 
ynew = random(180); 
while ((ypos != ynew)) 
{ 
change(ypos,ynew) 
yservo.write(ypos); 
delay (10); 
} 
}

This does not look right, but I can't figure what you would like it to do

ynew = random(180);
 while ((ypos != ynew))
 {
 change(ypos,ynew)
 yservo.write(ypos);
 delay (10);
 }

If you just want it to go to a new random position each time through loop() you just need

ynew = random(180);
 yservo.write(ynew);
 delay (10);

...R

change(ypos,ynew)
What is happening here?

#define change(a,b) if (a>b) a--; else (a

This can’t possibly be right, but I can’t figure out what it was meant to do.

Why don’t you just write the if statement where you want it instead of trying to use a macro here. Or write a function. Macros that do code can cause all sorts of headaches if you don’t know what you’re doing.

while ((ypos != ynew)) 
{ 
if(ypos > ynew)
{
     ypos--;
}
else
{
     ypos++;
}
yservo.write(ypos); 
delay (10); 
}

In addition to what the others said, look at this code for moving many servos http://forum.arduino.cc/index.php?topic=59530.msg430572#msg430572 (read the whole thread) and here is the result : http://vimeo.com/24959129#