Introduction: Teclado MIDI Super Simple - Super Simple MIDI Keyboard

Este tutorial te lleva paso a paso por la construcción de un teclado MIDI de una octava, programable via arduino gracias a su conector de 6 pines. Vas a necesitar:
Componentes:
  • 1 Atmega328p con el bootloader de Arduino
  • 1 Zócalo de 28 patas
  • 1 Cristal 16Mhz
  • 2 Capacitores 22 pF
  • 2 Capacitores 10 uF
  • 1 Capacitor 0.1 uF
  • 1 Regulador 7805
  • 1 conector de alimentación hembra para placa
  • 1 Conector DIN 5 (MIDI) hembra para placa
  • 6 pines macho 90°
  • 1 switch inversor simple (SPDT) para placa (o 3 pines macho verticales y un jumper)
  • 16 pulsadores para placa
  • 1 resistencia 10k
  • 1 resistencia 220 ohm
Circuito:
  • Placa de cobre virgen (una capa) de 20 x 10 cm
  • Cloruro férrico (250 cm3)
  • Recipientes plásticos
  • Pintura en aerosol
Botones:
  • 3 sobres de SUGRU blancos
  • 3 sobres de SUGRU negros
------------------------------------------------------------------------------------------

This tutoria shows how to build a 1 Octave Standalone Arduino programmable MIDI keyboard. You'll need:
  • 1 Atmega328p with Arduino bootloader 
  • 1 28 leg socket
  • 1 Crystal 16Mhz
  • 2 Capacitors 22 pF
  • 2 Capacitors 10 uF
  • 1 Capacitor 0.1 uF
  • 1 Regulator 7805
  • 1 Female Power plug for PCB
  • 1 Female DIN 5 (MIDI) Connector for PCB
  • 6 90° male pin headers
  • 1 SPDT switch por PCB or 3 vertical Male pin headers and a jumper
  • 16 pushbuttons
  • 1  10k resistor
  • 1  220 ohm resistor
Circuit:
  • 1 One layer copper board (20 x 10 cm)
  • Ferric chloride (a small bottle)
  • Plastic containers
  • Spray Paint
Buttons:
  • 3 White SUGRU packages
  • 3 Black SUGRU packages


Step 1: PCB 1

Si bien no es el objetivo de este tutorial, enseñar a hacer circuito impreso, vamos a pasar por cada paso. Si alguien necesita más información, hay varios tutoriales dedicados a construcción de PCB acá en Instructables.
1)Descargá el archivo de fritzing:
,2) Exportá el circuito en formato PDF e imprimilo en una impresora láser, usando papel ilustración (no modifiques su tamaño!)
1) Cortá (de una placa virgen de cobre de una capa) un pedazo de 20 x 7 cm.
2) Eliminá huellas dactilares, manchas y demás impurezas usando un pedazo de lana de acero
3) Recortá la impresión y colocala boca abajo sobre la placa
4) Calentá la plancha y colocala sobre el papel y presioná sin mover por unos segundos para que la impresión se adhiera a la placa.
5) Presioná con los bordes de la plancha haciendo movimientos circulares. Continúa hasta que veas el circuito a través del papel.
6) Sumergí la placa en agua y dejala por 30 minutos para que la pulpa del papel se ablande.
7) Sacá la placa del agua y comenzá a retirar con cuidado el papel de la placa
8) Todo resto pequeño de papel puede ser retirado con la ayuda de un escarbadiente o similar. La tinta quedará adherida a la placa. Es muy importante que retirés el papel de los agujeros por los que pasan los componentes ya que eso ayuda a la mecha (broca) a alinearse y perforar correctamente.
9) Es probable que en el proceso hayas levantado alguna que otra traza. Si no son muchas, podés volver a dibujarlas con un marcador indeleble.  Si son demasiadas, no te preocupés. Es normal las primeras veces, simplemente retirá todo con la ayuda de la lana de acero y volvé a comenzar desde el paso 2.
--------------------------------------------------------------------------------
Altough the purpose of this tutorial is not to show how to make PCB, we'll show it step by step. If you need more info, you can search through Instructables to see dedicated tutorials for PCB making.
1) Download and open Fritzing file.
2) Export circuit as PDF and print it in Laser Printer using glossy paper (don't modify its size!)
1) Cut a 20 x 7 cm (7,87 x 2,75 inches)  piece of one layered copper board
2) Remove fingerprints, dust, spots, etc. using iron wool.
3) Cut the print and put it over the board (ink towards copper).
4) Heat the Iron, put it over the paper and press gently without moving for a few seconds. This will stick the paper to the board.
5) Start moving the iron (using its borders) in circles, pressing all the time. After a few minutes, all the circuit will be revealed smoothly through the paper.
6) Put the board in water and wait for about 30 minutes for the paper to soften
7) Take the board out of the water and start removing all the paper. Ink will remain stick to the copper
8) Every small remainder of paper must be removed, using a toothpick or similar. Even the small holes in the traces.
9) It's probable that you also remove some ink traces. If they are not too many, you can draw them again using a permanent ink marker. If they are too many, don't worry! (it happens a lot a the first time) Remove every trace of ink and paper using iron wool, dry the board and start again from step 2.

