Even More Example Code SparkFun Robotic Arm

March 3, 2013
Tags: ,

This code allows you to control the arm with serial commands.  The keys 1-6 are used to control the servos.


/*
Robot console

This code will control the arm via serial commands

*/

#include Servo.h

Servo servo1; //base-pan
Servo servo2; //arm-tilt
Servo servo3; //claw

void setup()
{
  Serial.begin(9600);
  servo1.attach(9);  //pan range is 20 to 140
  servo2.attach(10); //tilt range is 0 to 179
  servo3.attach(11); //claw range is 70 to 130
}

void loop()
{

  int incomingData = 0;
  
  //listen for serial input
  Serial.flush();
  while(Serial.available() > 0) {
    incomingData = Serial.read();
    if(incomingData == 49 && servo1.read() > 20) {
      int pos;
      int pos2;
      pos = servo1.read();
      pos2 = servo1.read() - 5;
      for(pos; pos > pos2; pos -= 1)
      {
        servo1.write(pos);
        Serial.print("PanNum: ");
        Serial.println(pos);
      
        delay(25);
      }      
    }
    else if (incomingData == 50 && servo1.read() < 140) {
      int pos;
      int pos2;
      pos = servo1.read();
      pos2 = servo1.read() + 5;
      for(pos; pos < pos2; pos += 1)
      {
        servo1.write(pos);
        Serial.print("PanNum: ");
        Serial.println(pos);
        delay(25);
      }
    }
    else if (incomingData == 51 && servo2.read() > 6) {
      int pos;
      int pos2;
      pos = servo2.read();
      pos2 = servo2.read() - 5;
      for(pos; pos > pos2; pos -= 1)
      {
        servo2.write(pos);
        Serial.print("TiltNum: ");
        Serial.println(pos);
        delay(25);
      }
    }
    else if (incomingData == 52 && servo2.read() < 174) {
      int pos;
      int pos2;
      pos = servo2.read();
      pos2 = servo2.read() + 5;
      for(pos; pos < pos2; pos += 1)
      {
        servo2.write(pos);
        Serial.print("TiltNum: ");
        Serial.println(pos);
        delay(25);
      }
    }
    else if (incomingData == 53 && servo3.read() > 76) {
      int pos;
      int pos2;
      pos = servo3.read();
      pos2 = servo3.read() - 5;
      for(pos; pos > pos2; pos -= 1)
      {
        servo3.write(pos);
        Serial.print("ClawNum: ");
        Serial.println(pos);
        delay(25);
      }
    }
    else if (incomingData == 54 && servo3.read() < 124) {
      int pos;
      int pos2;
      pos = servo3.read();
      pos2 = servo3.read() + 5;
      for(pos; pos < pos2; pos += 1)
      {
        servo3.write(pos);
        Serial.print("ClawNum: ");
        Serial.println(pos);
        delay(25);
      }
    }
  }
}

 

 

Leave a Reply