Sunday, 3 August 2014

You can't use a 4n32 optocoupler for MIDI

In my last MIDI project, a MIDI to CV converter, I used the Sparkfun MIDI shield. It was probably overkill because I only wanted MIDI-in but it came with the female sockets and the optocoupler and I didn't have to get my head around how anything worked. Now I wanted to do MIDI-in via a breadboard. Fortunately there are lots of schematics and discussions around.

MIDI is simply serial communication at a 31250 baud rate so the Arduino should be able to read it using a serial Rx pin. The MIDI standard requires the devices to be electrically isolated so an optocoupler is usually used on the receiving end. An often quoted resource is this post to the Arduino forum. The hand-drawn schematic is pretty charming and it makes it all seem easy enough. The comments suggest both that this is a popular topic and that despite it being a relatively simple circuit people have a lot of trouble making it work. I guess there's a lot of idiots out there right? Well turns out I'm one of them, perhaps more than most.

Initially it was simply a matter of getting any signal at all. It took a while to figure out the numbering on the MIDI connectors and whether it's shown relative to the front or back of the connector. As an aside I'm still to understand why a five pin cable is needed when only two lines appear to be used. This summary of how MIDI is wired up was pretty useful, especially since I'll eventually want to do a MIDI-thru as well. Generally a diode is used to protect the optocoupler against reverse connections. I managed to destroy an optocoupler by removing the diode to inspect if it was the right way around while I had the MIDI cable connected up in the reverse sense. Also I had a little bit of brain fade with respect to how ICs are numbered.... suddenly it wasn't turning out so simple after all.

Eventually I got it all straightened out, had a more or less conventional setup hooked up to my MIDI keyboard and appeared to have some signal coming out. However only about one note in 20 actually changed the pitch and then it seemed more or less at random. I'd already written MIDI receiving and processing software for the Arduino that I knew worked so I had a fair degree of confidence that the software part was working.

Turns out the key was the optocoupler. I happened to have a handful of 4n32 optocouplers that I'd bought for some project or another.  There seemed to be lots of projects around using the 4nXX series to read MIDI so it should be OK, right? The 4n32 is a darlington (two transistor) optocoupler but so is the 6N138 and that's widely reported to work. Well actually it's worth checking the datasheet. If MIDI is at 31250 Hz then the period is of the order of 32 microseconds. An optocoupler takes a finite time to switch on (or on to full brightness I suppose) and to switch off. These values are given in the datasheet. For the 4n32 the on time is 5us. The off time has a max of 100us. So that's going to be a bit of a problem with a 31kHz signal. Indeed here's what it looks like on the scope:



The input, those nice square pulses, in green and the output in yellow. The MIDI signal is inverted by the optocoupler as expected since the MIDI definition of true is a high. You can see the slow turn off time of the 4n32 with respect to the signal frequency means the pulses are very quickly hopelessly out of sync and what I was reading with the Arduino was basically noise with a pseudo 31kHz baud rate.  So the lesson - read the datasheets. In retrospect I suppose it also was a little suspicious that a Google search for MIDI and 4n32 only shows up questions asking how to make it work...

Doing some research I saw there are ways to speed up optocouplers by adjusting the pull up resistors and the like and I did some experiments but I was unlikely to get the order of magnitude improvement I needed. Luckily a local supplier had some 4n35 optocouplers. These are a drop in replacement but the datasheet show a typical turn off time of 7us and a max of 10us. That's a lot better and indeed the scope shows that the input and output track pretty well:


So the Arduino could read the serial signal and I had MIDI-in! It's likely in my final design I'll use something even faster, perhaps the 6N137. These are designed for logic operations and have switching times in the ns range which might be overkill but I'll do some experiments to see. Typically a 6N138 is used, that's what was in the Sparkfun MIDI shield I mentioned earlier. The 6N138 has switching times comparable to the 4n35.

Here's a short video of what I have so far connected up to my Arturia Beatstep - a great little sequencer that has both CV/Gate and MIDI out. I get a lot of use out of it on my modular system. I had in mind building something similar and I try and avoid buying new toys but this was so cheap and works so well it was one of the few times I was discouraged from DIY.



Finally in doing some research on MIDI and the Arduino I discovered there's a reasonably mature and very well supported MIDI library available. This is fantastic, is very flexible - even allowing me to read MIDI on Serial1 of the Arduino mega so I could continue to have debugging to the normal serial output. The resulting code is very clean, much more so that the state-heavy code I wrote myself and the library handles a whole range of standard messages. I'm looking forward to exploring it further.


Friday, 1 August 2014

Waveshapers - some sound!

