Making Music With MIDI 2

Introduction

Another project converting Arduino input into MIDI output. Like the one before, this project applies a loose definition of the term 'music'. In this project, a rotary encoder is used as the input device.

You Will Need

  • Sparkfun Illuminated Red/Green Rotary Encoder
  • 1 x MIDI Jack
  • 1 x 220 Ohm Resistor
  • USB MIDI Adapter
  • Jumper Wires

Making The Circuit

The LED connections for the rotary encoder are shown in the diagram but not used in the sketch.

Arduino Circuit

Programming The Arduino

An array of 16 notes is defined at the start of the sketch. Turning the encoder changes the note that is playing.

#define encA 14
#define encB 15
#define encPort PINC

int notes[] = {0x30, 0x32, 0x33, 0x34, 0x35, 0x37, 0x39, 0x3a, 0x3b, 0x3c, 0x3e, 0x3f, 0x40, 0x41, 0x43, 0x45};
int playnote = 9;
int previousnote = 9;
int counter = 0;
void setup()
{
  pinMode(encA, INPUT);
  digitalWrite(encA, HIGH);
  pinMode(encB, INPUT);
  digitalWrite(encB, HIGH);
  // Set MIDI baud rate:
  Serial.begin(31250);
}

void loop()
{
  int8_t tmpdata;
  tmpdata = read_encoder();
  if(tmpdata==1) {
    if(counter!=255)
    {
      counter += tmpdata;
    }
  }
  else if(tmpdata==-1)
  {
    if(counter!=0)
    {
      counter += tmpdata;
    }     
  }
  playnote = int(counter/16);
  if (playnote!=previousnote)
  {
    noteOn(0x90, notes[previousnote], 0x00);
    noteOn(0x90, notes[playnote], 0x45);
    previousnote = playnote;
  }
  delay(1);
}

int8_t read_encoder()
{
  static int8_t enc_states[] = {
    0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0      };
  static uint8_t old_AB = 0;
  old_AB <<= 2;      
  old_AB |= ( encPort & 0x03 );  
  return ( enc_states[( old_AB & 0x0f )]);
}



//  plays a MIDI note.  Doesn't check to see that
//  cmd is greater than 127, or that data values are  less than 127:
void noteOn(int cmd, int pitch, int velocity) {
  Serial.write(cmd);
  Serial.write(pitch);
  Serial.write(velocity);
}

Choice of instrument makes a little difference to how bad this sounds.

Challenges

Clearly, the rotary encoder is not the best input device for note selection. This project seems to demonstrate that. However, the rotary encoder would be a good component to use for pitch bending. If you were using VMPK to play the notes, you will see the pitch bender tool and can drag left and right with the mouse to bend the note down or up. The rotary encoder would do this job very well if the note selection was taken care of with something sensible like some buttons.