Step 2: PCB 2

Una vez que tu placa está lista, es hora de "comer" el cobre que no queremos. Para ello usamos Cloruro Férrico. Es importante que tomés precauciones:
  • No trabajes en presencia de niños (y mantené la botella cerrada lejos de su alcance).
  • Elegí un lugar ventilado.
  • Usá guantes (o algún elemento protector como una bolsa)
  • No tires excedentes de cloruro férrico en cañerías. Volvé a embotellarlo ya que podés usarlo muchas veces!
  • Usá ropa vieja. Donde el cloruro cae, mancha para siempre.
  • No uses recipientes que luego destinarás a almacenar comida.
  • No tengás miedo al manipularlo, simplemente sé precavido.
Ahora estamos listos:
  1. Calentá la botella de cloruro férrico a baño maría durante unos 10 minutos en agua hirviendo
  2. Apoyá la placa sobre el fondo de un recipiente y derramá el contenido de la botella hasta cubrirla por completo
  3. Cada 5 minutos, podés tomar la placa (usá guantes o una bolsa!) y ver como va. Cada tanto podés sacudir levemente el recipiente para mejorar el contacto entre el cloruro y la placa
  4. En un día templado tu placa debería estar lista en unos 15 minutos. Te darás cuenta porque al sacarla ya no habrá ningún rastro de cobre en las superficies expuestas.
  5. Limpiá los excedentes de cloruro usando papel de cocina. Cuando esté completamente seca, podés limpiarla con agua y secarla.
  6. Tu placa está lista para ser perforada. Antes de esto, vamos a pintar con alguna pintura en aerosol la cara que no tiene el circuito, sólo para que se vea mejor ;)
---------------------------------------------------------------------------------------------
  • Once the board is ready, it's time to etch. Since we're using ferric chloride, it's important to take some precautions
  • Don't etch boards in presence of kids (and store the bottles away from them!!!)
  • Chose a ventilated or open space
  •  Use gloves (or even a plastic bag) to protect your hands
  • Don't pour remaining acid on the drain! Store it again in its plastic bottle. You can use it many times!
  • Use old clothes. FeCl3 stains will remain forever
  • Don't use container where you usually store food. Remember also that they must be made plastic or glass (not steel!)
  • Don't be afraid, just be cautious
