Spectrum Analyzer Revisited

Encouraged by the happy ending of the Swinging Needles project, I decided to revisit an earlier audio spectrum analyzer. This time, instead of programmatically processing analog signals, I used a VS1053 plugin to let the chip do the Fourier stuff.

Before even starting to read actual frequency band values, I wanted to test my sketch by reading the plugin’s default frequency settings from VS1053’s memory. However, some of these readings made no sense at all, up to the point that I suspected a faulty chip. It took me some time to find out that the chip needs a few seconds of audio input before it will tell you something useful, even if it concerns a fixed setting like number of frequency bands.

Once the above mystery was solved, things became very straightforward. What a versatile chip this VS1053 is! While playing a 320 Kbps internet radio station, it can easily handle 14 frequency bands and let an esp8266 at 160 MHz show the results on a 128×64 Oled display. Part of the credits should go to the authors of the libraries that I used.

 

First impression produced by the sketch below; better videos with sound (and colors?) will follow.

 

Here’s an esp8266 demo sketch for a basic internet radio (fixed station, no metadata, no audio buffer), just to show a 14 band spectrum analyzer on a 128×64 SH1106 Oled display. Used pins are for the rather rare Wemos D1 R1, so you’ll probably have to change them.

 

This is the content of the plugin.h file that needs to be in the directory of the sketch:

 

 

 

 

Swinging Needles

…finally!

It took me some time (and strong coffee), but I finally managed to have the ESP32 version of my Internet Radio drive two vintage style analog VU meters!

 

And here they are…

Web browser controlled prototype with basic display and no matrix keypad attached

Soon after I had purchased a rather obscure VU meter kit, it turned out that the driver board was completely useless because it was mono (Chinese for stereo?).

So I decided to have the ESP32 read the analog (DC-biased) line out signals from the VS1053 mp3 decoder, map the peak-to-peak readings to [0,255] scaled values and send these to the ESP’s DACs for driving the meters. However, I couldn’t figure out how to do that without having to connect the VS1053’s floating audio ground to the system ground, which, so I guessed, would either not work, cause noise or even damage something.

Then I remembered the VU meter plugin for the VS1053, enabling you to read dB levels from a memory register. But these plugin readings are leaking peak dB levels, so I started wondering if it was possible to use them for reconstructing instantaneous dB levels. Not suitable for audio purists, but I wouldn’t mind if the result was convincing. After all, these cheap Chinese meters will never behave like professional VU meters anyway.

So I wrote a simple algorithm with some tuning parameters and functions for scaling and smoothing, calculated resistor values for limiting current to my meters to 0.4 mA max, added (probably unnecessary) flyback diodes to protect the ESP32 from negative voltage spikes, and just gave it a try. Here’s the wiring that I used for the meters.

The first result looked surprisingly good: the needles eagerly followed every move and twist of the music. Since everything is controlled by an algorithm, any desired meter ballistics can be easily simulated without electronics.

For now, further fine tuning seems unnecessary. Besides, a more audiophile approach already crossed my mind: have a FreeRTOS task listen in to the mp3 stream while it’s being sent to the VS1053, and programmatically decode it. That will allow me to extract true dB levels and could even become a replacement for the VS1053 board. Like I recently read in an article about Software Defined Radio (SDR), “software is the new hardware“.

Anyway, music finally looks almost as good again as it did in my youth. Let’s just hope for an analog VU meter revival soon. And how about a global rediscovery of reel-to-reel tapedecks (with analog VU meters, of course)? That would make much more sense to me than the somewhat puzzling comeback of vinyl.

Dual Core Business

Almost a year after finishing my ESP8266-based Internet Radio project, I still have had no idea why running that sketch on the much more powerful ESP32 produces a heavily stuttering sound, resembling Michael Palin in “A Fish Called Wanda”.  So I wondered if I could solve this problem by dividing the audio streaming process between the ESP32’s two cores: filling the audio buffer on one core, and feeding the VS1053 decoder from that buffer on the other core.

