Add SPI to littleBits Arduino 2

Music makers working with littleBits Arduino will almost certainly want to add a high(er) resolution digital-to-analog converter (DAC) to their Arduino. Part 1 shows how to add an ICSP header to your littleBits Arduino module. The ICSP header is where you find the SPI signals — MISO, MOSI, and SCK — along with Vcc (+5 Volts) and ground. The ICSP header pin layout is:

         GND ---O  O--- RESET
    MOSI/D16 ---O  O--- SCK/D15
         VCC ---O  O--- MISO/D14

This is the layout when viewing the top of the Arduino module with the USB connector at the top (i.e., away from you, “north” on a map).

Now let’s take a look at a simple circuit using the Microchips MCP4921 12-bit DAC. (Click on images to get higher resolution.)

spi_dac_schematic

Three signals control the DAC: Slave Select (SS/Pin D9), Master Out Slave In (MOSI) and Serial Clock (SCK). Data is sent to the DAC through SPI’s bit serial protocol. First, SS is driven LOW, then 16 bits are sent one at a time to the DAC. SCK synchronizes the data bits sent via MOSI. The first byte consists of a 4-bit “command” and the top 4 bits of the 12-bit value to be converted. The second byte is the lower 8 bits of the value to be converted. After sending 16 bits, the SPI master drives SS HIGH. If you’re curious about all of the signaling details, please see the MCP4921 data sheet.

The rest of the DAC circuit consists of a voltage reference for the converter and a post-conversion (reconstruction) filter. The filter is a simple, one stage passive low pass filter with a 10,600Hz corner frequency.

I built the DAC circuit on a small solderless breadboard. Here’s the layout.

spi_dac_breadboard

I connected MOSI, SCK, +5V and ground to the appropriate ICSP pins on the Arduino module. Slave Select is sourced by Arduino pin D9. I connected a littleBits Proto module to D9 and routed the input signal to the breadboard. If you want to postprocess the DAC’s audio output with littleBits modules, then route the DAC output to the Proto module’s output snap. Be sure to remove the shorting block (jumper) between the middle two pins on the Proto module. This approach provides power and ground to the audio postprocessing modules connected to the output snap of the Proto module — an important side-benefit.

The choice of pin D9 for Slave Select was the beginning of a long, hard journey in debugging. To make a long story short, pins D5 and D9 are buffered and the output buffer introduces additional delay on the Slave Select signal. The delay is long enough such that the DAC does not see a low Slave Select signal before data bits start arriving.

Here’s the code that writes the DAC:

#define NOP asm volatile ("nop\n\t")
void busyWait(uint8_t count) { 
  for(uint8_t i = count; i > 0 ; i--) { NOP ; } 
}

void writeDac(int16_t dacValue) {
  byte data ;
  SPI.beginTransaction(SPISettings(20000000,MSBFIRST,SPI_MODE0)); 
  digitalWrite(SlaveSelect, LOW) ;
  busyWait(25) ;
  data = highByte(dacValue) ;
  data = 0x0F & data ;
  data = 0x30 | data ;
  SPI.transfer(data) ;
  data = lowByte(dacValue) ;
  SPI.transfer(data) ;
  digitalWrite(SlaveSelect, HIGH) ;
  SPI.endTransaction() ;
}

The busy wait effectively stops the sketch for a little while after driving Slave Select LOW. This gives the Slave Select more time to reach the DAC before the sketch transfers the first data byte to the DAC. If you use an unbuffered pin like D1, you don’t need the busy wait.

It took a long time to eliminate all of the other possible issues that could have caused a failure: bad solder joints, wiring mistakes, etc. Fortunately, I have a similar DAC — the MidiVox — which works correctly. I also tested the hardware with Arduino UNO where all digital pins are unbuffered. It was frustrating to get everything working with the UNO, but not the littleBits Arduino module! Persistence wins the day.

In closing, I want to warn developers who interface high speed logic to littleBits Arduino. Beware of the delay through those buffered outputs! The delay may be long enough to throw off critical timing.