As a start I wanted to test the basics - the ability of Arduino to create a musically correct tone and to shape that into a useful ramp or square wave with external circuitry.  As a starting point I used two resources. The strategy of sinneb to generate an accurate pulse from the Arduino as shown here. Also from the PicSynth the simple 4520 based waveshaper shown in this schematic.

Here's an obligatory photo of the breadboard.


Interesting huh? Anyway it worked - I had sound! A chunky sounding square wave and a surprisingly chunky ramp. However there was an oddity - the PWM control seem to only have a could of steps so it wasn't possible to get that classic PWM sweep I like.  Taking a look at the output on my scope it soon became apparent why. Here's the ramp wave:



It's a ramp Jim, but not as we know it. If I'd stopped to think a bit about how the circuit works then it would have made more sense. The 4520 is a four-bit counter and essentially divides the input into four square waves that are added together to make this stepped ramp. 

Reading the PicSynth site a bit more closely I realized that the author knew this of course and had an alternative. This circuit based on a 4046 and 4024 gives more conventional sounds and much better looking waveforms. There's also an excellent explanation on that page of how the ramp->square conversion works. This explains very well why the stepped ramp wave can't really be used for PWM. I won't repeat it now, go read it yourself.

Here's the circuit on the breadboard:



 I haven't built the LFO yet but I've simply been using a pot as a voltage divider to control the pulse width. Here's the ramp and the square with the square wave near the minimum width:



You can see the ramp wave looks much better - more or less like the real thing. This is a 256 step conversion so it's pretty smooth. There's a bit of noise, but hey - it's on a breadboard!

Here's another image with the pulse width near maximum:



I don't have any proper input device yet but have simply been using a pot connected up to the analog input of the Arduino and using that to sweep across the notes.

Finally I used my guitar tuner, which has a chromatic mode, to verify the notes were as I expect them. Every single one was within about 5 cents and I confirmed a few with the frequency counting mode of my multimeter as well. So this is a promising start. The next thing I will try is hooking up some MIDI input so I have a more conventional way of setting the current note.




Wednesday, 30 July 2014

Background - how I got interested in this sort of thing

Some years ago now I became interested in the hobby of analog music synthesis. My first project was Ray Wilson's "Weird Sound Generator". I did this with a home etched circuit board, didn't really understand much of it but had a lot of fun in the process. It's a great project for beginners. In fact I'm a big fan of Ray's work and highly recommend his MFOS website and his book on Analog Music Synthesizers.

My next step was one of Ray's "Sound Lab Minisynth". Again I hand etched the board based on Ray's PCB artwork. It took a lot of trial and error to get any sound out at all and I learned a lot about how to, and not to, construct synths. Some of the soldering was substandard and the wiring was definitely a mess. The case was a plastic food container with an aluminium faceplate epoxied on.






It was however lots of fun and even though it's never been perfectly in tune and some aspects have never worked, I was thrilled to get some real "synth" sounds out of it.

From this project however I could see that "normalized", self-contained, synths were a little limiting. My next project was to construct a more traditional modular system. This I assembled using modules from various places - some hand etched using Ray's designs, some strip board and a number of PCBs kindly given to me by my friend and colleague Piotr Rotkiewicz  who has an amazing modular system.

My own modular system is a lot more modest:



Still it has all the basics and given the very diverse origin of the modules is likely unique in the world. The large module on the right is a MIDI-CV converter that I constructed using an Arduino and a 10 bit SPI controlled DAC. I do regret that I only thought to build a single oscillator (but three LFOs!) however it's perfectly usable and is musically accurate over four octaves or so. Here's an example of a track produced with it. Apologies to JS Bach.



My current modular project is building one of Ray Wilson's Sound Lab Ultimate and the Ultimate Expander.  These will go in a cabinet that's the same size as my existing modular and should supplement it quite well. This time I actually bought the PCBs and faceplates and it has made the whole thing a lot easier. I have the PCB populated and all the intra-faceplate wiring done and I'm beginning working on the board to faceplate wiring. Trying to keep it as neat as possible.

While I enjoy working on the modular systems and will likely eventually expand to a third cabinet, I had a desire for something a bit more portable. Plus, especially since I don't do a lot of coding now in my day job, I like the idea of a project with a programming component.  I enjoy having two projects on the go at once, it's useful when one gets stuck or just simply when the work is tedious! However I really need to work hard to make sure it's not more than two projects....


A synth that's both mega and mini?

The Basic Idea

Yes, it's pretty much an oxymoron but I was at a loss to think of a better name.  In some later post I will explain my background and how I got interested in this sort of thing. But I want to start simply describing my idea. This blog is mostly for my own documentation purposes but I've been aware for some time that I've benefited from reading about the often painstakingly documented projects of others. Sometimes even a brief mention in a blog or website can be enough to trigger an "ah-ha" moment that is all that's required to resolve some problem in one's own project.

