/* 4 MIDI Controlled Digital Potentiometers by Sebastian Tomczak 24 May 2008 */ /* INITIALISATION */ // Pins int ss1 = 2; int ss2 = 3; int clk = 4; int mosi = 5; // Variables and bytes byte pot0 = B00010001; // write to pot 0 byte pot1 = B00010010; // write to pot 1 int baud = 31250; byte data; byte channel; byte ccnumber; byte ccvalue; int flag_previous = 0; /* flag_previous meanings: -1 = note off status -2 = note off pitch 0 = no action / waiting 1 = note on status 2 = pitch 3 = cc status 4 = cc number */ /* SETUP */ void setup() { Serial.begin(baud); pinMode(ss1, OUTPUT); pinMode(ss2, OUTPUT); pinMode(clk, OUTPUT); pinMode(mosi, OUTPUT); digitalWrite(ss1, HIGH); digitalWrite(ss2, HIGH); } /* MAIN PROGRAM */ void loop () { if(Serial.available() > 0) { data = Serial.read(); // deal with cc data if((data >= 0xb0) && (data < 0xc0) && (flag_previous == 0)) { channel = data & B00001111; flag_previous = 3; } else if((data < 0x80) && (flag_previous == 3)) { ccnumber = data; flag_previous = 4; } else if((data < 0x80) && (flag_previous == 4)) { ccvalue = data; doCC(channel, ccnumber, ccvalue); flag_previous = 0; } // done with cc data } } /* FUNCTIONS */ void spi_transfer(byte working) { for(int i = 1; i <= 8; i++) { if (working > 127) { digitalWrite (mosi,HIGH); } else { digitalWrite (mosi, LOW); } digitalWrite (clk,HIGH); working = working << 1; digitalWrite(clk,LOW); } } void spi_out(int ss, byte cmd_byte, byte data_byte) { digitalWrite (ss, LOW); spi_transfer(cmd_byte); spi_transfer(data_byte); digitalWrite(ss, HIGH); } void doCC(byte channel, byte ccnumber, byte ccvalue) { if(ccnumber == 1) { if(channel == 0) { spi_out(ss1, pot0, ccvalue); } else if(channel == 1) { spi_out(ss1, pot1, ccvalue); } else if(channel == 2) { spi_out(ss2, pot0, ccvalue); } else if(channel == 3) { spi_out(ss2, pot1, ccvalue); } } }