Thursday, 10 October 2013

My DIY Arduino MIDI controller - 8. MIDI communication: Sparkfun's MIDI shield

Long time no write about this project. Actually I've been too busy this past year to work on the project (or should I say too busy the first months, and too lazy then), but I decided I should get back to it.

I decided to get a Sparkfun MIDI shield to test my code with a reliable MIDI circuit. Haven't tested my code yet but Sparkfun's test code seems to work just fine so I'll keep prototyping with it.

Buttons 2 & 3 send note on messages (as well as last note off), button 1 sends last note off. Potentiometer 1 defines the pitch of the note sent, pot 2 is set to adjust control #74 ("Brightness" according to the MIDI message table - which in Reason will control the synth's filter frequency).

Here is the edited code from Sparkfun's MIDI Shield and MIDI breakout test code:

// SparkFun MIDI Sheild and MIDI Breakout test code
// Defines bare-bones routines for sending and receiving MIDI data
// Written 02/16/10

// defines for MIDI Shield components only

//  Reason 6 MIDI implementation chart:
//  http://dl.propellerheads.se/Reason6/Reason%206%20MIDI%20Implementation%20Chart.pdf

#define KNOB1  0
#define KNOB2  1

#define BUTTON1  2
#define BUTTON2  3
#define BUTTON3  4

#define STAT1  7
#define STAT2  6

byte ccVal;
int pot;
int ccPot;
int note;
int lastNote = -1;
int lastCcVal = -1;

void setup() {
  pinMode(STAT1,OUTPUT);   
  pinMode(STAT2,OUTPUT);
  pinMode(BUTTON1,INPUT);
  pinMode(BUTTON2,INPUT);
  pinMode(BUTTON3,INPUT);

  digitalWrite(BUTTON1,HIGH);
  digitalWrite(BUTTON2,HIGH);
  digitalWrite(BUTTON3,HIGH);

  for(int i = 0;i < 10;i++) // flash MIDI Sheild LED's on startup
  {
    digitalWrite(STAT1,HIGH);  
    digitalWrite(STAT2,LOW);
    delay(30);
    digitalWrite(STAT1,LOW);  
    digitalWrite(STAT2,HIGH);
    delay(30);
  }
  digitalWrite(STAT1,HIGH);   
  digitalWrite(STAT2,HIGH);

  //start serial with midi baudrate 31250
  Serial.begin(31250);     
}

void loop () {

  //*************** MIDI OUT ***************//
  pot = analogRead(KNOB1);
  ccPot = analogRead(KNOB2);
  note = pot / 8;  // convert value to value 0-127
  ccVal = 127 - ccPot / 8;
  
  //  send notes
  if(button(BUTTON2) || button(BUTTON3))
  {
    if (lastNote > -1) Midi_Send(0x80,lastNote, 0x0);
    Midi_Send(0x90,note,0x45);
    lastNote = note;
    while(button(BUTTON2) || button(BUTTON3));
  }
  //  send last note off
  if (button(BUTTON1) && lastNote > -1) {
    Midi_Send(0x80, lastNote, 0x0);
  }
  
  // send cc
  // only if the value has changed
  if (ccVal != lastCcVal) {
    Midi_Send(0xB0, 74, ccVal);
    lastCcVal = ccVal;
  }
}

void Midi_Send(byte cmd, byte data1, byte data2) {
  Serial.write(cmd);
  Serial.write(data1);
  Serial.write(data2);
}

char button(char button_num) {
  return (!(digitalRead(button_num)));
}
<< Previous: 7. STUCK! (Help needed)

No comments:

Post a Comment