Superficie de control MIDI con Arduino Leonardo presentación (DIY).

Hace quizá un par de años decidí construir mi propio controlador midi para personalizarlo completamente, puesto a investigar encontré las placas de desarrollo Teensy basadas en el micro controlador de Atmel mega32u4, este chip tiene la particularidad de soportar MIDI directamente por USB por lo cual era la opción obvia sin tener que hacer una conversión por hardware para conectarla a un PC, por cuestiones geográficas supongo me fue difícil encontrar dicha placa y el envío me resultaba mas caro que la misma placa ademas del tiempo de espera, investigando mas encontré la placa Arduino Leonardo basada en el mismo micro chip y en teoría con las mismas prestaciones según algunos blogs.

La placa la encontre en la ciudad de México de manera relativamente fácil y me puse a aprender programación para poder llevar acabo mi proyecto. Una vez empece a trabajar con ella me di cuenta que en las librerías de dicha placa no existía el soporte MIDI-USB por lo cual tenia que hacer la conexión por hardware y eso no era lo que quería así que deje el proyecto de lado buscando eventualmente si la situación había cambiado.

Después de haber dejado el proyecto unos meses realize una nueva búsqueda y encontré el trabajo de Rkistner quien había modificado el core de las librerías de hardware de la Leonardo para que pudiera ofrecer el soporte que yo necesitaba para realizar mi proyecto, técnicamente el trabajo de Rkistner esta en desarrollo y no ofrece APIs de alto nivel por el momento, sin embargo es fácil entender el protocolo de los mensajes midi para crear el código necesario de entrada y salida, de nuevo me puse a trabajar en ello.

En internet existe bastante documentación de controladores MIDI basados en Arduino por lo cual es relativamente fácil programar la placa para recibir leer potenciometros y botones y enviar los mensajes correspondientes, lo que no encontré y era parte de mi proyecto eran buenas referencias para el uso de un encoder, (si, mi perversión es hacer scratch como los dj famosos) de igual manera me puse a investigar y probar códigos que encontré en internet para leer el encoder. Quizá sea mi completa inexperiencia en programación pero ninguno de los códigos que encontré funciono y no quise tomarme la molestia de entender lo que los autores habían intentado o su método de lectura del rotativo.

Si usamos algo de logica es sencillo entender como funciona uno de estos encoders para detectar el movimiento hacia adelante o hacia atrás, entonces cree un código muy sencillo que detectara dos cosas, una si el encoder se había movido desde su ultima lectura y dos, en que sentido se había movido para enviar el mensaje correspondiente.

Aqui el enlace: Encoder código basico.

Entre una cosa y otra también me puse a diseñar la forma física que tendría mi controlador y llegué mas o menos a esto:

Intente optimizar el diseño para aprovechar al máximo las conexiones que la Leonardo posee, en esta etapa me di cuenta que sería util cuando menos desde el punto de vista estético que mi interface tuviera medidores de nivel de señal aprovechando la posibilidad de configuración de Traktor para proveer salidas de nivel de señal y usando las salidas PWM de Arduino junto con el chip LM3914 de Texas Instruments poder encender una linea de leds.

De nueva cuenta modifique el código para que leyera los mensajes Control Change que salen de Traktor y los utilizara para encender el/los leds.

Usando un solo led con la salida PWM (analogWrite) un solo led parece estar encendido siempre o varía muy poco su brillo, por el momento no he comprado el LM3914, entonces he optado por usar el led de manera digital usando un nivel de referencia para que encienda solo cuando el nivel de la señal exceda cierto parámetro y solo represente los pulsos mas altos, como se puede ver en el siguiente video todo va funcionando como se espera.

Aqui el código basico para enviar y recibir MIDI, un encoder con una salida de nivel de señal para led en dos versiones, led análogo y led digital, es necesario renombrar los archivos eliminando el signo «+»: Encoder code.

 

Espero esta información sea util para alguien mas e ire informando de los progresos.

