ArduinoをMIDI機器にする

mocolufaを使う
https://github.com/kuwatay/mocolufa

mocolufaをArduino UNO R3で使ってみる
(Arduino UNOといってもR1とR2でハードウェア構成が違うのでR3がおすすめ
→R2で試したけどうまく行かなかったのでR3でやったらうまくいった)

Macさんがdfu-programmerで死んでたのでdfu-programmerは使いたくない
http://qiita.com/tadfmac/items/9136f47ae1eea99a4ef7
AVR ISP mkIIを使って16u2にMIDI化ファーム(mocolufa)をアップロードする

1. 16u2用のファームウェアの書き込み

$ git clone https://github.com/kuwatay/mocolufa.git
$ cd mocolufa/HEX
$ avrdude -p atmega16u2 -F -P usb -c avrispmkii -U flash:w:dualMoco.hex -U lfuse:w:0xFF:m -U hfuse:w:0xD9:m -U efuse:w:0xF4:m -U lock:w:0x0F:m


2. Arduinoスケッチの書き込み

MIDI Libraryを使った
USBシリアルとして認識させるにはGNDとMOSIを短絡する(結線したら一度USBを切断して接続し直すとUSBシリアルとして見えるようになる→終わったら外すとMIDI機器として見えるようになる)
16u2のICSPのピン配置は以下を参考に

MIDI_Basic_IO

#include <MIDI.h>
/*
  Basic I/O MIDI tutorial
  by Franky
  28/07/2009
*/

#define LED 13   		// LED pin on Arduino board

void setup() {
  pinMode(LED, OUTPUT);
  MIDI.begin(4);            	// Launch MIDI with default options
				// input channel is set to 4
}

void loop() {
  if (MIDI.read()) {
    digitalWrite(LED,HIGH);     // Blink the LED
    MIDI.sendNoteOn(42,127,1);  // Send a Note (pitch 42, velo 127 on channel 1)
    delay(1000);		// Wait for a second
    MIDI.sendNoteOff(42,0,1);   // Stop the note
    digitalWrite(LED,LOW);    	
  }
}

3. テスト

http://webaudiodemos.appspot.com/midi-synth/
MocoLUFAとして認識されている

でもやりたいのはOUTPUTとして認識させること

4. テストその2

以下のスケッチをアップロード
MIDI信号が来たらLEDが光る
MIDI_Callbacksの改変

#include <MIDI.h>

void HandleNoteOn(byte channel, byte pitch, byte velocity) { 
  digitalWrite(8,HIGH);
  if (velocity == 0) {
    //this is kinda NoteOff
    digitalWrite(8,LOW);
  }
}


void setup() {
  pinMode(8,OUTPUT);
  MIDI.begin(MIDI_CHANNEL_OMNI);    
  MIDI.setHandleNoteOn(HandleNoteOn);  // Put only the name of the function  
}

void loop() {
  MIDI.read();
}

MIDI用のgemをインストール

$ gem install unimidi

サンプルコード

require 'unimidi'

notes = [36, 40, 43] # C E G
octaves = 5
duration = 0.1

# Prompt the user to select an output
output = UniMIDI::Output.gets

# using their selection...
(0..((octaves-1)*12)).step(12) do |oct|

  notes.each do |note|

    output.puts(0x90, note + oct, 100) # note on
    sleep(duration) # wait
    output.puts(0x80, note + oct, 100) # note off

  end

end

NoteOffが出てないけどLEDが光ったからOK