Anyway - the idea. I want to create a hybrid analog/digital music MIDI driven music synthesizer based on an Arduino Mega2560. The Arduino will provide the digitally controlled oscillators, therefore always be in tune unlike many fully analog synths, and will provide the user interface and command and control features. The digital oscillator will drive wave shapers, then there will be more conventional analog voltage controlled filter, a voltage controlled amplifier and envelope generator. The whole system can be described in a block diagram:




OK - that's a lot of lines! But I'm hoping by careful design of the ArduinoMega shields I can minimize wiring and make routing feasible.

Requirements

This is definitely a hobby project rather than anything commercial. As such a lot of the decisions have been primarily made to increase/exercise my skills. The requirements can be summarized as follows:

  • Mostly SMD where possible
  • Not strictly modular in the conventional sense but at least extensible without having to redo the whole thing. 
  • Provide a base for experimentation - it would be good to be able to prototype modules on a breadboard for example. 
  • Small and portable with a single-rail 9v (battery or adapter) supply
  • MIDI input with CC mapping to nearly every adjustable parameter
  • Minimal user interface
  • Not much, if any, wiring (I don't enjoy wires)
  • Programmable via Arduino interface
  • Settings saved to SD card
  • Open source hardware and software

Features

Very Likely:

  • MIDI Input
  • Two DCOs
  • Two LFOs
  • Noise generator (I like noise)
  • Mixer
  • Voltage Controlled Filter
  • Envelope Generator (A/R at least)
  • Voltage controlled amplifier
  • LCD display 
  • Rotary encoders for input

Possible:

  • A third oscillator (The Arduino Mega has 4 16-bit timers)
  • Arpeggiator
  • Some sort of built-in sequencer

Keeping in mind:

  • Software based envelopes, LFOs etc. Might be worth considering a DAC "just in case"
  • Additional 5V voltage regulator to take the load off the Arduino one
  • CV/Gate input?

Inspiration

There are lots of great projects out there and a huge number of enthusiastic analog synth builder who are willing to share their projects and ideas. I'll describe some of my general inspirations in a subsequent post. However there are several projects that I'd like to mention as being especially important (and I'm sure many I don't know about!):

PicSynth - Also from New Zealand! This is a great project and I openly acknowledge taking a lot of the ideas from this. The creator does not release his software but sells pre-programmed Pic chips which is fine because then I'm not tempted to steal his software as well. He has however generously shared his schematics and I'm planning to use the waveshapers, filters, VCA and envelope generators with only small modifications. I really like his hand-drawn faceplates!

Sinneb - This blog hasn't been active for a while but there's some great "problem solving" type explanations and some useful Arduino examples

Audiono - Although this is based on granular synthesis and not very closely related to the current project it did show me how an Arduino could be used to make music. I built one a couple of years ago, added a photo-resistor and linear soft-pot as options to make a Theremin and/or ribbon controller type interface.


Technology

Here's some of the bits and pieces I'm planning on using. Some of these I have no experience with so I'll have to do some initial tests before I commit to them.

Arduino Mega 2560 - When I first thought of this project I had it in mind that I would develop my own board with some sort of AVR processor just for the fun of it. After I thought about it however I realized it might not be that much fun and I'd just be redoing an Arduino anyway. Using a standard Arduino Mega gives me a solid base to work on, with basic power supply, USB connectivity and pin breakout issues all solved. The Mega should have enough pins, likely enough memory and has the required two 16-bit timers to support two oscillators.

2.2" TFT LCD Display with MicroSD card - My initial experiments with this show it seems to work well, is nice and clear and bright and solves two problems (display and storage) at once. Like all AdaFruit products it seems well made and well supported.

RGB illuminated rotary encoder - The RGB part of this might not really be necessary however it will add a bit of glitz and may help with UI cues. The comments section on the product page is not actually that encouraging since it seems a number of people have had problems with them but I'll give them a try and see how they go before I commit. I've used simple rotary encoders in the past with an Arduino and once you get the hang of them they are pretty useful. I've also picked up the clear knobs which work pretty well with these.

MCP4161 Digital Pot - These are a key part of the design if it's to be able to save patches and to avoid having to wire up manual pots. I don't have any experience with these but they seem to be widely used with Arduinos and well supported with a library. I have no idea if 256 resolution steps will suffice but I'll need to experiment

SP3T Digital Switch - Again these are new to me. I have no idea if they will actually work in this context but they seem like what I need for routing signals. Definitely some experimentation required here.