88 comentarios en “Superficie de control MIDI con Arduino Leonardo presentación (DIY).”

  1. Hi, my friend … I bought the Arduino Leonardo card … I need your help … the following error appears; ‘MIDIEvent’ was not declared in this scope. I’m using IDE 1.8.5. Please help me.

    1. Hi, that’s because you are not using arcore but now we have a midiusb library integrated in IDE, you need to update the code to use the new library, please wait, tomorrow i will change the code to use the new library.

  2. Amigo, muitíssimo obrigado pela ajuda. Esse erro foi resolvido. Eu consegui instalar o Arcore master, agora já consegui gravar o código no arduino, porém não consigo estabilizar o rotary encoder. Por favor você poderia me ajudar dando dicas sobre como fazer as conexões entre o arduino e o rotary encoder?

    Quando eu clico em LEARN no TRAKTOR para configurar o encoder em Device Maping o Canal e a mensagem MIDI ficam oscilando muito. Não consigo girar o rotary encoder.

    Estou conectando um rotary encoder assim: Pino A na porta 0 – RX e Pino B na porta 1 – TX, e o pino central na GND…está correto dessa forma??

    Você poderia por favor me mostrar como fazer a conexão correta entre rotary encoder e o arduino leonardo?? Preciso utilizar resistores ou capacitores?? E também como faço para configurar as PREFERENCES no traktor? Agradeço muito por sua ajuda.

    Acompanho seu site a mais de um ano, já te enviei e-mail´s e você tem ajudado muito no meu projeto.

    Segue link de um vídeo sobre o problema:

    Estou usando o código Midi_controller_Final_, que você postou em seu site.
    Windows 8 – 32bits
    IDE do arduino Versão 1.5.4
    O Rotary Encoder é da marca ALPS: http://uk.rs-online.com/web/p/mechanical-rotary-encoders/2651723/
    Placa: Arduino Leonardo (arcore)

    Muitíssimo obrigado.

    1. Lo que pasa es que no tienes nada mas conectado y esta entrando ruido por todos los puertos, por eso esta mandando mensajes midi constantemente, es por eso que traktor se confunde, una de dos, o conectas todo lo que falta o desactivas del codigo todo lo que no se trate del encoder, Si esta bien conectado el encoder.

    1. Hi, You don’t need resistors for the encoder, you need capacitors conected between each digital in and ground, one .1uf cap for each arduino in conected to the encoder, the center pin of encoder conected directly to GND.

      You need 220 homs resistors conected in serie with the leds, arduino in->220 resistor->led positive input -> led negative to GND.

      I hope this could help.

      1. Friend, what kind of capacitor do you use? I can not stabilize the signal … what am I doing wrong? Thanks a lot for the help.

  3. Ceramic capacitor, but i think that’s not your problem, do you have everything conected? Potentiometers? Buttons?, because if you don’t, you are getting noise from that other inputs. Another big problem is that you may get a lot of noise if you don’t have everything isolated, as an example, if your potentiometers body are mettalic and they aren’t connected to GND just by touching them you are introducing noise, same thing with the rotary encoder, because your skin is acting like a big capacitor, same principle of touch screens, i need to see photos of your project please. BTW, sorry, i completly forget to mention that noise problem, normally you need to build everything and put it in a metallic box, then conect arduino GND to the box, a wooden box can work if you put some aluminium or copper foil inside conected also to GND.

    Please send me pictures of your proyect to see how you have everything connected.

    1. Hello friend, once again here to ask you for help. I’m only using Protoboard with Arduino and Encoder, I’m not using other controls … Once I can solve this problem I’m going to continue with the project. See the photos … Please inform me what is wrong …. Is there a connection missing?

      https://ibb.co/c3MA0w

  4. Friend … it worked …. thank you very much …. thank you … !!! But there is one more problem … when I turn the encoder to one side it works very well without noise, but when I turn to the other side … it has noise .. What can it be ??

  5. Good day. At sketch level the code does not care the way the encoder is turning, it only detects logic changes, so, i think it may be because you are working with a protoboard and you have some false contact when you move the encoder or you touch the wires.

    1. I thought of that too. I changed the position of the sketch on the Protoboard and even then continued …. After I create the Prototype put here on your site the result. I really wanted you to send me an example code for buttons and potentiometer, using Arcore. I believe it is not very difficult, but as I do not understand much about an Arduino programming language with an easier example to complete my project and learn. I want to thank you for your attention and promise to keep asking. LOL …

  6. i’m planning to do a video explaining how the original code work, but the problem is my poor internet connection, i can’t upload long videos. the original code has an array of buttons and potentiometers. if i can explain how it works you should be able to understant how to modify.

    Other potential problem is that i speak spanish, i’m mexican, so, i’m not shure i can explain in inglish with enough clarity, however i will try.

    Have a nice day.

  7. Amigo, si usted habla español en el vídeo sería muy bueno porque yo soy brasileño y entiendo el español mejor que el inglés. Sería muy útil. Le agradezco una vez más por la atención que jamás conseguirá sin su ayuda. Necesito mucho de esta información y me gustaría seguir teniendo su ayuda.

  8. Ok, je, curiosamente yo sé y reconozco que el portugués es muy parecido al español pero me cuesta mucho entenderlo, aunque de ser honesto el español de otra region a veces también es dificil, me costo mucho entender los modismos españoles europeos, en fin, voy a tratar de hacer el video lo mas pronto posible, ver como hago para subirlo y publico aquí en el blog la actualización, y si, siempre que se pueda estoy dispuesto a ayudar. Buena tarde.

  9. Good Morning. My project is doing very well. I already have 2 encoders working. The noise disappeared after I removed the capacitors (I did not understand), but it is working.
    I’m studying a way to expand Arduino Digital and Analog ports MUX/Multiplex, but I still do not know very well how the ICs work: CD4051 for digital ports and 74HC595 for analog. Do you have any code that I can take advantage of?

  10. You can use 4051 chips for analog and digital outputs and inputs, i recommend to use the cd 4067 because it provide 16 inputs or outputs and it only use one more control pin, yes i have a code, but i need to search for it, i really don’t know where it can be.

    About the noise, ¿are you shure the capacitors where the right value? my .1 caps are very little. Anyway if the encoder work witout the caps it is fine.

  11. Could you explain to me how I make connections between the cd4051 and the arduino and potentiometer ?? If possible at Fritzing ??? Thank you very much.

  12. My friend … I know you have helped me a lot with my project … I could never do it without your help … I need your help. Please, how do I adapt this code to use only 1 CD4051. I would like to connect 8 potentiometers initially. Unfortunately I understand little of programming and this is my biggest problem. I was only able to get here because you showed me how to do it in detail. I think if I run 01 CD 4051 for 8 potentiometers I might be able to expand for later. As soon as possible please help me.

  13. Friend, after a lot of research I managed to understand and managed to run the cd 4051. Now there are only multiplex for the buttons. I already tried to implement here with 74hc595, but I can not work. The potentiometers are ok. now it’s only mux for the buttons. Do you have any sample code for the buttons using ci 74hc595 ?? Again, thank you very much. as soon as I complete the project I will be posting the complete code here.

  14. No, sorry, i have not used that IC mainly because you can use the 4051 for buttons and digital inputs, i use four 4067 ic to manage 32 pots and 32 buttons.

    The hc 595 is better as led controll.

  15. My friend, take a look at the code snippet below … I’m trying to use the 4051 for the buttons the same way I do with Potentiometers, but I do not think it’s right. I can not figure out how to modify the code.

    Do you have any sample code for buttons with 4051 ??

    Please help me…

    // ######### DIGITAL ####################

    for (count1=0; count1 Ldi1[count1] + thresh || di1[count1] Ldi2[count1] + thresh || di2[count1] < Ldi2[count1] – thresh) {

    CC(Chan1-1, count1+offsetB, di2[count1]/8);

    Ldi2[count1] = di2[count1];
    }

    }

  16. // #################################### DIGITAL

    for (count1=0; count1 Ldi1[count1] + thresh || di1[count1] Ldi2[count1] + thresh || di2[count1] < Ldi2[count1] – thresh) {

    CC(Chan1-1, count1+offsetB, di2[count1]/8);

    Ldi2[count1] = di2[count1];
    }

  17. My friend, sorry my ignorance is that I’m not very good at programming. After several attempts I was able to run the buttons on 4051. It only has a problem when I press the button it triggers more than once. There is somewhere that to solve this problem you need to activate a Delay / Millis to avoid repeated drives. Do you have any way to solve this problem? Another question is how can I activate a led when I press a button to show that the function is activated on the traktor ??? I know how to do a led up but I do not know how to put it inside the code.

  18. You can use capacitors connected in parallel to avoid that behaviour it’s called electric bounce, you can use a simple delay but i never nieed a delay when usin capacitors. I’m sorry, i don’t use leds the way you try to do because the feedback came from the pc screen.

  19. is there a measure for the capacitor (1uf) is enough? Does anything need to be modified in the code to work correctly? I’m testing here but continue with debounce.

  20. Friend when I use the button without the 4051 it works normally, but when with the 4051 appear the noises … I think I need to modify something in the code. The code I am using is the same for the potentiometers in 4051. Do you have any idea how to solve ?? Please help … And thanks again …

  21. .1 uf is the value i use. I’m sorry, i dont see how i can help you because i really need to have the hardware in my hands to review what’s happening. BTW, with buttons you need to send note on and note off messages, not control change messages. Maybe that’s your problem.

  22. Digital Read for buttons should be included in the for cycle of analog inputs (potentiometers) because you are using that cicle to send control messages to the 4051. You need an array for buttons with 8 values (int Din[8];). put the buttons function into the potentiometers ‘for’ cycle and change the «i» variable to «count», i hope i’m not missing something.

  23. You need a separate chip, one for each group of 8 buttons or potentiometers. You can use 4051 four inputs to read analog and 4 to read digital inputs (or any other amixed arrange) but then you will need a more complex code, so keep it easy and use diferent chips.

  24. Friend, I know I asked too much, but please, I would like you to send me a sample code for the buttons with 4051, I tried but could not develop the code. Thank you so much.

      1. Yes. Yesterday I was listening to your songs and I liked it a lot, I’m sure I’ll play some. It’s the least I can do to reciprocate the help you have given me.

    1. Hi friend … I would like to use (06) 4051: 03 for digital and 03 for analog. Okay, I’m already listening to your son’s songs. They are very good. Excellent quality …. I’m downloading all for my case.

  25. Thank you, my friend, for remembering me.

    To multiplex the analog I am using 03 Digital pins 10 (s0), 11 (s1) and 12 (s2) and another Analog pin A0 (out). Can I use the same pins 10 (s0), 11 (s1) and 12 (s2) and another digital pin (out) to multiplex the buttons? Or do I need to use 3 other digital ports?

    If I need to use another 3 digital ports I will be limited, since the rotary encoders already occupy 4 doors.

    Additionally, the following error appears:
    ‘i’ was not declared in this scope, in code:

    if (Di1[count] != LDin1[count]) { // si cambio desde la ultima lectura
    if (Di1[count] == LOW) { // y lee estado bajo (LOW):
    NOn(Chan, i+offsetD, 100); // envia mensaje NoteOn al canal general con el valor i mas el ofset con valor 100
    }
    else {
    NOff(Chan, i+offsetD, 0); // envia mensaje NoteOff al canal general con el valor i mas el ofset con valor 0
    }
    LDin1[count] = Di1[count]; // asigna el valor actual al arreglo de la ultima lectura para comparar en el ciguiente ciclo
    }

  26. Ok tks for the comment, i see the error, i will fix it tomorrow, as i told you i can’t test nor compile because i don’t have arcore installed and it always send me errors. It’s good your comment because i haven’t see those errors, it’s easy but i’m almost sleeping in the chair. Good night!

  27. I’ve been able to multiplex the digital ports, with their code, it’s working perfectly, but I still have trouble multiplexing the buttons. Maybe I have not understood where to connect the wires to operate the buttons.

    1. No, the problem is the way you was trying to use buttons, buttons do not work in the same way. About the in/out, the analog pins can be used to as digital i/o ports, i thing we will connect the leds using A4, A5 & A6 ports, I will send you a fritzing diagram too. BTW i think about the leds, i know how to connect them but i have to write some code for them and i have not time righ now, maybe the weekend. I don’t know if the arduino have enough memory so you hill have to check when i send it to you.

  28. Good news, i find a couple of olds 4051 ic so i will be able to to test the code, the leds and to use the new library. I have a lot of 4051 and 4067 chips but all of them are SMD and i have no way to build a test circuit. i’m a little exited to test and integrate the feedback leds in the circuit so i will make some time tomorrow to build everything. Good night again.

  29. Hola! estuve siguiendo todos los comentarios y el progreso del codigo, muy interesante! estoy intentando recrear con botones y multiplexor cd4067b (de 16) pero al presionar cualquier botón me lanza varias notas midi a la vez, como puedo solucionarlo? muchas gracias!!

  30. Hola, buena noche. Necesito ver tu hardware, diagrama y el código que has usado, ya que yo no tengo un código publicado con el 4067 supongo que lo modificaste, necesitaría ver eso para hacerme una idea de que puede estar pasando.

  31. Hola! subi a mega el diagrama, el .ino y dos capturas de pantalla del midi control con los resultados de los botones presionados, una captura tiene una lista note on y off repetidas resultado de presionar el primer botón del multiplexor (lo mismo sucede si presiono los botones de los pines 8, 9 y 16) la otra captura es presionando los botones en los pines 2 y 3, eso esta bien…el otro problema surge al enlazar un segundo multiplexor (no sensa ningún botón, esta como muerto) revise todas las conexiones pero están bien…si podes ayudarme con esto te agradecería tanto!
    https://mega.nz/#F!u9MjgZJQ!d6FOBZ1truMK1Lir0D1XVQ

    1. Aunque de hecho estoy viendo que te esta mandando las señales note off a otro canal que debería ser el canal del segundo multiplexor, creo que para empezar deberías conectar un solo multiplexor y usar todas sus entradas, las señales de control que estas mandando solo estan activando 7 entradas, el ciclo for para un 4067 deberia contar de 0 a 15, empieza hechando a andar uno solo con todas las entradas y despues resolvemos lo del segundo multiplexor, conforme me dé tiempo ire respondiendo por aqui. Tambien te consejo limpiar el codigo de todo lo que no necesites o no estes usando por ahora, por ahi puede ir dando problemas aunque no debería.

    2. Ah, otra cosa, si dos pines funcionan como deben entonces el problema no esta en el código si no en alguna parte de la construcción en el proto, si hubiera problema en el código nada funcionaría, aunque si creo que debes activar la cuenta completa del 4067 como te dije en el comentario anterior, vamos a poner a funcionar 1 como debe y después integramos el otro.

    1. A ver, las notas repetidas pueden ser por que no tienes capacitores conectados en paralelo con los botones, esto puede producir ruido (bounce) y la arduino lo interpreta como si hubieras presionado cada boton multiples veces, los capacitores de .01uf son necesarios para el debounce.

      Respecto a que el segundo multiplexor no manda nada solo se me ocurre que pueda estar dañado el chip o el pin de tu arduino. por que todo lo veo correcto. ¿Que sucede si intercambias las entradas 6 y 7? Recuerda que también sobre la protoboard podemos tener algún falso contacto y no darnos cuenta.

  32. hola, realice varias pruebas y sigue sin funcionar el segundo multiplexor, lo que hice fue soldar a una placa el integrado con los botones le añadi los capacitares y aun así no funciona, se te ocurre que puede ser? gracias

  33. ¿Todos son botones? ¿Un solo integrado si funciona ya correctamente? Disculpa he estado bastante ocupado, se me ocurre que podrias ralentizar el ciclo poniendo un delay dentro del ciclo for, de ese modo mediante el puerto serie monitorizas que esta ocurriendo a nivel electronica cuando pulsas un boton, o si lees el datasheet del integrado puedes seleccionar cada entrada mediante jumpers y ver si la señal de presionar el botón se reproduce en la salida del integrado pin por pin. tambien habría que ver si la arduino esta proporcionando suficiente corriente a los integrados.

  34. Hi, great friend. After almost a year without messing with my project. here i am again. Thanks to your help I was able to use CD4051 and now I can run 24 potentiometers correctly. But I’m still stuck on the buttons. I have not yet been able to use the buttons with the Cd4051. Could you please send me an example code to make it easier for me to understand? Follow my current code.

    https://mega.nz/#!IfRyxSyK!skBwX2hmW_qsrzNctVULGnKKAQ931bmtjAoFgL4HnFA

Replica a Rideonbeat Cancelar la respuesta