Hello to all
I've hacked an old inkjet printer for use with various musical instruments. I'm particularly interested in using the print head and rail assembly to track back and fourth over sets of strings. While I have had success in positioning the head at various target points within my loop, once I add midi code to my sketch she fails to budge. The code compiles and the print head travels to both ends during setup but then stops altogether. Could someone please point out where I'm going wrong?
Thanks, Robbie
#include <MIDI.h>
MIDI_CREATE_DEFAULT_INSTANCE();
int enablePin = 10;
int motor1 = 9;
int motor2 = 8;
int encoderI = 2;
int encoderQ = 3;
byte target1 = 2000;
byte target2 = 400;
byte target3 = 3000;
byte target4 = 1000;
#define encoderI 2
#define encoderQ 3 // Only use one interrupt in this example
volatile int count;
void setup() {
 MIDI.begin(MIDI_CHANNEL_OMNI);
 MIDI.setHandleNoteOn(Note);
 count = 0;
 Serial.begin(115200);
 pinMode(motor1, OUTPUT);
 pinMode(motor2, OUTPUT);
 pinMode(enablePin, OUTPUT);
 pinMode(encoderI, INPUT); attachInterrupt(digitalPinToInterrupt(2), handleEncoder, CHANGE);
 pinMode(encoderQ, INPUT);
 // Finding home position by driving slowly to both end positions
 setMotor (0);
 Delay(1500);
 setMotor(100);
 Delay(1000);
 count = 0;
 setMotor(-100);
 Delay(900);
 setMotor(0);
 count = 0;
}
void loop() {
 MIDI.read();
}
void Note(byte channel, byte note, byte velocity) {
 if (note == 60)
 {
  driveTo(target1);
 }
 if (note == 62)
 {
  driveTo(target2);
 }
 if (note == 64)
 {
  driveTo(target3);
 }
 if (note == 65)
 {
  driveTo(target4);
 }
}
void setMotor(int speed) {
 // make sure speed variable is within accepted margins
 if (speed == 0) {
  analogWrite(enablePin, speed);
  digitalWrite(motor1, HIGH);
  digitalWrite(motor2, LOW);
 }
 else if (speed > 0 ) {
  if (speed >= 255) {
   speed = 255;
  }
  speed = map( speed, 0, 255, 200, 255);
  analogWrite(enablePin, speed);
  digitalWrite(motor1, HIGH);
  digitalWrite(motor2, LOW);
 }
 else {
  if (speed <= -255) {
   speed = -255;
  }
  speed = map (speed, -255, -1, -255, -200);
  analogWrite(enablePin, -1 * speed);
  digitalWrite(motor1, LOW);
  digitalWrite(motor2, HIGH);
 }
}
void handleEncoder() {
 if (digitalRead(encoderI) == digitalRead(encoderQ))
 { count++;
 }
 else
 { count--;
 }
}
void Delay(int interval) {
 unsigned long startTime = millis();
 while (millis() - startTime <= interval ) {
  // do nothing while waiting for time to pass
  Serial.println(count);
 }
 return;
}
void driveTo(int setpoint) {
 // basic Proportional feedback control for driving to set position
 float gain = 0.08;
 int error = 0;
 error = setpoint - count;
 while (error >= 20 || error <= -20) {
  error = setpoint - count;
  int control = gain * error;
  setMotor(control);
  Serial.print(count);
  Serial. print (" ");
  Serial.println(error);
 }
 // turn motor off when setpoint is reached
 setMotor (0);
}