Friday, February 3, 2012

PD sketch controlling a servo


I’ve got a tiny 9g servo from sparkfun, and decided to control this with a PD patch. There are some things you need to know about this patch/sketch. First off keep in mind that your arduino programmer, and your patch can not control the same comport. Also (on win7) I’ve occasionally had problems with one or the other refusing to release the com port resulting in having to restart both programs (I blame PD, sometimes it doesn’t like to let me switch GPU’s after it closes either.) Another interesting quirk deals with types of Data. As we learned Pd puts out x values in terms of  0-1 (in the case of this patch) so what I did (blatantly so there wasn’t any magic in my patch) was to multiply by 100, then modulus 100 to give me an integer. I don’t know about the Arduino specifically, but I avoid floats with uproccessors in general. Bad juju for a beginner IMHO. Then out to the comport. There may be a more elegant solution for the comport selection process, but I simply used device manager to find out what comport my arduino was on, (you need to know to program it anyway which is annoying) then simply put that as the argument for the patch. on the arduino side, you have to start serial communications, then read that value into some variable. It seems like I did a little magic in the sketch, but not really the map function is an awesome function to use (I found it when I was outputting sounds through the arduino) and the servo library is a huge help in something like this. For the sketch I modified the examples->servo->knob. I just replaced the potentiometer bit with the incoming serial values.
and the sketch...

/*
So this sketch will control a servo from data sent from PD

if I keep this up I'm likely to find my self halfway to jupider arguing with my spaceship as to whether or not it will let me back in.


 */
#include
Servo myservo;
int val;

void setup() {
  // initialize serial comms 
  Serial.begin(9600);
 myservo.attach(9); //Servo is going to be controlled on pin 9 
}

void loop() {
  if (Serial.available()){//check to see if something is coming in 
  val = map(Serial.read(),0,99,0,179);//this maps the in comeing value to a value that the arduino can send to a servo. 
  }

    myservo.write(val); // this 'writes' the value to the servo
    delay(15);  // servos don't work instantaniously.
  

  
}//abandon all hope ye who enter here....



No comments:

Post a Comment