/* MIDI With Two 4021s by Sebastian Tomczak 14 May 2008 */ // MIDI variables int baud = 31250; byte switchVar1 = 0; byte switchVar2 = 0; byte MIDI_channel = 0x00; byte MIDI_nibble = 0x90; byte MIDI_pitches_offset = 60; byte MIDI_on_velocity = 127; byte shadows[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // 4021 Pins int latchPin = 8; int dataPin = 9; int clockPin = 7; // Setup void setup() { Serial.begin(baud); pinMode(latchPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(dataPin, INPUT); } // Main Program void loop() { digitalWrite(latchPin, 1); delayMicroseconds(20); digitalWrite(latchPin, 0); switchVar1 = shiftIn(dataPin, clockPin); switchVar2 = shiftIn(dataPin, clockPin); midiShadows(switchVar1, 0); midiShadows(switchVar2, 8); delay(5); } // Functions byte shiftIn(int myDataPin, int myClockPin) { int i; int temp = 0; int pinState; byte myDataIn = 0; pinMode(myClockPin, OUTPUT); pinMode(myDataPin, INPUT); for (i=7; i>=0; i--) { digitalWrite(myClockPin, 0); delayMicroseconds(2); temp = digitalRead(myDataPin); if (temp) { pinState = 1; myDataIn = myDataIn | (1 << i); } else { pinState = 0; } digitalWrite(myClockPin, 1); } return myDataIn; } void midiShadows (byte data_byte, int i_init) { for(int i = i_init; i < (i_init + 8); i ++) { if(shadows[i] != (data_byte & (1 << i))) { shadows[i] = data_byte & (1 << i); if((switchVar1 & (1 << i)) == 1) { printByte(MIDI_channel + MIDI_nibble); printByte(MIDI_pitches_offset + i_init + i); printByte(MIDI_on_velocity); } if((data_byte & (1 << i)) == 0) { printByte(MIDI_channel + MIDI_nibble); printByte(MIDI_pitches_offset + i_init + i); printByte(0); } } } }