Now we're ready:
  • Heat the FeCl3 Bottle in a double boiler for about 10 minutes.
  • Lay the board in the bottom of the container and cover it with the hot FeCl3
  • Every 5 minutes, grab the board (using gloves or a plastic bag) and see how it's going. From time to time, shake smoothly the container.
  • In a warm day, the board should be ready in about 15 (it depends also on the times you've used the same FeCl3). You'll realise when it's ready because you'll see no copper at all (just the ink).
  • Clean the remaning FeCl3 with paper. Then you can clean the board with water. Dry it with a cloth
  • Your board is ready. Now we will paint it (using any spray paint) to make it look better.

Step 3: Perforar Y Soldar - Drill and Solder

Con la placa lista, es momento de perforar. Con una mecha de 0,8 a 1 mm, podrás hacer todos los agujeros de los componentes, excepto el conector de alimentación y las pestañas de agarre de los potenciómetros verticales y el conector MIDI.
Colocá un cartón fino debajo de la placa para no rayar la pintura y realizá todas las perforaciones. 
Al momento de soldar, podés usar la imagen de serigrafía de Fritzing (incluida abajo) para orientarte. Ahí están incluidos los valores de los componentes (en la introducción está la lista completa). Atención a la dirección en la que se coloca el zócalo y luego el Atmega 328, el regulador de voltaje y también a la polaridad en capacitores electrolíticos (10uF) y el diodo de protección (justo al lado del conector de alimentación). No olvides también soldar los dos jumpers o puentes (en azul en la imagen de Fritzing).
En la foto no verás los potenciómetros verticales (no se consiguen en Argentina) pero están ruteados en la PCB a las entradas A4 y A5.

-----------------------------------------------------------------------------------------------------
Once the board is ready, it's time to drill. You can use a 1⁄32 to 3⁄64 bits (sorry if conversion is not OK) for every component hole except from power plug and MIDI and Potentiometer "hooks". Place a thin cardboard under the board to avoid scratching the painting.
Use the image below to guide you through soldering components. There you can see values and orientation (complete BOM in Intro page). Pay atention to orientation in socket (and, of course, microcontroller), voltage regulator, and also polarity in electrolytic capacitors (10 uF) and diode. Don't forget to solder jumpers (a clipped resistor leg will do). They are marked blue in the image. You won't see the vertical 10 pots in the picture (we don't get those in Argentina) but they are properly routed to A4 and A5 (with 5V and GND on each extreme leg).

Step 4: Botones - Buttons

Para darle un aspecto más parecido a un piano y mejor "feel" al tocar, vamos a fabricarle botones flexibles usando Sugru. Vamos a usar 3 sobres blancos y tres negros. Modelá 7 bolitas de un tamaño similar y cubrí los botones. Yo les di forma cuadrada pero eso queda a criterio de cada uno. Simplemente no presiones mucho la pasta sobre la placa porque luego vamos a despegarlos para el último paso. Repetí el orden con los sostenidos (5 botones). Luego podés ayudarte de alguna herramienta plana para darles bordes más definidos.  Mezclá los restos de blanco y negro que te hayan quedado para hacer dos valores de gris distinos para los cuatro botones de la izquierda (destinados a la función Octave Up and Down y pitchbend). Dejá secar por 24 horas.
Una vez que el Sugru haya "fraguado", retirá los botones con cuidado (de a uno por vez). Vas a ver que formaron un molde perfecto del botón. Con la ayuda de una herramienta punzante (en mi caso una lima de uñas) retirá la silicona, formadas por la base metálica del botón para formar así una superficie cuadrada plana. Esto le dará mayor flexibilidad y superficie de contacto al botón. Repetí el paso con cada uno y listo! Tu teclado MIDI está terminado. Sólo falta subirle el código y conectarlo a algún módulo de sonido.
----------------------------------------------------------------
To give our keyboard a piano look and a better feel when played, we'll make flexible buttons with Sugru. We'll use three white packages and three black ones. Shape 7 small white balls of similar size adn cover the pushbuttons. I made them square but you can choose any shape you want. Don't press them too much because we will take them out later for the last step. . Repeat the same procedure with the five black buttons. Then you can use a plain tool (like a cutter) to make their edges more defined. Mix the remaining Sugru into two different shades of grey for the 4 buttons on the left (destined to Octave Up and Down and pitchbend). Let sugru cure for 24 hours.
Once Sugru is cured, take buttons away (one at a time). You'll see the perfect mold of the pushbutton. With the help of a pointed tool, take away the corners to leave to bottom plain. This will give the button more flexibility and contact surface. Once you're done, put it again on its place and repeat with each button. You MIDI keyboard is now ready. We only have one step left.

Step 5: Subir Código Y Conectar - Upload Code and Connect

El teclado MIDI se programa usando la IDE de Arduino. Tenés dos maneras de subir el código. Una es usar un conector USB/Serial como el de Adafruit, Arduino o Sparkfun. Conectalo directamente al conector de 6 pines a la derecha y subí el código (recordá elegir correctamente la placa correspondiente al bootloader de tu chip atmega328p).  También podés cargar el código usando la placa arduino y luego retirarlo para colocarlo en el sócalo del teclado.
El código no incluye aún las funciones octave up, down y pitch bend (espero incorporarlas en el futuro pŕóximo). Pero permite tocar las notas de la octava media para probar que todo funcione correctamente. Tampoco hay funciones asignadas por código a los dos potes (otra promesa a futuro). El sketch hace uso de la librería MIDI y está basado en un ejemplo extraído de la página de Adafruit

// PRINCIPIO DEL CÓDIGO
/*
This sketch is based on example code from ADAFRUIT
http://www.adafruit.com/blog/2009/10/20/example-code-for-multi-button-checker-with-debouncing/
and uses MIDI library:
http://sourceforge.net/projects/arduinomidilib/


*/
#include <MIDI.h>
#define DEBOUNCE 10  // button debouncer, how many ms to debounce, 5+ ms is usually plenty

// here is where we define the buttons that we'll use. button "1" is the first, button "6" is the 6th, etc
byte buttons[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; // the analog 0-5 pins are also known as 14-19
// This handy macro lets us determine how big the array up above is, by checking the size
#define NUMBUTTONS sizeof(buttons)
// we will track if a button is just pressed, just released, or 'currently pressed'
byte pressed[NUMBUTTONS], justpressed[NUMBUTTONS], justreleased[NUMBUTTONS];

void setup() {
   MIDI.begin(1);             // Launch MIDI with default options

  byte i;

  // pin13 LED
  pinMode(13, OUTPUT);

  // Make input & enable pull-up resistors on switch pins
  for (i=0; i< NUMBUTTONS; i++) {
    pinMode(buttons[i], INPUT);
    digitalWrite(buttons[i], HIGH);
  }
}

void check_switches()
{
  static byte previousstate[NUMBUTTONS];
  static byte currentstate[NUMBUTTONS];
  static long lasttime;
  byte index;

  if (millis() < lasttime) {
     // we wrapped around, lets just try again
     lasttime = millis();
  }

  if ((lasttime + DEBOUNCE) > millis()) {
    // not enough time has passed to debounce
    return;
  }
  // ok we have waited DEBOUNCE milliseconds, lets reset the timer
  lasttime = millis();

  for (index = 0; index < NUMBUTTONS; index++) {
    justpressed[index] = 0;       // when we start, we clear out the "just" indicators
    justreleased[index] = 0;

    currentstate[index] = digitalRead(buttons[index]);   // read the button



    if (currentstate[index] == previousstate[index]) {
      if ((pressed[index] == LOW) && (currentstate[index] == LOW)) {
          // just pressed
          justpressed[index] = 1;
      }
      else if ((pressed[index] == HIGH) && (currentstate[index] == HIGH)) {
          // just released
          justreleased[index] = 1;
      }
      pressed[index] = !currentstate[index];  // remember, digital HIGH means NOT pressed
    }
    //Serial.println(pressed[index], DEC);
    previousstate[index] = currentstate[index];   // keep a running tally of the buttons
  }
}


void loop() {
  check_switches();      // when we check the switches we'll get the current state

  for (byte i = 0; i < NUMBUTTONS; i++) {
    if (justpressed[i]) {
       MIDI.sendNoteOn(44+i,127,1);
    }
    if (justreleased[i]) {
      MIDI.sendNoteOff(44+i,127,1);
    }

  }
}

// FINAL DEL CÓDIGO


La placa puede alimentarse directamente del puerto USB o por el conector de alimentación (7 a 15 Volt / positivo al medio). El interruptor (o jumper) ubicado a la derecha (cerca del conector de 6 pines) debe estar en la posición que corresponda a cada caso. Recordá desconectar cualquier dispositivo MIDI de la placa para cargar el código ya que utiliza los mismos puertos de comunicación en ambos casos. Eso es todo! Solo resta conectar un cable MIDI entre el teclado y un dispositivo con MIDI IN. espero que lo disfrutes. Si hacés algo con él, mostrame! Rercordá que podés hackear cualquier dispositivo con botones para transformarlo en un dispositivo MIDI con esta placa.  Gracias po tu atención!
Jorge (Laboratorio de Juguete)


---------------------------------------------------------------------

You can program this keyboard using Arduino IDE. There are at two ways of uploading the code. One is using a typical USB to Serial adapter like the ones from  Adafruit, Arduino or Sparkfun (other adapters may not have the same pinout but you can redirect them, just look the tags on the six pin connector on the image below) . If you have one of those, just connect it to the board. Remember to choose the same board of the bootloader your atmega has inside.   If you don't have any of these adapters You can also program the chip on your arduino board, then pull it out an put it in the keyboard socket.
The code is very basic yet and does not have octave Up/ Down functions or pitchbend (hope to add them in the near future). Neither do thei have code asigned to the two potentiometers (A4 and A5) . The sketch uses the MIDI Library and is based on an example from Adafruit's page.
The board can be powerd via USB Adapter or its power plug (7 to 15 volt - positive to the center). Switch (or jumper) on the upper right side of the board must be turned to one of these choices.  Remember to unplug any midi device connected to the board when you try to ulpload code since it uses the same port for both communications. That's all. Remember that you can use this board to hack any device with buttons and turn it into a MIDI controller. Meanwhile, just connect the board using a midi cable to a sound module or keyboard with MIDI IN jack and enjoy! Thanks for your attention!
Jorge (Laboratorio de juguete)