Guest User

Audio MIDI Controller

a guest
Jul 22nd, 2015
304
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  // Basic MIDI Controller code for reading all of the Arduino's digital and analogue inputs
  2. // and sending them as MIDI messages to the host PC.
  3. //
  4. // Authors: Michael Balzer, David H.
  5. //
  6. // Revision History:
  7. // Date        |  Author  |  Change
  8. // ---------------------------------------------------
  9. // 2011-02-22  |  MSB     |  Initial Release
  10. // 2011-03-01  |  MSB     |  Updated MIDI output to send same MIDI signals as official MIDI Fighter
  11. //             |          |  Reduced debounce length from 5ms to 2ms
  12. // 2011-03-14  |  MSB     |  Modified analogue input logic so only pins moved within the timer
  13. //             |          |    period are updated, not all of them.
  14. //             |          |  Experimental code added for higher speed (but less accurate) analogue reads
  15. //             |          |  Reduced analogue timer length from 1000ms to 250ms
  16. // 2011-03-21  |  MSB     |  Removed TimerOne library. Each analogue pin now maintains its own time
  17. //             |          |    since it was last moved, rather than one timer for all pins. This stops
  18. //             |          |    sending jittery movements on analogue inputs which haven't been touched.
  19. // 2011-04-11  |  TC      |  Teensy USB code added.
  20. //             |  MSB     |  Updated with #defines for Arduino Mega and Teensy USB for easy compilation
  21. // 2011-10-23  |  MSB     |  Added default #defines for Teensy 2.0 and Teensy++ 2.0 digital pins
  22. //             |          |  Removed #defines for Teensy 1.0 as usbMIDI is not supported
  23. // 2012-01-20  |  MSB     |  Updated to support Arduino 1.0 (updated Serial.print to Serial.write)
  24. //             |          |
  25. // 2015-07-22  |  DH      |  Modified to support a unique model of the controller with an Arduino Mega 2560.
  26. //
  27. //
  28. // This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
  29. // See http://creativecommons.org/licenses/by-nc-sa/3.0/ for license details.
  30.  
  31. // THIS IS A MODIFICATION OF THE CODE THAT ONLY WORKS FOR ARDUINO MEGA 2560. -David H.
  32.  
  33. // Uncomment this line to send debug messages to the serial monitor
  34. //#define DEBUG
  35.  
  36. //#define FASTADC
  37. // defines for setting and clearing register bits
  38.  
  39.  
  40. #ifndef cbi
  41. #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
  42. #endif
  43. #ifndef sbi
  44. #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
  45. #endif
  46.  
  47. // MIDI mapping taken from http://www.nortonmusic.com/midi_cc.html
  48. #define MIDI_CC_MODULATION 0x01
  49. #define MIDI_CC_BREATH 0x02
  50. #define MIDI_CC_VOLUME 0x07
  51. #define MIDI_CC_BALANCE 0x08
  52. #define MIDI_CC_PAN 0x0A
  53. #define MIDI_CC_EXPRESSION 0x0B
  54. #define MIDI_CC_EFFECT1 0x0C
  55. #define MIDI_CC_EFFECT2 0x0D
  56.  
  57. #define MIDI_CC_GENERAL1 0x0E
  58. #define MIDI_CC_GENERAL2 0x0F
  59. #define MIDI_CC_GENERAL3 0x10
  60. #define MIDI_CC_GENERAL4 0x11
  61. #define MIDI_CC_GENERAL5 0x12
  62. #define MIDI_CC_GENERAL6 0x13
  63. #define MIDI_CC_GENERAL7 0x14
  64. #define MIDI_CC_GENERAL8 0x15
  65. #define MIDI_CC_GENERAL9 0x16
  66. #define MIDI_CC_GENERAL10 0x17
  67. #define MIDI_CC_GENERAL11 0x18
  68. #define MIDI_CC_GENERAL12 0x19
  69. #define MIDI_CC_GENERAL13 0x1A
  70. #define MIDI_CC_GENERAL14 0x1B
  71. #define MIDI_CC_GENERAL15 0x1C
  72. #define MIDI_CC_GENERAL16 0x1D
  73. #define MIDI_CC_GENERAL17 0x1E
  74. #define MIDI_CC_GENERAL18 0x1F
  75.  
  76. #define MIDI_CC_GENERAL1_FINE 0x2E
  77. #define MIDI_CC_GENERAL2_FINE 0x2F
  78. #define MIDI_CC_GENERAL3_FINE 0x30
  79. #define MIDI_CC_GENERAL4_FINE 0x31
  80. #define MIDI_CC_GENERAL5_FINE 0x32
  81. #define MIDI_CC_GENERAL6_FINE 0x33
  82. #define MIDI_CC_GENERAL7_FINE 0x34
  83. #define MIDI_CC_GENERAL8_FINE 0x35
  84. #define MIDI_CC_GENERAL9_FINE 0x36
  85. #define MIDI_CC_GENERAL10_FINE 0x37
  86. #define MIDI_CC_GENERAL11_FINE 0x38
  87. #define MIDI_CC_GENERAL12_FINE 0x39
  88. #define MIDI_CC_GENERAL13_FINE 0x3A
  89. #define MIDI_CC_GENERAL14_FINE 0x3B
  90. #define MIDI_CC_GENERAL15_FINE 0x3C
  91. #define MIDI_CC_GENERAL16_FINE 0x3D
  92. #define MIDI_CC_GENERAL17_FINE 0x3E
  93. #define MIDI_CC_GENERAL18_FINE 0x3F
  94.  
  95. #define MIDI_CC_SUSTAIN 0x40
  96. #define MIDI_CC_REVERB 0x5B
  97. #define MIDI_CC_CHORUS 0x5D
  98. #define MIDI_CC_CONTROL_OFF 0x79
  99. #define MIDI_CC_NOTES_OFF 0x78
  100.  
  101. #define NOTE_C0 0x00 // 0
  102. #define NOTE_C1 0x0C // 12
  103. #define NOTE_C2 0x24 // 24
  104. #define NOTE_C3 0x36 // 36
  105. #define NOTE_C4 0x30 // 48
  106. #define NOTE_C5 0x3C // 60
  107.  
  108.   // Number of digital inputs. Can be anywhere from 0 to 68.
  109.   #define NUM_DI 52
  110.   // Number of analogue inputs. Can be anywhere from 0 to 16.
  111.   #define NUM_AI 16
  112.  
  113.  
  114.   #define MIDI_CHANNEL 1
  115.   // First note, starting from upper left button
  116.   #define NOTE NOTE_C5
  117.   // This pin order corresponds to the top left button being zero, increasing by one as we move from left to right, top to bottom
  118.   // 0  1  2  3  4
  119.   // 5  6  7  8  9
  120.   // 10 11 12 13 14
  121.   // 15 16 17 18 19
  122.   // This array size must match NUM_DI above.
  123.     #define DIGITAL_PIN_ORDER 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53
  124.  
  125.  
  126.  
  127.   #define ANALOGUE_PIN_ORDER A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, A13, A14, A15
  128.  
  129.   #define LED_PIN 13
  130.  
  131.  
  132. #define MIDI_CC MIDI_CC_GENERAL1
  133.  
  134. // Comment this line out to disable button debounce logic.
  135. // See http://arduino.cc/en/Tutorial/Debounce on what debouncing is used for.
  136. #define DEBOUNCE
  137. // Debounce time length in milliseconds
  138. #define DEBOUNCE_LENGTH 2
  139.  
  140.  
  141. // Comment this line out to disable analogue filtering
  142. #define ANALOGUE_FILTER
  143. // A knob or slider movement must initially exceed this value to be recognised as an input. Note that it is
  144. // for a 7-bit (0-127) MIDI value.
  145. #ifdef FASTADC
  146. #define FILTER_AMOUNT 3
  147. #else
  148. #define FILTER_AMOUNT 2
  149. #endif
  150. // Timeout is in microseconds
  151. #define ANALOGUE_INPUT_CHANGE_TIMEOUT 250000
  152.  
  153.  
  154. // Array containing a mapping of digital pins to channel index.
  155. byte digitalInputMapping[NUM_DI] = {DIGITAL_PIN_ORDER};
  156.  
  157. // Array containing a mapping of analogue pins to channel index. This array size must match NUM_AI above.
  158. byte analogueInputMapping[NUM_AI] = {ANALOGUE_PIN_ORDER};
  159.  
  160. // Contains the current state of the digital inputs.
  161. byte digitalInputs[NUM_DI];
  162. // Contains the current value of the analogue inputs.
  163. byte analogueInputs[NUM_AI];
  164.  
  165. // Variable to hold temporary digital reads, used for debounce logic.
  166. byte tempDigitalInput;
  167. // Variable to hold temporary analogue values, used for analogue filtering logic.
  168. byte tempAnalogueInput;
  169.  
  170. // Preallocate the for loop index so we don't keep reallocating it for every program iteration.
  171. byte i = 0;
  172. byte digitalOffset = 0;
  173. // Variable to hold difference between current and new analogue input values.
  174. byte analogueDiff = 0;
  175. // This is used as a flag to indicate that an analogue input is changing.
  176. boolean analogueInputChanging[NUM_AI];
  177. // Time the analogue input was last moved
  178. unsigned long analogueInputTimer[NUM_AI];
  179.  
  180. #ifdef DEBUG
  181. unsigned long loopTime = 0;
  182. unsigned long serialSendTime = 0;
  183. #endif
  184.  
  185. void setup()
  186. {
  187.   // Taken from http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1208715493/11
  188.   #ifdef FASTADC
  189.     // set prescale to 16
  190.     sbi(ADCSRA,ADPS2) ;
  191.     cbi(ADCSRA,ADPS1) ;
  192.     cbi(ADCSRA,ADPS0) ;
  193.   #endif
  194.  
  195.   // Only enable serial on the Arduino or when debugging. The Teensy board should be set as a usb-midi device so serial is not needed.
  196.     // Enable serial I/O at 115200 kbps. This is faster than the standard MIDI rate of 31250 kbps.
  197.     // The PC application which we connect to will automatically take the higher sample rate and send MIDI
  198.     // messages out at the correct rate. We only send things faster in case there is any latency.
  199.     Serial.begin(115200);
  200.  
  201.   // Initialise each digital input channel.
  202.   for (i = 0; i < NUM_DI; i++)
  203.   {
  204.     // Set the pin direction to input.
  205.     pinMode(digitalInputMapping[i], INPUT);
  206.  
  207.     // Don't enable pullup resistor on LED_PIN, as the LED and resistor will always pull it low, meaning the input won't work.
  208.     // Instead an external pulldown resistor must be used on LED_PIN.
  209.     // NOTE: This will cause all of the high/low logic for LED_PIN to be inverted.
  210.     if (digitalInputMapping[i] != LED_PIN)
  211.     {
  212.       // Enable the pull-up resistor. This call must come after the above pinMode call.
  213.       digitalWrite(digitalInputMapping[i], HIGH);
  214.     }
  215.    
  216.     // Initialise the digital state with a read to the input pin.
  217.     digitalInputs[i] = digitalRead(digitalInputMapping[i]);
  218.   }
  219.  
  220.   // Initialise each analogue input channel.
  221.   for (i = 0; i < NUM_AI; i++)
  222.   {
  223.     // Set the pin direction to input.
  224.     pinMode(analogueInputMapping[i], INPUT);
  225.    
  226.     // Initialise the analogue value with a read to the input pin.
  227.     analogueInputs[i] = analogRead(analogueInputMapping[i]);
  228.    
  229.     // Assume no analogue inputs are active
  230.     analogueInputChanging[i] = false;
  231.     analogueInputTimer[i] = 0;
  232.   }
  233.  
  234.   #ifdef DEBUG
  235.     serialSendTime = millis();
  236.   #endif
  237. }
  238.  
  239.  
  240. void loop()
  241. {
  242.   #ifdef DEBUG
  243.     loopTime = micros();
  244.   #endif
  245.  
  246.   for (i = 0; i < NUM_DI; i++)
  247.   {
  248.    
  249.     digitalOffset = i;
  250.    
  251.     // Read the current state of the digital input and store it temporarily.
  252.     tempDigitalInput = digitalRead(digitalInputMapping[i]);
  253.    
  254.     // Check if the last state is different to the current state.
  255.     if (digitalInputs[i] != tempDigitalInput)
  256.     {
  257.       #ifdef DEBOUNCE
  258.       // Wait for a short period of time, and then take a second reading from the input pin.
  259.       delay(DEBOUNCE_LENGTH);
  260.       // If the second reading is the same as the initial reading, assume it must be true.
  261.       if (tempDigitalInput == digitalRead(digitalInputMapping[i]))
  262.       {
  263.       #endif
  264.         // Record the new digital input state.
  265.         digitalInputs[i] = tempDigitalInput;
  266.        
  267.         // Moved from HIGH to LOW (button pressed)
  268.         if (digitalInputs[i] == 0)
  269.         {
  270.           // All the digital inputs use pullup resistors, except LED_PIN so the logic is inverted
  271.           if (digitalInputMapping[i] != LED_PIN)
  272.           {
  273.             noteOn(MIDI_CHANNEL, NOTE + digitalOffset, 0x7F); // Channel 1, middle C, maximum velocity
  274.           }
  275.           else
  276.           {
  277.             noteOff(MIDI_CHANNEL, NOTE + digitalOffset); // Channel 1, middle C
  278.           }
  279.         }
  280.         // Moved from LOW to HIGH (button released)
  281.         else
  282.         {
  283.           // All the digital inputs use pullup resistors, except LED_PIN so the logic is inverted
  284.           if (digitalInputMapping[i] != LED_PIN)
  285.           {
  286.             noteOff(MIDI_CHANNEL, NOTE + digitalOffset); // Channel 1, middle C
  287.           }
  288.           else
  289.           {
  290.             noteOn(MIDI_CHANNEL, NOTE + digitalOffset, 0x7F); // Channel 1, middle C, maximum velocity
  291.           }
  292.         }
  293.       #ifdef DEBOUNCE
  294.       }
  295.       #endif
  296.     }
  297.   }
  298.  
  299.   /*
  300.    * Analogue input logic:
  301.    * The Arduino uses a 10-bit (0-1023) analogue to digital converter (ADC) on each of its analogue inputs.
  302.    * The ADC isn't very high resolution, so if a pot is in a position such that the output voltage is 'between'
  303.    * what it can detect (say 2.505V or about 512.5 on a scale of 0-1023) then the value read will constantly
  304.    * fluctuate between two integers (in this case 512 and 513).
  305.    *
  306.    * If we're simply looking for a change in the analogue input value like in the digital case above, then
  307.    * there will be cases where the value is always changing, even though the physical input isn't being moved.
  308.    * This will in turn send out a constant stream of MIDI messages to the connected software which may be problematic.
  309.    *
  310.    * To combat this, we require that the analogue input value must change by a certain threshold amount before
  311.    * we register that it is actually changing. This is good in avoiding a constantly fluctuating value, but has
  312.    * the negative effect of a reduced input resolution. For example if the threshold amount was 2 and we slowly moved
  313.    * a slider through it's full range, we would only detect every second value as a change, in effect reducing the
  314.    * already small 7-bit MIDI value to a 6-bit MIDI value.
  315.    *
  316.    * To get around this problem but still use the threshold logic, a timer is used. Initially the analogue input
  317.    * must exceed the threshold to be detected as an input. Once this occurs, we then read every value coming from the
  318.    * analogue input (not just those exceeding a threshold) giving us full 7-bit resolution. At the same time the
  319.    * timer is started. This timer is used to keep track of whether an input hasn't been moved for a certain time
  320.    * period. If it has been moved, the timer is restarted. If no movement occurs the timer is just left to run. When
  321.    * the timer expires the analogue input is assumed to be no longer moving. Subsequent movements must exceed the
  322.    * threshold amount.
  323.    */
  324.   for (i = 0; i < NUM_AI; i++)
  325.   {
  326.     // Read the analogue input pin, dividing it by 8 so the 10-bit ADC value (0-1023) is converted to a 7-bit MIDI value (0-127).
  327.     tempAnalogueInput = analogRead(analogueInputMapping[i]) / 8;
  328.    
  329.     #ifdef ANALOGUE_FILTER
  330.     // Take the absolute value of the difference between the curent and new values
  331.     analogueDiff = abs(tempAnalogueInput - analogueInputs[i]);
  332.     // Only continue if the threshold was exceeded, or the input was already changing
  333.     if ((analogueDiff > 0 && analogueInputChanging[i] == true) || analogueDiff >= FILTER_AMOUNT)
  334.     {
  335.       // Only restart the timer if we're sure the input isn't 'between' a value
  336.       // ie. It's moved more than FILTER_AMOUNT
  337.       if (analogueInputChanging[i] == false || analogueDiff >= FILTER_AMOUNT)
  338.       {
  339.         // Reset the last time the input was moved
  340.         analogueInputTimer[i] = micros();
  341.        
  342.         // The analogue input is moving
  343.         analogueInputChanging[i] = true;
  344.       }
  345.       else if (micros() - analogueInputTimer[i] > ANALOGUE_INPUT_CHANGE_TIMEOUT)
  346.       {
  347.         analogueInputChanging[i] = false;
  348.       }
  349.      
  350.       // Only send data if we know the analogue input is moving
  351.       if (analogueInputChanging[i] == true)
  352.       {
  353.         // Record the new analogue value
  354.         analogueInputs[i] = tempAnalogueInput;
  355.      
  356.         // Send the analogue value out on the general MIDI CC (see definitions at beginning of this file)
  357.         controlChange(MIDI_CHANNEL, MIDI_CC + i, analogueInputs[i]);
  358.       }
  359.     }
  360.     #else
  361.     if (analogueInputs[i] != tempAnalogueInput)
  362.     {
  363.       // Record the new analogue value
  364.       analogueInputs[i] = tempAnalogueInput;
  365.      
  366.       // Send the analogue value out on the general MIDI CC (see definitions at beginning of this file)
  367.       controlChange(MIDI_CHANNEL, MIDI_CC + i, analogueInputs[i]);
  368.     }
  369.     #endif
  370.   }
  371.  
  372.   #ifdef DEBUG
  373.   loopTime = micros() - loopTime;
  374.  
  375.   // Print the loop execution time once per second
  376.   if (millis() - serialSendTime > 1000)
  377.   {
  378.     Serial.print("Loop execution time (us): ");
  379.     Serial.println(loopTime);
  380.    
  381.     serialSendTime = millis();
  382.   }
  383.   #endif
  384. }
  385.  
  386. // Send a MIDI note on message
  387. void noteOn(byte channel, byte pitch, byte velocity)
  388. {
  389.   // 0x90 is the first of 16 note on channels. Subtract one to go from MIDI's 1-16 channels to 0-15
  390.   channel += 0x90 - 1;
  391.  
  392.   // Ensure we're between channels 1 and 16 for a note on message
  393.   if (channel >= 0x90 && channel <= 0x9F)
  394.   {
  395.     #ifdef DEBUG
  396.       Serial.print("Button pressed: ");
  397.       Serial.println(pitch);
  398.     #elif defined(TEENSY_PLUS_PLUS) || defined(TEENSY_2) || defined(TEENSY_PLUS_PLUS_2)
  399.       usbMIDI.sendNoteOn(pitch, velocity, channel);
  400.     #else
  401.       Serial.write(channel);
  402.       Serial.write(pitch);
  403.       Serial.write(velocity);
  404.     #endif
  405.   }
  406. }
  407.  
  408. // Send a MIDI note off message
  409. void noteOff(byte channel, byte pitch)
  410. {
  411.   // 0x80 is the first of 16 note off channels. Subtract one to go from MIDI's 1-16 channels to 0-15
  412.   channel += 0x80 - 1;
  413.  
  414.   // Ensure we're between channels 1 and 16 for a note off message
  415.   if (channel >= 0x80 && channel <= 0x8F)
  416.   {
  417.     #ifdef DEBUG
  418.       Serial.print("Button released: ");
  419.       Serial.println(pitch);
  420.     #elif defined(TEENSY_PLUS_PLUS) || defined(TEENSY_2) || defined(TEENSY_PLUS_PLUS_2)
  421.       usbMIDI.sendNoteOff(pitch, 0x00, channel);
  422.     #else
  423.       Serial.write(channel);
  424.       Serial.write(pitch);
  425.       Serial.write((byte)0x00);
  426.     #endif
  427.   }
  428. }
  429.  
  430. // Send a MIDI control change message
  431. void controlChange(byte channel, byte control, byte value)
  432. {
  433.   // 0xB0 is the first of 16 control change channels. Subtract one to go from MIDI's 1-16 channels to 0-15
  434.   channel += 0xB0 - 1;
  435.  
  436.   // Ensure we're between channels 1 and 16 for a CC message
  437.   if (channel >= 0xB0 && channel <= 0xBF)
  438.   {
  439.     #ifdef DEBUG
  440.       Serial.print(control - MIDI_CC);
  441.       Serial.print(": ");
  442.       Serial.println(value);
  443.     #elif defined(TEENSY_PLUS_PLUS) || defined(TEENSY_2) || defined(TEENSY_PLUS_PLUS_2)
  444.       usbMIDI.sendControlChange(control, value, channel);
  445.     #else
  446.       Serial.write(channel);
  447.       Serial.write(control);
  448.       Serial.write(value);
  449.     #endif
  450.   }
  451. }
RAW Paste Data