MeerkatsCode

This is the code on the Arduino which controls the robots. Portions of it are forked from this tutorial about the sparkfun ez stepper motor driver.


#include <MIDI.h>

#define DIR_PIN 2
#define STEP_PIN 3

byte diddlyPitchChannel = 4;
byte diddlyTrigChannel = 5;

int currentStep = 0;
int goalStep = 0;
int scale = 1800;
float speed = 0.3;

int frets[19] = {0, 101, 196, 286, 371, 451, 527, 598, 666,
                 729, 789, 846, 900, 950, 998, 1043, 1085, 1125, 1163};

void HandleNoteOn(byte channel, byte pitch, byte velocity) {

  // Do whatever you want when you receive a Note On.
  if (channel == diddlyTrigChannel)
  {
  digitalWrite(diddlyTrigChannel, HIGH);
  }
  if (channel == diddlyPitchChannel)
  {
  goalStep = frets[pitch];
  }
  if (channel == 6)
  {
  digitalWrite(6, HIGH);
  }

  if (velocity == 0) {
    
    //blinkbool = false;
    // This acts like a NoteOff.
  }
}
void HandleNoteOff(byte channel, byte pitch, byte velocity) {
 
  if (channel == 13)
  {
  digitalWrite(13, LOW);
  }
  if (channel == 7)
  {
  digitalWrite(7, LOW);
  }
  if (channel == 6)
  {
  digitalWrite(6, LOW);
  }
  if (channel == 5)
  {
    digitalWrite(5, LOW);
  }
 
}

void setup() {
  pinMode(DIR_PIN, OUTPUT);
  pinMode(STEP_PIN, OUTPUT);
 
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(13, OUTPUT);
  // Initiate MIDI communications, listen to all channels
  MIDI.begin(MIDI_CHANNEL_OMNI);    
 
  // Connect the HandleNoteOn function to the library, so it is called upon reception of a NoteOn.
  MIDI.setHandleNoteOn(HandleNoteOn);  // Put only the name of the function
  MIDI.setHandleNoteOff(HandleNoteOff);  
}

void loop(){
 
  MIDI.read();
 
  //rotate a specific number of degrees
  if (currentStep < goalStep)
  {
  currentStep++;
  rotateDeg(1, speed);
  }
 
  if (currentStep > goalStep)
  {
  currentStep--;
  rotateDeg(-1, speed);
  }
  //delay(1000);

  //rotateDeg(-360, .25);  //reverse
  //delay(1000);

}



void rotate(int steps, float speed){
  //rotate a specific number of microsteps (8 microsteps per step) - (negitive for reverse movement)
  //speed is any number from .01 -> 1 with 1 being fastest - Slower is stronger
  int dir = (steps > 0)? HIGH:LOW;
  steps = abs(steps);

  digitalWrite(DIR_PIN,dir);

  float usDelay = (1/speed) * 70;

  for(int i=0; i < steps; i++){
    digitalWrite(STEP_PIN, HIGH);
    delayMicroseconds(usDelay);

    digitalWrite(STEP_PIN, LOW);
    delayMicroseconds(usDelay);
  }
}

void rotateDeg(float deg, float speed){
  //rotate a specific number of degrees (negitive for reverse movement)
  //speed is any number from .01 -> 1 with 1 being fastest - Slower is stronger
  int dir = (deg > 0)? HIGH:LOW;
  digitalWrite(DIR_PIN,dir);

  int steps = abs(deg)*(1/0.225);
  float usDelay = (1/speed) * 70;

  for(int i=0; i < steps; i++){
    digitalWrite(STEP_PIN, HIGH);
    delayMicroseconds(usDelay);

    digitalWrite(STEP_PIN, LOW);
    delayMicroseconds(usDelay);
  }
}