Thanks to its builtin FreeRTOS, pinning a task to a specific core of the ESP32 is easy:

1. Put the code for the task in a function, wrapped in an endless for (;;) { } loop.

2. Create a task handle for the task in the main section of the sketch:

3. Create the task, specifying which function it should execute on which core:

 

(Since there was nothing in my loop() function (yet), I put a delay(1000); command in it. The loop() function runs on core 1, and I didn’t want it to claim too much of that core’s processor time.)

So my Radio sketch will have two independent tasks running on different cores: one that listens to the radio station’s audio stream for filling the circular buffer, and one for feeding the VS1053 decoder with bytes from that buffer. Both processes maintain their own pointer for accessing the circular buffer and the code guarantees that they will never catch up with the other process’ pointer. So there is no need to use a semaphore.

However, my first step into the dual core business produced an error. A ‘watchdog timer’ had become nervous and halted the ESP32. It turned out that including the following line in both functions solved at least that problem (bug?):

 

Now the ESP32 no longer crashed, and it actually produced sound. But alas, it was Michael Palin again…!

I can’t think of any reason for this behaviour. The serial monitor shows that the ESP32 has no problem filling the 30 Kbyte circular buffer, so feeding the VS1053 seems to be the bottleneck. I swapped cores for both tasks, but that didn’t help.

UPDATE: Meanwhile, I had become so desperate about finding a solution that I renamed the project “dESPeRadio“. But then, during a sleepless night, I wondered if the ESP32 might perhaps need a different policy for filling the circular buffer. The chunks it reads from the WiFi client per loop cycle have an upper size limit of 1024 bytes, in order to prevent the VS1053 from running dry during the process. But I didn’t specify a lower size limit.

For the ESP8266 this was OK, but the EP32 is so fast that, after it has rapidly filled the circular buffer, there will never be more than just a couple of free positions in the next loop cycle. All following cycles will therefore be very inefficient, causing so much overhead that the VS1053 actually runs dry in a very regular time pattern – the stuttering.

So I added just one single line for skipping the fill cycle if there’s less than 512 bytes of free buffer space available and uploaded the sketch without much hope, because so many ‘good’ ideas had failed before. What followed was complete silence…, which then turned out to be the pause between two movements of  Brahms’ fourth symphony! Then the music started in clean and, above all, uninterrupted sound!

The radio has been running non-stop now for a couple of hours. It looks like I finally have a solid and stable foundation for further development of my dESPeRadio on ESP32. Although using two cores isn’t necessary, it will be nice way to explore FreeRTOS.

In order to keep the code clean and readable, all future features and controls will be implemented as (optional) includible header files. I’ll make the full code available in my first github repository soon, so if you’re interested, stay tuned.

Plans for additional control options, apart from the already implemented keypad, are:

  • ☑ an embedded web server
  • ☐ the touch screen overlay of my display
  • ☐ IR remote
  • ☐ rotary encoders for volume, bass and treble

Other plans:

  • ☑ add VU meters (I love the analogue ones!)
  • ☐ use a FreeRTOS queue instead of a circular buffer

 

 

 

 

 

On-air

All ESP-based Internet Radio projects that I’ve seen so far lack a clean modular setup that programs should have if they offer many optional features and support a broad variety of hardware setups. So I decided to write my own sketch from scratch, consisting of a main sketch for all hardware-independent basic functions, and a growing set of includible modules, one for each optional feature or hardware device.

Now I can compile tailor made sketches for the desired functionality (like support for Air Traffic Control stations) and actually used hardware only. I’m satisfied with the first results, and I learned a lot during this project.

Keypad controlled prototype in radio mode (left) and ATC mode (right)

The radio on the pictures runs without problems on an ESP8266 board, driving an Adafruit VS1053 breakout and a 2.4″ ili9341 TFT display. It can be controlled with a 16-key matrix keypad and via a browser.

The prototype uses almost 500 lines of code for the radio. David Bird’s excellent METAR functions take yet another 500 lines. Too big to post on this page, I’m afraid…

