# Raspberry Pi LED Spectrum Analyzer

## Introduction and Ingredients

http://www.youtube.com/watch?v=AMPJH1LOu50

A Spectrum Analyzer shows the loudness of different frequency bands (low, mid, high) in real-time, letting you visualize music. Using a RasPi, RGB LED Strip and some wire, make yourself a dynamic display and media player. This project is based on some great python xmas light code from the [LightShowPi project,](https://plus.google.com/communities/101789596301454731630) and advanced users can even configure it for song voting via SMS!  
  
The project runs in Python, even including the audio processing. It's just able to play and analyze mp3s in realtime as long as your Pi isn't doing anything else.

![](https://cdn-learn.adafruit.com/assets/assets/000/013/626/medium800/raspberry_pi_spectrum_analyzer_display_raspi_rgb_led_strip.jpg?1389556742)

 **Hardware**

- RasPi -- this guide is built on one running wheezy, Raspbian, ver 3.10.19
- [5m RGB LED strip](http://www.adafruit.com/products/306), (~160 leds) controllable via SPI, built in PWM control. This guides shows using one strip wrapped around to form 5 columns, and writing to different segments of the strip. Only three wires connected to the Pi: ground, SPI Clock and SPI Data.
- [10A 5V power supply to drive the LEDs](http://www.adafruit.com/product/658)
- Miscellaneous:
  - [USB WiFi adapter](http://www.adafruit.com/products/814) (RTL8188CUS chipset drivers are built in to wheezy OS!) if you don't want to use Ethernet. I used these [instructions](http://learn.adafruit.com/adafruits-raspberry-pi-lesson-3-network-setup) to get it working.
  - [SD card 4GB or larger](http://www.adafruit.com/products/102)
  - [USB Power speakers](http://www.adafruit.com/product/1363)
  - Powered USB Hub to plug in keyboard, mouse, wifi,
  - Some cell phone charger to power the Pi via it's USB power connector
  - USB keyboard, mouse, HDMI monitor
  - wire, some female to female jumpers or some [JST connectors](http://www.adafruit.com/products/578) if you don't want to solder to the RGB strip.

**Software** :

- This project is mostly based on the [Pi-based xmas lights controller code](https://plus.google.com/communities/101789596301454731630) from Chris Usey,Todd Giles and Ryan Jennings. It's a full command center for orchestrating xmas lights to audio (wav, mp3, etc). Their code and hardware lets you setup playlists and turn on and off 120VAC power based on frequency bands. You can even vote on songs through SMS messages! We're going to control an RGB strip instead of output pins on the Pi. Grab the attached [synchronized\_lights\_LED\_strip.py](http://www.instructables.com/files/orig/F8J/J4J8/HQCWG0FE/F8JJ4J8HQCWG0FE.py) file.
- [Python control of LPD8806 RGB LED strip](https://github.com/adammhaile/RPi-LPD8806) via SPI.
- This isn't specific to this project, but I used the [Geany](http://www.geany.org/) IDE for coding right on the Pi.

If you have any questions, check out the [LightShowPi github repo](https://github.com/shatteredsword/lightshowpi)

# Raspberry Pi LED Spectrum Analyzer

## LED strip and RGB LED software

Here's an overview picture showing all the major components. Go ahead and plug in your powered USB hub, mouse, keyboard, speakers, and either ethernet or WiFi connection.

![](https://cdn-learn.adafruit.com/assets/assets/000/013/628/medium800/raspberry_pi_spectrum_analyzer_raspi_parts.jpg?1389558411)

# Connecting the RGB LED Strip
First, cut back the plastic sleeve from the RGB strip and solder 4 wires. Note that there's an Input and Output end of the strip, and it's important to connect to the input end. You can also use some JST connectors if you don't want to solder.  
![](https://cdn-learn.adafruit.com/assets/assets/000/013/627/medium800/raspberry_pi_RGB_LED_strip_wiring_spi_LPD8806.jpg?1389558154)

![](https://cdn-learn.adafruit.com/assets/assets/000/013/629/medium800/raspberry_pi_raspi_wiring_rgb_led_strip.jpg?1389558444)

Now connect the wires to the Raspberry Pi and 5V Power supply as shown. Don't forget to connect the ground of the power supply to the ground of the Pi! A much more [detailed guide](http://learn.adafruit.com/light-painting-with-raspberry-pi/hardware) to creating this connection can be found in the light painting project. The picture below is from that guide.

![](https://cdn-learn.adafruit.com/assets/assets/000/013/630/medium800/raspberry_pi_diagram.png?1389558710)

# RGB Strip Software
  
Grab the [software](https://github.com/adammhaile/RPi-LPD8806) and follow the instructions on that page for getting the Pi able to output to SPI. **Do** install spidev. It's important that you use the hardware SPI because any bit-banging approach won't be fast enough.  
  
**sudo raspi-config** to enable hardware SPI (follow instructions at git page). While you're there, set the audio output to be out the 3.5mm jack rather than the HDMI connector.  
  
I added the install directory to my PYTHONPATH in bashrc so I could call the functions from anywhere.  
  
**nano ~/.bashrc:**  
  
**export PYTHONPATH=$PYTHONPATH:/home/pi/RPi-LPD8806**  
  
(you could also add **PYTHONPATH=$PYTHONPATH:/home/pi/RPi-LPD8806** to /etc/environments, but this will require a reboot to register on new terminal windows)  
  
Test out that the strip works by running the example code:  
  
**python example.py**  
  
The xmas light code we're going to download later wants to run as root, and when you run things with a sudo in front, the environment variables, specifically, PYTHONPATH aren't transferred.  
  
To keep those environment variables around, edit /etc/sudoers by typing  
  
**sudo visudo**  
  
and then add to the bottom  
  
**Defaults env\_keep=SYNCHRONIZED\_LIGHTS\_HOME  
Defaults env\_keep+=PYTHONPATH**  
  
the first line is something we'll need for the xmas light package to be installed later.   
  
To test that you have it setup right and can run things as root, close the terminal and re-open, then type  
  
**sudo python**  
**from bootstrap import \***  
**led.fill(Color(50,50,50),0,10)**  
**led.update()**  
  
that should turn on the first 10 LEDs. You might need to restart a terminal window to make sure the environment variables get loaded.  
![](https://cdn-learn.adafruit.com/assets/assets/000/013/631/medium800/raspberry_pi_RGB_led_strip_as_spectrum_analyzer.jpg?1389559835)

# Mount the LED Strip
  
I looped my strip back and forth on a baby gate with twist ties, but this wastes LEDs at the bends. A cleaner route would be to cut the strip into 5 even segments and solder 4-wire jumpers between each segment. You'll just need to adjust the address of the LEDs for the columns. # Raspberry Pi LED Spectrum Analyzer

## Speed up the RGB Strip Software

The RGB python code is a bit slow at the time of this writing, but a few tweaks can dramatically speed it up.   
  
First edit **ledstrip.py** to use the hardware SPI, note the argument **use\_py\_spi = True**.  
  
My ledstrip.py was located at /home/pi/RPi-LPD8806/raspledstrip/ledstrip.py

```
def __init__(self, leds, use_py_spi = True, dev="/dev/spidev0.0", driver="LPD8806"):
```

Now inside LPD8806.py, we're going to change the SPI speed to 16MHz.```
if self.use_py_spi:
	import spidev
	self.spi = spidev.SpiDev()
	self.spi.open(0,0)
	self.spi.max_speed_hz = 16000000
	print 'py-spidev MHz: %d' % (self.spi.max_speed_hz / 1000000.0 )
```

That print statement is there just to make sure everything gets set correctly.  
  
One final change to the LPD8806.py file is in the update() function. Every call to self.spi.xfer2() seems to have a 160ms delay at the end, so we're simply going to change the update function so that it calls the spi.xfer2() fewer times.

```
def update(self, buffer):
	temp_buffer = []
	if self.use_py_spi:
		for x in range(self.leds):
			temp_buffer = temp_buffer + [i for i in buffer[x]]
			#self.spi.xfer2([i for i in buffer[x]])
		self.spi.xfer2(temp_buffer)
		self.spi.xfer2([0x00,0x00,0x00]) #zero fill the last to prevent stray colors at the end
		self.spi.xfer2([0x00]) #once more with feeling - this helps :) time2 = time.time()
```

If you re-run the example.py python file, you should see a substantial increase in speed.

# Raspberry Pi LED Spectrum Analyzer

## Install LightShow Pi

Now that we've got writing to the LED strip fast, and accessible from python running as root from anywhere, it's time to install the fantastic xmas [light orchestration software](https://plus.google.com/communities/101789596301454731630), and update it to control the LED strip.  
  
Once you download the [code](https://bitbucket.org/togiles/lightshowpi/wiki/Home "Link: https://bitbucket.org/togiles/lightshowpi/wiki/Home") from bitbucket, follow the instructions to get it installed. I recommend installing to /home/pi/lightshowpi to avoid some installation issues. You can also change the **INSTALL\_DIR** inside install.sh if you wish.  
  
Before running sudo ./install.sh, you should edit the file and change the INSTALL\_DIR. Then run:  
  
**sudo ./install.sh**  
  
The end of the bash script sets up some environment variables in /etc/environment, but I also added it to my .bashrc at the end like so:  
  
**export SYNCHRONIZED\_LIGHTS\_HOME="/home/pi/lightshowpi"  
export PYTHONPATH=$PYTHONPATH:/home/pi/RPi-LPD8806-master**  
  
that second line is for the LEDs. Make sure sudoers also has this line so that the environment variable sticks around when you run things as sudo. This should already be there from a previous step.  
  
**Defaults env\_keep=SYNCHRONIZED\_LIGHTS\_HOME**  
  
As a first step, try to run a song and see if the code throws any errors:  
  
**sudo py/synchronized\_lights.py --file /home/pi/some\_random\_music\_file.mp3**  
  
Don't hear any sound? I had to change my audio out from the default HDMI to the onboard 1/8" jack:  
  
**amixer cset numid=3 1**  
  
I also had to turn up the volume  
  
**amixer set PCM 1**

# Raspberry Pi LED Spectrum Analyzer

## Customize LightShowPi

Our final step is to customize LightShowPi's config file, and run a special script that outputs to our RGB LED strip instead of turning GPIO pins on and off.  
  
go into the lightshowpi/config directory, and **copy of defaults.cfg** to **overrides.cfg**. Open overrides.cfg and make the following changes:  
  
**gpio\_pins = 7,0,1,2,3** # it doesn't matter what the numbers are, only that there are 5 for our 5 LED columns  
  
**preshow = on:0,off:0** # no need to delay the start of the show!  
  
**min\_frequency = 50** # this is just preference since my speakers don't play much sound below 50Hz. You can specify the exact frequency ranges you want, too.

\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_  
  
Now, if you haven't already downloaded the code, grab the [synchronized\_lights\_LED\_strip.py](http://www.instructables.com/files/orig/F8J/J4J8/HQCWG0FE/F8JJ4J8HQCWG0FE.py "Link: http://www.instructables.com/files/orig/F8J/J4J8/HQCWG0FE/F8JJ4J8HQCWG0FE.py") file and put it in the same directory with the original syncrhonized\_lights.py file. This file writes out to our LED strip instead of the GPIO pins in the default script.  
  
You might need to make the file executable before running it:  
  
**chmod +x synchronized\_lights\_LED\_strip.py**  
  
Try running with the new script:  
  
**sudo py/synchronized\_lights\_LED\_strip.py --file /home/pi/lightshowpi/music/some\_song.mp3**  
  
And that's it! Hopefully you hear and see music!   
  
Depending on your strip, you might need to make changes to the display\_column() function to adjust for what number LEDs make up your columns.   
  
For some more details on how the code works and changed made to the original script, checkout the longer [instructable](http://www.instructables.com/id/Raspberry-Pi-Spectrum-Analyzer-with-RGB-LED-Strip-/) I originally wrote.  
  
If you have any questions, you can use the feedback link on the left or contact me through my google + page: [plus.google.com/+ScottDriscoll](http://plus.google.com/+ScottDriscoll "Link: http://plus.google.com/+ScottDriscoll") or try the [LightShowPi community](http://https//plus.google.com/communities/101789596301454731630)


## Featured Products

### Digital RGB LED Weatherproof Strip - LPD8806 32 LED 5m

[Digital RGB LED Weatherproof Strip - LPD8806 32 LED 5m](https://www.adafruit.com/product/306)
These LED strips are fun and glowy. There are 32 RGB LEDs per meter, and you can control each LED individually! Yes, that's right, this is the digitally-addressable type of LED strip. You can set the color of each LED's red, green and blue component with 7-bit PWM precision (so 21-bit...

In Stock
[Buy Now](https://www.adafruit.com/product/306)
[Related Guides to the Product](https://learn.adafruit.com/products/306/guides)
### Raspberry Pi Model B 512MB RAM

[Raspberry Pi Model B 512MB RAM](https://www.adafruit.com/product/998)
Adafruit ships the **Raspberry Pi Model B 512MB RAM** as of 10/18/2012.  
  
The Raspberry Pi® is a single-board computer developed in the UK by the Raspberry Pi Foundation with the intention of stimulating the teaching of basic computer science in schools. The Raspberry...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/998)
[Related Guides to the Product](https://learn.adafruit.com/products/998/guides)
### 5V 10A switching power supply

[5V 10A switching power supply](https://www.adafruit.com/product/658)
This is a beefy switching supply, for when you need a lot of power! It can supply 5V DC up to 10 Amps, running from 110V or 220V power (the plug it comes with is for US/Canada/Japan but you can use any plug adapter for your country, or just replace the cable with a standard computer/appliance...

Out of Stock
[Buy Now](https://www.adafruit.com/product/658)
[Related Guides to the Product](https://learn.adafruit.com/products/658/guides)
### 5V 4A (4000mA) switching power supply - UL Listed

[5V 4A (4000mA) switching power supply - UL Listed](https://www.adafruit.com/product/1466)
Need a lot of 5V power? This switching supply gives a clean regulated 5V output at up to **4 Amps** (4000mA). 110 or 240 input, so it works in any country. The plugs are "US 2-prong" style so you may need a plug adapter, but you can pick one up at any hardware store for $1 or so,...

In Stock
[Buy Now](https://www.adafruit.com/product/1466)
[Related Guides to the Product](https://learn.adafruit.com/products/1466/guides)
### Female DC Power adapter - 2.1mm jack to screw terminal block

[Female DC Power adapter - 2.1mm jack to screw terminal block](https://www.adafruit.com/product/368)
If you need to connect a DC power wall wart to a board that doesn't have a DC jack - this adapter will come in very handy! There is a 2.1mm DC jack on one end, and a screw terminal block on the other. The terminals are labeled with positive/negative assuming a positive-tip configuration...

In Stock
[Buy Now](https://www.adafruit.com/product/368)
[Related Guides to the Product](https://learn.adafruit.com/products/368/guides)
### USB Powered Speakers

[USB Powered Speakers](https://www.adafruit.com/product/1363)
Add some extra boom to your audio project with these powered loudspeakers. We sampled half a dozen different models to find ones with a good frequency response, so you'll get quality audio output for music playback. Simply connect the standard 3.5mm stereo plug into your Raspberry Pi model...

In Stock
[Buy Now](https://www.adafruit.com/product/1363)
[Related Guides to the Product](https://learn.adafruit.com/products/1363/guides)
### USB 2.0 Powered Hub - 7 Ports with 5V 2A Power Supply

[USB 2.0 Powered Hub - 7 Ports with 5V 2A Power Supply](https://www.adafruit.com/product/961)
Add lots more USB capability to your Raspberry Pi or computer using this powered USB 2.0 hub. It adds a full **seven powered ports** , all at USB 2.0 speeds so you can use video cameras and other high speed devices (cheaper hubs are v1.1 and not as fast!)  
  
The extra sauce...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/961)
[Related Guides to the Product](https://learn.adafruit.com/products/961/guides)
### PIHUB - USB Hub for Raspberry Pi with US Power Adapter

[PIHUB - USB Hub for Raspberry Pi with US Power Adapter](https://www.adafruit.com/product/1516)
![Raspberrypi](https://www.adafruit.com/images/madeinuk.jpg) **A high-power, reliable, USB 2.0 hub ideal for the Raspberry Pi®  
 Fast, Fiesty and Fruity - Comes with a US-plug 5V 3A power supply, plenty of power for your...**

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/1516)
[Related Guides to the Product](https://learn.adafruit.com/products/1516/guides)

## Related Guides

- [LPD8806 Digital RGB LED Strip](https://learn.adafruit.com/digital-led-strip.md)
- [Gemma 3D Printed Tree Topper](https://learn.adafruit.com/gemma-3d-printed-tree-topper.md)
- [3.5" PiTFT OctoPrint Rig](https://learn.adafruit.com/3-dot-5-pitft-octoprint-rig.md)
- [DIY WiFi Raspberry Pi Touchscreen Camera](https://learn.adafruit.com/diy-wifi-raspberry-pi-touch-cam.md)
- [Trellis Python Library](https://learn.adafruit.com/trellis-python-library.md)
- [xLights for Sparkle Motion Board](https://learn.adafruit.com/xlights-for-sparkle-motion-board.md)
- [Glowing WhoVille Hat](https://learn.adafruit.com/glowing-whoville-hat.md)
- [Networked Thermal Printer using Raspberry Pi and CUPS](https://learn.adafruit.com/networked-thermal-printer-using-cups-and-raspberry-pi.md)
- [Flora+NeoPixel LED Skateboard Upgrade](https://learn.adafruit.com/flora-neopixel-led-skateboard-upgrade.md)
- [Raspberry Pi Pygame UI basics](https://learn.adafruit.com/raspberry-pi-pygame-ui-basics.md)
- [Halloween Neon LED Signs](https://learn.adafruit.com/halloween-neon-led-signs.md)
- [Adafruit DPI Display Kippah](https://learn.adafruit.com/adafruit-dpi-display-kippah-ttl-tft.md)
- [Adafruit 16-Channel PWM/Servo HAT & Bonnet for Raspberry Pi](https://learn.adafruit.com/adafruit-16-channel-pwm-servo-hat-for-raspberry-pi.md)
- [NeoPixel Basketball Hoop](https://learn.adafruit.com/neopixel-mini-basketball-hoop.md)
- [Rainbow Chakra LED Hoodie](https://learn.adafruit.com/rainbow-chakra-led-hoodie.md)
- [Glowing Viking Rune wayFinder](https://learn.adafruit.com/glowing-viking-rune-artifact.md)