Add SPI to the littleBits Arduino

As Moe Szyslak might say, “He ain’t pretty no more!”

Last time through, I mentioned that I wanted to add a SPI digital-to-analog converter (DAC) to the littleBits Arduino module. The Microchips MCP4921 is a good candidate. It is a 12-bit DAC which communicates via the Small Peripheral Interface (SPI) bus or “SPI.”

The littleBits Arduino module is essentially an Arduino Leonardo. As such, its SPI port is available through the module’s ICSP pads. (“ICSP” stands for “in-circuit serial programming,” by the way.) The ICSP pads are the group of pads (two rows of three pads) between the D5 and D9 bitSnaps.

I soldered a 2×3 vertical pin header to the ICSP pads using a very simple jig. The image below is a “before and after” picture. (Click images for higher resolution.) The jig is a solderless breadboard that holds the header in place. I pushed the header into the breadboard just enough to hold the header and then placed the Arduino module over the header and pressed down. The idea is to get the black base of the header in contact and properly aligned with the module printed circuit board (PCB). The blue strips of masking (painter’s) tape keep the assembly together. The “after” part of the image shows the module with the header soldered in place.

icsp_solder_after

The jig really makes the soldering job easy. I have used other methods like trying to tape the header pins in place, but this approach was a piece of cake and frustration free.

The image below shows the header, module and jig just before soldering. The picture also shows the 2×3 vertical pin header and a compatible 2×3 female header block. You could install the female header block instead. I went with the male header because most ICSP cables expect a male header on the PCB to be programmed.

icsp_solder_jig

I ordered the parts from Mouser Electronics. Mouser and Jameco are my usual “go to” sources for components and tools. Here are the part numbers:

  • Harwin M20-9980346 03+03 DIL VERTICAL male header 2.54mm
  • Harwin M20-7830342 03+03 DIL VERTICAL female header 2.54mm
  • BPS BB170-WH White 170 point solderless breadboard
  • BPS ZW-MF-20 ZIPWIRE Female-Male 20cm
  • BPS ZW-MM-20 ZIPWIRE Male-Male 20cm

The “2.54mm” refers to the pin spacing (AKA “0.1 inch”). The female header is $1.19 and the male header is $.24. Buy at least ten of each and the price goes down a little. The contacts are tin; gold is a little more expensive.

I plan to make (eventually) little PCB “hats” using the female header blocks. The idea is to build a small, single-purpose circuit that plug onto the ICSP header or littleBits Proto module header like a hat. This approach would eliminate point-to-point connections using jumper wires. I may experiment with this approach once I get the basic DAC circuit ironed out and tested.

I really like Busboard Prototype System (BPS) products. BPS has the most useful prototyping board patterns. They also have these nifty ZIPWIRE ribbon cables. The wires terminate with individual male pins or female receptacles. Let’s say you need to make six connections from the ICSP header to a solderless breadboard. Then tear off a group of six wires and associated terminations. Push the receptacles onto the male header and push the pins into the solderless breadboard. The individual wires are color-coded in order to make the correct point-to-point connections at both ends. I’ll use ZIPWIRE to connect the Arduino SPI port (ICSP) to a solderless breadboard with the SPI DAC circuit.

If you have a littleBits Arduino module and want to make the most of it, it’s time to break out the soldering iron. Best of luck!

USB audio for Raspberry Pi

In the first few articles of this series:

Get started with Raspbian Jessie and RPi2
Get started: Linux ALSA and JACK
Raspberry Pi soft synthesizer: Get started

we used the built-in, 3.5mm audio output from the Raspberry Pi 2 (RPi2) to produce sound through powered monitors. If you tried this with your own RPi2, you realize that the sound quality is good enough for initial experiments, but not good enough for production — unless you’re into lo-fi.

This article starts with background information about the built-in audio circuit and why it is lo-fi. Then, I briefly mention a few alternative approaches for high quality audio output and audio input. Finally, I describe my experience bringing up the Behringer UCA-202 USB audio interface on RPi2 and Raspbian JESSIE.