It has the following features (more will be added later):

  • Can play mp3 encoded streams from internet radio stations (up to 320 Kbps).
  • Built in webserver accepts control commands via a browser.
  • Can also be controlled with a 4×4 matrix keypad, using VS1053’s own GPIO pins.
  • Offers storage of 40 station presets (grouped in four  bands).
  • Displays station name and song title on TFT display and web page.
  • Displays a decoded weather report (METAR) when playing an air traffic control (ATC) channel. The first 10 stations in the preset list are reserved for ATC stations (I used David Bird’s excellent functions for METAR decoding).
  • A 30 Kbyte ring buffer is used for smooth playback.
  • Can play stations with redirected urls.
  • Designed to handle chunked transfer encoded streams if necessary (I was unable to test this, because I couldn’t find any station that uses this encoding).
  • Stereo dB levels can be read directly from the chip and be used to drive VU meters from PWM pins (or DACs on ESP32).

Below is a flow chart of the initial connection, followed by the streaming process (basically a finite state machine). In practice, it all comes down to determining each incoming byte’s function within the stream by keeping track of some counters and states. Once the actual streaming has started, an incoming byte can be one of the next types:

  1. audio byte – will be sent to a ringbuffer that feeds the VS1053 decoder
  2. metadata byte – a human readable character from the song title
  3. metadata size – an integer; multiplied by 16, it is the following song title’s length
  4. CR or LF – used as separators
  5. chunk size (if station uses chunked transfer encoding) – size of the next chunk

Keep streaming

While still in an early stage of research for my Internet Radio (previous post), I came across Ed Smallenburg’s comprehensive Esp-radio project on github. It’s a very well documented project with a heavily commented sketch.

Instead of proceeding with my own (basic) Internet radio project, I decided to take Ed’s nearly flawless Esp-radio as a starting point, and adapt it according to my personal needs. Most important change will be the addition of two small oled displays for emulating analog VU meters.

There’s also an (even better?) version for ESP32 by the same author. This persuaded me to finally enter the ESP32 world, so now I’m the proud owner of a Wemos LOLIN32 Pro. My hope is that this powerful dual core board will be able to drive the entire setup of radio, TFT touch display, IR remote and VU meter oleds.

Update:

Unfortunately, my Wemos LOLIN32 Pro is from a batch with a faulty serial chip (CP2104). Most of the time, my PC will not recognize the board when I connect it, resulting in the serial chip becoming very hot within 5 seconds. This is my fourth Wemos device, two of which were crap!

However, when the board is recognized, it works fine and I even managed to upload and run the ESP32-Radio sketch. As for performance, I would say that both versions (ESP8266 and ESP32) seem equally satisfying and stable.

Below is a screenshot of the web interface. I removed and changed some buttons from the original version, and added a “now playing” display that updates every two seconds.

My futher plans with an ESP32 based Internet radio will have to wait for the replacement of my board. Planned changes are mainly peripheral and cosmetic, like adding VU-meters and a frequency analyzer. To be continued (stay tuned…)

Stream it!

 

The purchase of this versatile breakout board from Adafruit immediately made me put on hold all my ongoing projects. May the stream be with me!

 

This breakout board, built around the VS1053B chip, decodes various digital (stereo) audio formats such as MP3, AAC, Ogg Vorbis, WMA, MIDI, FLAC, WAV (PCM and ADPCM), and sends the analog signal to a female headphone plug (included as a breadboard friendly separate part). It can also record audio in both PCM (WAV) and compressed Ogg Vorbis format. All functions can be controlled over SPI.

Other features of the breakout board are:

  • microSD card holder for storing audio files
  • works with 3.3V and 5V boards (5V compliant pins)
  • 8 digital GPIO pins (not 5V compliant)
  • Volume, bass and treble control
  • a microphone input port
  • MIDI mode (reads MIDI data on the UART pin)
  • Additional functions (e.g. spectrum analyzer and VU meters) available via plugins

