by on
Arduino

Once again find myself in a windowless cube. So I 3d printed a varient of a compact camera gimbal and attached an rpi camera to it.  I needed to set up a serial based protocol to talk to it. Its a pretty good example of creating your own protocol as described in the Physical Computing book. The gimbal is servo based and there is one servo for rotation or “yaw” and one for attitude or “pitch”. So the protocol I came up with was:

yXXX<cr>
pXXX<cr>

where XXX represents a number between 0 and 180 (servo values)

Here is the code.


/*
  demonstration of a private protocol.
  we have a serial connected device that has two servos attached to it. 
      one controls the pitch (up and down) 
      one controls the yaw (round and round)
  we send it lines of text in the form 
  s<cr>
  where s is:
    pnnn -- pitch value (0-180)
    ynnn -- yaw value (0-180) 
  Normally it doesnt respond unless weWANNADEBUGTHIS or if it doesnt understand us
  in this case it replys with ?????
 */

#include <Servo.h>
#include <stdlib.h>

#define YAW_PIN 10
#define PITCH_PIN 9
#define YAW_HOME 60

#define PITCH_HOME 35
#define MAXCHARS 10
//#define IWANNADEBUGTHIS 1
#ifdef  IWANNADEBUGTHIS
#define HEY_ARE_YOU_LISTENING_TO_ME 1
#define HEY_I_AM_TALKING_TO_YOU 1
#endif

Servo yaw;
Servo pitch;
char inputBuffer[MAXCHARS];
boolean inputBufferReady;
int inputBufferIndex;

void setup()
{
  // initialize the serial communication:
  Serial.begin(9600);
  yaw.attach(YAW_PIN);
  pitch.attach(PITCH_PIN);
  yaw.write(YAW_HOME);
  pitch.write(PITCH_HOME);

}

boolean gotDataLine (void){
  char inch;
  if (inputBufferIndex>=MAXCHARS) {
    inputBufferIndex=0;
  }
  if (Serial.available()){
    inputBuffer[inputBufferIndex++]=inch=Serial.read();
    inputBuffer[inputBufferIndex]='\0';
    //Serial.print("I received: "); Serial.println(inch);
    if ((inch == '\n') && (inputBufferIndex>0)) {      // I dont want this charachter
      inputBufferIndex--;    // "dtmfa" - dan savage
      return false; 
    }
    if ((inch == '\r') && (inputBufferIndex>1)) {
        inputBuffer[inputBufferIndex-1]='\0';
        inputBufferIndex=0;
        return true;
    }
  }
  return false;
}

void loop() {
  int myValue;
  if (gotDataLine()) {
    myValue=atoi(inputBuffer+1);
    if (myValue>180) myValue=180;
    if (myValue<0) myValue=0;
    switch(inputBuffer[0]) {
      case 'p' : 
#ifdef HEY_ARE_YOU_LISTENING_TO_ME
                 Serial.print("Setting pitch to ");
                 Serial.println(myValue);
#endif
                 pitch.write(myValue);
                 break;
      case 'y' : 
#ifdef HEY_ARE_YOU_LISTENING_TO_ME
                 Serial.print("Setting yaw to ");
                 Serial.println(myValue);
#endif
                 yaw.write(myValue);
                 break;
      default:  Serial.print("?"); Serial.print(inputBuffer); Serial.println("????");
    }
  }
}

 

Leave a Reply

  • (will not be published)