Built-in audio

The Raspberry Pi Foundation has not yet published a schematic for the Raspberry Pi 2. However, Adafruit (and others) claim that the audio circuit is the same as the earlier, first generation Raspberry Pi. Let’s take a look at that.

The Raspberry Pi drives a pulse width modulated (PWM) signal into a passive low pass audio filter. (See the schematic below. Click on images to enlarge and get full resolution.)

rpi_audio_schematic

The PWM technique produces OK audio, but not good, clean audio. The software performs RPDF dithering and noise shaping to improve quality. Later RPi models (like the B+ and generation 2) have better power regulation and produce less digital noise at the audio output. There is much on-line debate about further improvements, but the PWM technique seems is limited by the 11-bit quantization. (This latter point alone is subject to debate!)

JACK seems to modify the audio sample stream as well. I can hear a loud hiss from my speakers when JACK is running and sending audio through the built-in DAC circuit. Ideally, the speaker should be completely silent.

Raspberry Pi 2 does not have an audio input. Thud!

Alternatives to built-in audio

If you want better audio quality or need to record an external audio signal, there are two approaches:

  1. Buy and install an audio board.
  2. Buy and install a USB audio interface.

With respect to the first approach, I briefly explored two of the available Raspberry Pi add-on audio boards:

  1. Cirrus Logic Audio Card
  2. HiFiBerry DAC Pro+

The Cirrus Logic board is well-specified with a WM5102 audio hub, WM8804 S/PDIF transceiver, and two WM7220 digital microphone integrated circuits. Those in the know will recognize these parts as Wolfson designs. The HiFiBerry DAC+ Pro is output only and uses an equally well-respected Burr Brown digital-to-audio converter (DAC).

Potential users are advised to be careful and to check compatibility with their particular model of Raspberry Pi. Adafruit cautions that the Cirrus Logic board may not be compatible with Raspberry Pi 2.

Both boards have drivers. However, both vendors eshew device configuration and prefer to distribute full OS images that include the requisite drivers. This approach puts existing users at a disadvantage. Now that I have Raspbian JESSIE installed and running, I would like to build and install the driver by itself, not write another micro SD card and go through the bring up process again.

With these issues in mind, I decided to go the USB audio interface route. It’s also the lowest cost option for me because I already have a Behringer USB audio interface in hand.

Behringer UCA-202 audio interface

The Behringer UCA-202 is an inexpensive ($30 USD) USB audio input/output interface. Analog signals are transfered on RCA connectors (left/right IN and left/right OUT). The UCA-202 also has a headphone output and an S/PDIF optical output. The UCA-202 is bus-powered and class-compliant. Conversion is 16-bit at 32kHz, 44.1kHz or 48kHz. The UCA-202 has a sister, the UCA-222, with the same spec.

I have used the UCA-202 as a plug-and-play audio interface with both Windows and Mac OS X. Now, I can claim success with Raspbian JESSIE Linux, too. This thing is the “pocket knife” of low-cost USB audio interfaces.

Even though I’m using a Behringer UCA-202, the directions below should also apply to other class-compliant USB audio interfaces. It never hurts to search the Web for directions, problems and tips for your particular audio interface. Just sayin’.

Before plugging in the UCA-202, run aplay -l and aplay -L to see a list of the sound cards (-l) and PCMs (-L) that are installed on your machine.

Next, plug the UCA-202 into one of the USB ports. Run the aplay commands, again, and look for a new audio device. On my machine, a new sound card appears in the aplay -l output:

    card 1: CODEC [USB Audio CODEC], device 0: USB Audio [USB Audio]
      Subdevices: 1/1
      Subdevice #0: subdevice #0