I had noticed the board before, but what made me decide to purchase it was this very simple esp8266 Internet Radio sketch on the Adafruit site. The fact that the VS1053 chip can handle mp3 live streams, delivered by an esp8266, means that it can be used for building a music streamer/internet radio! Since the esp8266 is capable of acting as a web client and a web server at the same time, it should be possible (in theory) to control the player with any web device (apart from several additional options, like buttons, IR remotes, rotary encoders, keypads, joysticks…).

After soldering the included header pins, I started with some simple MP3 playback from an SD card. My vintage Sennheiser Ovation was impressed! Then, with great expectations, I ran the Internet Radio sketch…. No sound! Not even debug messages on the serial monitor. Although Adafruit only, my hardware wasn’t from their new Feather/Wing line, for which the sketch was written. After quite some desperate attempts, almost losing hope, out of the blue came Bob Dylan’s “there must be some way out of here“. How appropriate (just as “something is happening, but you don’t know what it is” would have been). What did the trick was connecting the RST pins of the VS1053 and esp8266 boards, although the Adafruit example sketch suggests otherwise in the following line:

 

Here’s what I plan to do next:

  • Add a display (probably SPI, claiming two additional esp8266 pins; only one left…)
  • Make the esp8266 run a web server, listening to commands via a web page, very similar to the one I wrote for controlling my Transporter
  • Add manual control (buttons, IR, keypad?). The board’s own GPIO pins can be used for simple high/low devices like buttons
  • Support a list of selectable presets, pointing to internet radio stations
  • Make it possible to switch between radio mode and file mode (play ‘local’ music files)
  • Implement a larger (cyclic) buffer for more stability

 

 

 

 

 

Transporter

At the heart of Transporter is a “no compromise” attitude to component selection and electronic design.

 

I bought my Tranporter in 2010, right before this audiophile streamer was discontinued by Logitech. It was originally designed and manufactured by a company called Slim Devices. The above quote refers to them, certainly not to Logitech!

The Transporter, or any player from the Squeezebox line, is controlled by a free and open source streaming server. This server communicates with connected players via the ‘SlimProto’ protocol over TCP/UDP. All functions can be controlled via Telnet commands, but the server also has an interface that can be accessed over http. This means that you can fully control a player (or query its status) by sending http requests to the server. This is what sets this streaming solution apart from the many commercial (often LoFi) products that have meanwhile entered the market. And it can stream lossless FLAC files!

Once you understand the mechanism of controlling the player by sending commands over http, it only takes some basic knowledge of html, javascript and css to create a fully functional remote control web page.

My personal goal was to create a web page that shows a picture of the Transporter, with all buttons executing their function when clicked or touched (the player comes with a remote control but can also be controlled by buttons at the front). It also should mimic the player’s display. Most if this turned out to be very simple.

This picture shows a screenshot of my web based Transporter in action: a fully functional synchronized clone of the physical player, including volume- and brightness control, as well as the switch back to the ‘NOW PLAYING’ display, 30 seconds after the last command.

The approach is pretty straightforward:

The buttons:

  • Create a <div> element for every button and give it an unique id.
  • Use css to place every <div> exactly over ‘its’ button on the Transporter image.
  • Add an onclick event to every <div>, executing a javascript function with the <div>’s id as a parameter.
  • Write this javascript function, making it send the appropriate command url to the server, based on the firing <div>’s id.

The display:

  • Create a <div> for every relevant part of the display and give it an unique id.
  • Use css to place every display <div> at its right position on the Transporter image.
  • Create a javascript function with a timer loop, asynchronously requesting the latest information that the server has sent to the physical Transporter’ s display. By using ajax calls, only the display will be refreshed (vs the entire web page).
  • Make the same javascript function populate the display <div> elements with the updated display info (innerHTML property).

Well, that’s basically all it takes for the essential functions. Because it’s completely web based, it will work in every browser on every operating system. No app installation or Java required! This method gives you full control over what to display, and how. You’re not even limited to what the physical Transporter can do or show. For instance, you could add cover art or extra buttons for custom functions.

Continue reading “Transporter”