6 Axis Servo Control Code For Arduino
6 Axis Servo Control Code For Arduino
servoBase;
// declare variables for the 6 servos
servoShoulder;
servoElbow;
servoWrist;
servoWristrotate;
servoGrip;
base = 0;
shoulder = 0;
elbow = 0;
wrist = 0;
wristrotate = 0;
grip = 0;
void setup() {
servoBase.attach(basePin);
// attach all pins to the servos
servoShoulder.attach(shoulderPin);
servoElbow.attach(elbowPin);
servoWrist.attach(wristPin);
servoWristrotate.attach(wristrotatePin);
servoGrip.attach(gripPin);
servoBase.write(1000);
servoShoulder.write(1000);
servoElbow.write(1000);
servoWrist.write(1000);
servoWristrotate.write(1300);
servoGrip.write(600);
Serial.begin(9600);
void loop()
{
if (Serial.available() > 1) {
// if there are more than 1 bytes of data in
the buffer read them in 2 byte chunks
// this will cycle round every 2 bytes. As long as you send 2 bytes at a time
to the buffer
// they should all set fine. If one byte is sent it will wait for the next on
e but
// if no appropriate header byte is found, it will do nothing but clear the b
uffer
//
// the servovalue byte must be from 0 - 180 for the map function to work righ
t
// example setting for all 6 servos:
// ABCDEF
// As a byte sequence this is: 200 65 201 66 202 67 203 68 204 69 205 70
200){
BASE ");
201){
SHOULDER ");
202){
ELBOW ");
}
if (incomingByte ==
Serial.print(" }
if (incomingByte ==
Serial.print(" }
if (incomingByte ==
Serial.print(" }
203){
WRIST ");
204){
WRIST ROTATE ");
205){
GRIP ");
if (incomingByte > 199 && incomingByte < 206) // if command is valid, state s
ervo setting
{
Serial.print(" - VALUE: ");
Serial.print(servovalue, DEC);
Serial.println(" Degrees");
// Serial.println(" ");
}
else
{
Serial.println(" Command not recognised "); // if command header byte is no
t 200-205, signal error
}
if (incomingByte == 200) // sets base to value following 200
{
pos = servovalue;
base = pos; // keep value of base set for future use (not implemented yet)
val0 = map(pos, 0, 180, MIN_PULSE , MAX_PULSE );
servoBase.write(val0);
// tell servo to go to position in vari
able 'pos' from 0 to 180
}
if (incomingByte == 201) // sets shoulder to value following 201
{
pos = servovalue;
shoulder = pos;
val0 = map(pos, 0, 180, MIN_PULSE , MAX_PULSE );
servoShoulder.write(val0);
// tell servo to go to position in
variable 'pos' from 0 to 180
}
if (incomingByte == 202) // sets elbow to value following 202
{
pos = servovalue;
elbow = pos;
val0 = map(pos, 0, 180, MIN_PULSE , MAX_PULSE );
servoElbow.write(val0);
// tell servo to go to position in var
iable 'pos' from 0 to 180
}
if (incomingByte == 203) // sets wrist to value following 203
{
pos = servovalue;
wrist = pos;
val0 = map(pos, 0, 180, MIN_PULSE , MAX_PULSE );
servoWrist.write(val0);
// tell servo to go to position in var
iable 'pos' from 0 to 180
}