The new sound card is named “CODEC”, it is ALSA card number 1, and it has one subdevice (number 0). The aplay -L output lists a whole slew of new PCMs:

    sysdefault:CARD=CODEC
        USB Audio CODEC, USB Audio
        Default Audio Device
    front:CARD=CODEC,DEV=0
        USB Audio CODEC, USB Audio
        Front speakers
    surround21:CARD=CODEC,DEV=0
        USB Audio CODEC, USB Audio
        2.1 Surround output to Front and Subwoofer speakers
    surround40:CARD=CODEC,DEV=0
        USB Audio CODEC, USB Audio
        4.0 Surround output to Front and Rear speakers
    surround41:CARD=CODEC,DEV=0
        USB Audio CODEC, USB Audio
        4.1 Surround output to Front, Rear and Subwoofer speakers
    surround50:CARD=CODEC,DEV=0
        USB Audio CODEC, USB Audio
        5.0 Surround output to Front, Center and Rear speakers
    surround51:CARD=CODEC,DEV=0
        USB Audio CODEC, USB Audio
        5.1 Surround output to Front, Center, Rear and Subwoofer speakers
    surround71:CARD=CODEC,DEV=0
        USB Audio CODEC, USB Audio
        7.1 Surround output to Front, Center, Side, Rear and Woofer speakers
    iec958:CARD=CODEC,DEV=0
        USB Audio CODEC, USB Audio
        IEC958 (S/PDIF) Digital Audio Output
    dmix:CARD=CODEC,DEV=0
        USB Audio CODEC, USB Audio
        Direct sample mixing device
    dsnoop:CARD=CODEC,DEV=0
        USB Audio CODEC, USB Audio
        Direct sample snooping device
    hw:CARD=CODEC,DEV=0
        USB Audio CODEC, USB Audio
        Direct hardware device without any conversions
    plughw:CARD=CODEC,DEV=0
        USB Audio CODEC, USB Audio
        Hardware device with all software conversions

Not all of these PCMs are defined and configured by the way. Take note of the PCM named “hw:CARD=CODEC,DEV=0”. This is essentially the raw interface to the UCA-202. This PCM, at the very least, is defined.

Connect the audio outputs of the UCA-202 to powered monitors. Test the audio output interface by playing an audio (WAV) file:

    aplay -D hw:1,0 HoldingBackTheYearsDb.wav

or:

    aplay -D hw:CARD=ALSA,DEV=0 HoldingBackTheYearsDb.wav

Please note that you need to pass in the entire PCM name “hw:CARD=CODEC,DEV=0“.

Connect an audio source to the inputs of the UCA-202. Test the audio input interface by recording to an audio (WAV) file:

    arecord -D hw:CARD=ALSA,DEV=0 -f cd test.wav

I had trouble with the duration (-d) option. YMMV. Type Control-C to stop recording. Then, play back the test audio file through the UCA-202.

That’s all there is to it! The UCA-202 is truly plug and play.

Configure JACK and other applications

You need to tell the JACK audio server to use the UCA-202 instead of the RPi’s built-in audio device. Run qjackctl and click the Settings button. Select “hw:CODEC” as the Input Device and Output Device. (See the image below.) Click OK to return to the main control panel and start the JACK server. The server routes digital audio to and from the UCA-202 and JACK clients. Launch amsynth and click its Audition button. You should hear sound from the powered monitors that are connected to the UCA-202.

qjackctl_codec

ALSA’s aplay and arecord commands are OK for testing, but are clunky for practical use. Let’s install Audacity:

    sudo apt-get install audacity

Audacity is the well-known cross-platform, open source, audio editing tool.

Edit Audacity’s preferences to set the audio interface. (See the following image.) If you want to use ALSA directly, set the interface Host to ALSA. Then set the Playback and Recording Devices to “USB Audio CODEC”. Audacity should now be able to play and record through the UCA-202.

audacity_alsa

If you prefer to use JACK instead, once again edit Audacity’s preferences. (See the following image.) Set the interface Host to “JACK Audio Connection Kit”. Set the Playback and Recording Device to “system”. Make sure the JACK audio server is running. You may need to restart Audacity at this point. Play back an audio file or try recording a new file. JACK should serve the UCA-202 audio to/from Audacity.

audacity_jack