Raspberry Pi Lights: how to sync Christmas lights to midi audio

** UPDATE 9/21/2014 **

I updated the source code today. Now lightorgan supports more than 7 output channels.  It chooses the pin to light up based on both the pitch and the octave of every note. Now the number of supported output channels is limited only by how dynamic the range of the midi file is. I observed that this worked practically for at least 24 channels on several Christmas songs. This is cool because the new Rasperry Pi Model B now supports up to 28 pins!  See Gordon’s page at http://www.wiringpi.com.

Also, the WiringPi pins that lightorgan uses are now configurable. Just modify the array called pinMapping[] that’s near the top of the lightorgan.c file to add, remove, or remap a lightorgan channel to a corresponding WiringPi  pin. Recompile with your changes and then you should be good to go.

Check out the new source code from the google code page:

svn checkout http://pi-lightorgan.googlecode.com/svn/trunk/ pi-lightorgan-read-only


Special thanks to KnC for collaborating with me on getting this up and running!



Check out Todd Gile’s project which uses the Raspberry Pi to sync mp3 audio by way of real time sampling! It’s really an awesome project, and if you want to use mp3 instead of midi, you should definitely check it out. https://bitbucket.org/togiles/lightshowpi


I’m recommending the use of the SAINSMART mechanical relays instead of the solid state ones I was originally using. There have been some reports that the PI does not have enough amperage to drive the solid state relays in some cases.

This post will show you the details of my Raspberry Pi powered synchronized Christmas lights project.  I really enjoyed working on this and I wanted to share it with anyone interested in this sort of thing.

It’s fun to begin at the end, so here is a video of the Pi Lights playing to Star Wars.

Also, the Peanuts theme song:

Theory of operation:

Untitled drawing

First, a Midi file is fed into Linux’s ALSA midi sequencer service, destined to be played on a particular port.  The sequencer then broadcasts accurately timed midi events to all programs subscribed to said port.  One of those programs is Timidity, which is a free midi synthesizer that will take care of playing the sound.  The other is a simple C program that I wrote to  control the GPIO pins based on midi events.  Each GPIO pin controls a solid state relay, which ultimately toggles the main electricity  going to each bank of  lights.

Materials required:

1 Raspberry Pi and case


SainSmart 8-Channel 5V Solid State Relay Module Board  (30$ on amazon.com)

Female to male jumpers

Cooper Wiring Devices 15-Amp White Duplex Electrical Outlet

6 Electrical outlets ( < $1 US  each)

CARLON 2-Gang Plastic Old Work Electrical Box 2-Gang Almond Standard Duplex Receptacle Plastic Wall Plate 2-Gang Light Almond Blank Nylon Wall Plate

3 Electrical boxes and cover plates  (prices vary)

 50' 14 AWG Non-Metallic Wire

50 feet of Electrical cable of appropriate gauge

IDEAL 50-Count 1/2-in Plastic Insulated Staples

A bag of electrical cable staples

Plytanium 15/32 x 4 x 8 Pine Sheathing Plywood

Enough Plywood to build a ~24″/12″/24″ box

Product Details

A small amplifier (~$20 amazon):

PYLE PLMR24 3.5-Inch 200 Watt 3-Way Weather Proof Mini Box Speaker System (White)

Outdoor speakers: (~$20 amazon )

Software needed:

Debian Rapsberry Pi distro  (http://www.raspberrypi.org/downloads)

Timidity (apt-get install timidity)

Alsa devel libraries (http://www.alsa-project.org/main/index.php/Main_Page)

Gordon’s wiringPi library (https://projects.drogon.net/raspberry-pi/wiringpi/)

About Midi Files:

Midi files are comprised of a sequence of events that richly describe how to play a song.  There are many different kinds of events, but the most interesting ones for my purposes are the NOTE ON and NOTE OFF events.

NOTE ON event {

Note value: { 0..127 }

Channel { 0..15 }


NOTE OFF event {

Channel { 0..15 }


Think of the note value part of the NOTE ON event as corresponding to key on an imaginary piano that has 128 keys.

Controlling the GPIO pins based on midi events:

I decided to control the pins based on the pitch of the notes.  There are 12 notes in an octave, so the pitch is obtained by taking modulus 12 on the note value.  From there, it’s again divided among the number of pins.  Using 6 pins, pin 0 corresponds to notes with pitch 0-2, pin 1 corresponds to 2-4, etc.

Getting Started – Software:

The first thing to do is download Timidity and make sure midi playback works properly.  After installing, configure it to run as a daemon.  Then use the ‘aconnect -o’ command to verify that it is listening on a midi port.  It should display something like this:

client 14: ‘Midi Through’ [type=kernel]
0 ‘Midi Through Port-0’

client 128: ‘TiMidity’ [type=user]
0 ‘TiMidity port 0 ‘

Try playing a midi file using the ‘aplaymidi’ command.  For example, ‘aplaymidi –port 128 yourMidiFile.mid’.

It’s probably the case that the default Timidity settings will be too aggressive for the Raspberry Pi to handle.  The midi playback may stutter and crackle.  To remedy this, modify the /etc/timidity/timidity.cfg file.  Uncomment these lines and restart Timidity.

opt EFresamp=d          #disable resampling
opt EFvlpf=d            #disable VLPF
opt EFreverb=d          #disable reverb
opt EFchorus=d          #disable chorus
opt EFdelay=d           #disable delay
opt anti-alias=d        #disable sample anti-aliasing
opt EWPVSETOZ           #disable all Midi Controls
opt p32a                #default to 32 voices with auto reduction
opt s32kHz              #default sample frequency to 32kHz

Once that’s all sorted out, it’s time to get started with the pin controller program.  You’ll need to download Gordon’s wiringPi library.  Download the latest software from the his repository, and follow the easy installation instructions (https://projects.drogon.net/raspberry-pi/wiringpi/).

The ALSA libraries should be installed by default on debian.  If you are using a different distro, go to http://www.alsa-project.org/main/index.php/Main_Page and get the latest development libraries.

You can then download the source code for my program here, called light organ.  http://code.google.com/p/pi-lightorgan/source/browse/trunk/lightorgan.c.  Check out the code to your pi using this command:

svn checkout http://pi-lightorgan.googlecode.com/svn/trunk/ pi-lightorgan-read-only

Compile the program by issuing the ‘make’ command.  Feel free to edit the code to suit whatever new ideas you come up with.

At this point, you should have a binary for the pin controlling program.  Run lightorgan as root.  Open another terminal and issue the command ‘aconnect -ol’ to list all of the active midi outputs.  You should see three entries: Timidity, lightorgan and the midi thru port.  The midi thru port needs to be configured to send it’s output both to lightorgan and Timidity.  Here is an exmaple of doing that:

aconnect -ol

client 14: ‘Midi Through’ [type=kernel]
0 ‘Midi Through Port-0’
client 128: ‘TiMidity’ [type=user]
0 ‘TiMidity port 0 ‘
client 129: ‘LightOrgan’ [type=user]
0 ‘listen:in       ‘

aconnect  14:0 128:0

aconnect 14:0 129:0

aconnect -ol

client 14: ‘Midi Through’ [type=kernel]
0 ‘Midi Through Port-0’
Connecting To: 128:0, 129:0
client 128: ‘TiMidity’ [type=user]
0 ‘TiMidity port 0 ‘
Connected From: 14:0
client 129: ‘LightOrgan’ [type=user]
0 ‘listen:in       ‘
Connected From: 14:0

At last, the ports are configured properly.  Now all midi traffic destined for port 14 (the through port) will be copied to ports 129 and 128 – Timidity and lightorgan.  You can use aplaymidi –port 14 midifile.mid to send to both Timidity and lightorgan.

If you’ve reached this point and everything is setup properly – you should be able to test the setup using a breadboard and some LEDs.  Here is an example with 4 LEDs:

In the file lightorgan.c, change MY_NUM_PINS to be the number of pins you plan on using.

Wire your pins to the LEDs using the chart at Gordon’s site: https://projects.drogon.net/raspberry-pi/wiringpi/pins/

Be sure to check out his tutorial on how to get started with GPIO on the Pi for more information.

Putting it all together:

I chose to build an enclosure using plywood to house the PI, the amplifier, outlets, relays, and connectors:

Photo: Construction has begun for my sound synchronized christmas light project. The photo shows six solid state relays and a half completed wooden enclosure. Also, a cat named dewey.

The junction box on the left is where the power comes in.  From there, individual runs of romex are run across to each relay, the ‘hot’ wire for each of these runs is separated by a solid state relay.  When voltage is run through the bottom terminals of a relay, the power is able to travel freely onto the outlet on the right side:

Photo: Oh what tangled webs we weave.

Shown above are 8 outlets (and also, my cat Dewey).  Two of the outlets are not connected to the relays, they are there to provide power for the Pi and the amp.  The connections on the left side are yet to be made.  Here is a view from another angle:


From here, the only thing left to do is complete the enclosure, add in the amp, add the Pi and wiring from the Pi.


This is the finished state of the box.  I probably should have cleaned it up a bit more, but I was too eager to see it in action. With everything being in an outdoor environment, I put a container of Damp-Rid in the box to try to mitigate the threat of condensation.

I hope this has been helpful.  If you have any questions, please comment.

-Chivalry Timbers

This entry was posted in Uncategorized. Bookmark the permalink.

315 Responses to Raspberry Pi Lights: how to sync Christmas lights to midi audio

  1. Tarcas says:

    Hi Chivalry,
    I used your LightOrgan program to animate my display this Christmas. I thought people here browsing the project might like to see a few of the songs as they played on my house this year.
    At the end of my youtube playlist, you will find a tour of my control board and modified power strips.
    Please note that this is NOT a tutorial on how to do it. There are a number of safety precautions that I took that are not mentioned in these videos. Your enclosed box is a much better plan than mine. I am not responsible if anybody tries to copy my method and causes injury, damage, or death.
    That said, here is my Youtube Christmas Light playlist:

  2. Pingback: Raspberry Pi — что можно сделать на основе «малинки»? | FNIT.RU

  3. NIKHIL says:

    can you please guide how to prepare a tron dance act. please look on youtube for reference video, also called as techno light balance dance act.
    I am not worried about the costumes, I am looking for software and board receiver that emit controlled light in further led lights attached with the costumes.

  4. Pingback: Cool Raspberry Pi Project Ideas

  5. Pingback: 25 unglaubliche Raspberry-Pi-Projekte | t3n

  6. derekshull says:

    Can this set up be rigged to listen to midi notes sent from a web browser using socket.io and play the notes/light up the lights?

    • Chivalry Timbers says:

      I think it’s possible. LightOrgan receives input from the Alsa midi port (mapped from midi port 14). If you can configure socket.io to send midi events to midi port 14 on the Pi, then LightOrgan will play the note. Similarly, Timidity will play the sound if it is mapped to port 14

  7. Pingback: Etwas für den Sonntag : Geniale Projekte für Raspberry Pi und Pi 2 ! | DER KLUGSCHEISSER

  8. Pingback: Raspberry Pi Projects: Best projects for your raspberry pi 1&2.

  9. Pingback: 7 cool Raspberry Pi 2 projects (and a sweet deal) | 0LF Translated & Grouped

  10. Anonymous says:

    this gets me mad

  11. Steve says:

    There are 8 notes in an octave. Do – Re – Mi – Fa – Sol – La – Ti – Do

    I assume this would tweak the way you develop the software?

    • KnC says:

      There are actually 12 notes per octave. (Don’t forget the half-steps.) 😉

    • Chivalry Timbers says:

      Yeah I think technically you’re correct that there 8 notes in the musical theory definition of octave. In terms of implementation, the actual octal distance between two notes is 7. For example, the last ‘Do’ in the octave you cited above is actually the first ‘Do’ in the next octave.

      And as KnC stated, there are technically 12 steps in an octave. Here is an interesting article that shows why our ancestors chose to divide it like that:


      • KnC says:

        My Mind is blown! That is such a crazy article! I love it! Thank you for the awesome app, sharing the history, and the unbelievable mathematics that ARE music as we know it.

  12. Pingback: 17 Cool Raspberry Pi 2 and Pi Projects 

  13. Zach says:

    Hi trying to figure out you connected the electrical wires to a power source can you explain that for me? I have my Pi connected to my ssr i am just wondering how you connect the power source


    • KnC says:

      Check out these links for wiring…

    • Tarcas says:

      For mine, I ran power into one relay’s terminal, and jumpered from the same terminal to one terminal on the next relay, and from there to the next, and so on. The other terminal of each relay is for your outlet’s hot terminal. The neutral from the power cable does NOT run through the relay at all, but goes to the neutral side of each outlet.
      I hope this helps. If not, please explain what you’re unclear on.

  14. Ryan says:

    This is a great project, but the first two images are not rendering to show the power source coming in to the box (upper right in the last image). Any additional insight is appreciated.

    Thanks for sharing this!

  15. Aaron says:

    This is a great project and I have just gotten started. Unforunately, it looks like a few critical images arent loaded when I go thru the above. Any chance they can be updated? Also, perhaps this is addressed in the missing parts, but I’m not understanding somethings:
    1. Do the outlets all join together ultimately for a plug that goes into the wall, but their power is controlled in each outlet based upon the relaying turning a switch on/off? Or is the power for all the outlets coming thru the 5V connection from the Pi to the board (which cant possibly be enough I would think…granted I’m a total newbie here-so sorry if this is a dumb question)
    2. From the images, it looks like each individual plug is separately controlled by the relay-how do you split up 1 plug, when all the tutorials I’ve seen about outlets show a single black/white line for an outlet (2 plugs). What am I missing here?

    Again, sorry for the kindergarden questions, I’m completely new to this (only got the Pi yesterday and the OS running a few hours ago-but I’m scouring the net and feel like I’ve already hit a wall

    Thanks again

    • KnC says:

      Here is a diagram I scraped from a site awhile back. It only shows 2 channels, so hopefully keeping it simple will make it more understandable, then you can scale up the channels based on the example. 😉

  16. Pingback: Weihnachtsbeleuchtung in kreativ: so (be-)leuchtet der Nerd von heute - Das Conrad Blog

  17. Thanks for sharing this nice article.

  18. Damien says:

    Hey, would you mind giving an estimate of the light bill increase this would have? I’m sure it would take a decent toll and obviously each setup would differ but I’m just looking for a guesstimate really. Thanks for the awesome tutorial!

    • Steve says:

      So – In theory:

      Each channel on the solid state board allows a maximum of 2 Amps.
      AC Current runs at 120 Volts
      This would mean an absolute maximum of 240 Watts per channel – multiplied by 8 channels is 1984 Watts.

      If you run the light show for 5 hours (5hrs x 240w x 8 channels), then you would be consuming 9.6kWh.

      Running at the national average of $0.12, you would spend around $35.00 across a 30 day period (a little over $1 per day).

      • Hoops says:

        Just to add to Steves comment I would like to say that he is presuming maximum load on all channels at all times. Due to diversity the actual load/cost will be a lot less, as the lights are not continuously on, the actual power/cost I would estimate to be 60% less or most likely more than his estimate.

    • Tarcas says:

      It’s really impossible to estimate. If you’d have the lights up anyway, then this will actually LOWER your power bill because it’s turning them off for part of the time that they would otherwise be on.
      On the other hand, if you’re putting up new lights for this, you’re adding to your cost.

      To get a ceiling estimate, use Steve’s math. 2A per channel is the max for an SSR.
      For a more accurate estimate use the Amperage rating for the lights you’re using (most of them say on a tag or the box what they’re rated at) and for the time, multiply by the time they’re actually on each day (if the show is running for 6 hours but the lights are only on for an average of 25% of the time, use 1.5 hours instead of 6 in the formula.)

  19. Jim says:

    Thanks for this project! We now have a Christmas light show setup using lightorgan. However, we noticed one thing. The music seems to be delayed slightly and plays about a quarter second after the lights come on. I know it’s not much, but it is noticeable. Has anyone else noticed that?
    Anyway, I modified the code to add a delay to the lights so now they match the music perfectly.

    • Anonymous says:

      Yeah the delay is annoying. Could you please share the code change you made to correct it? -chivalry

      • Jim says:

        I’m still working on the code – trying to clean up my changes and make the delay configurable. When I have it ready I’ll post the changes.

  20. Hey, I wanted to say thanks. Still a great writeup! I’ve got an oddity in my LED’s on my roof line but here’s my project:


    Next year I’m going to add more strands and channels ( Already got a Pi-B to use ). Now I have to find a Mooning Santa I can use for the Bass notes….

  21. KnC says:

    After posting this on a lightshowpi thread, I thought others here would probably gain more benefit from the process…

    — start of post (Sorry I am lazy, and am just using copy & paste) —

    Checkout lightorgan for the Pi:


    I use an open-source / cross-platform Midi sequencer that accepts input from Midi devices, the mouse, or computer keyboard:


    I then import the Midi into GarageBand (Mac), and add real world instruments, drum kits, or sampled music to the tracks. Then export as MP3.

    Back to Aria Maestosa to add notes to the original midi file to create custom trigger events on the arrangements. (the midi sounds like crud after, but the lights are more to my liking.)

    It’s been a very long, tedious process, that takes some experimenting to get the channels you want to trigger. But I can then play MP3 files, along side the midi files that lightorgan is using to trigger the GPIO / relays. After 3 years, I have created 7 songs of my own, and the rest of the hour long show is LSP, but I find both approaches to the show rewarding, and having their own merit. 😉

    I use a random .playlist with LSP, and about 40 songs to play in between my cronned “top of the hour show” utilizing lightorgan. It works out great!

    — end of post —

  22. Pingback: Deck The Decks 2015 | thelusticlife

  23. Антон says:

    Множество Ваших партнеров и покупателей ждут Вас!

    ПИШИТЕ ТОЛЬКО НА ЭТУ ПОЧТУ: baza-gorodov(собака)yandex.ru

    Любые базы данных фирм 2016 года городов стран: России, Белоруссии, Украины и Казахстана

    Базы данных НЕ ИЗ 2 ГИС! Собираем базы данных из ЯНДЕКСА !!!

    Стоимость баз от 700 рублей за 1 город!

    В базах есть (формат Ексель): страна, регион, населенный пункт, адрес, телефон, ЕМАЙЛЫ, сайт, город,
    (разделы и рубрики для выбора по фильтру), а так же странички или группы соцсетей фирм: ВК, Твиттер, Фейсбук, ОД

    Пишите какие базы городов Вам надо, так же собираем базы по видам деятельности фирм.

    ГАРАНТИЯ СБОРА 2016 ГОДА, а так же быстрота предоставления!

  24. Pingback: A Light Show with RPi | Section9

  25. Pingback: 12 Cool Projects For Your Raspberry Pi – Your Smart IOT

  26. Pingback: 10 coisas legais que você pode fazer com o Raspberry Pi – Marcelo Venceslau

  27. Pingback: Raspberry Pi(ラズベリー・パイ)でここまで出来る!12のクールな使い方 | リードライト(日本版)

  28. Pingback: 10 awesome creations made with a Raspberry Pi | Digital Trends

  29. Pingback: Think the Raspberry Pi is underpowered? Here’s 10 projects that prove you wrong | Artikel Online

  30. Pingback: Think the Raspberry Pi is underpowered? Here’s 10 projects that prove you wrong

  31. Pingback: Think the Raspberry Pi is underpowered? Here’s 10 projects that prove you wrong - Ac Stories

  32. StevieMac says:

    Awesome project, however, I cannot get the SVN to download. Any help is greatly appreciated!!!

  33. Pingback: Things You Can Do With Raspberry Pi

  34. mfetting says:

    Any support for i2c, instead of the GPIO pins?

  35. Hey Everyone!

    Total Newbie to all of this so I am sorry if this is an easy question but I’ve spent a few hours trying to find the answer to no avail (and posting on various forums). Also, apologies in advance if this is an inelegant way of explaining what I want to accomplish:

    My band is going on tour and I want to create a light show using LED strips similar to the second Youtube Link below. We play to a click track so I’d like to write a light show set to tempo in a DAW using midi where each note represents a light.

    I think the easiest way would be to then save these ‘songs’ on a SD card and make a Playlist for our set that I can control with just a simple Play//Stop//Forward//Backward button set up. This project is the closest I’ve seen to what I want, but I’d like to confirm that. Also, since we are playing music, we don’t need any playback of the midi.

    Thank you so so much in advance!

    • KnC says:

      As much as I love this project, I think a better fit for your need would be LightShowPi.org. Go to the Google+ group and search for USB input. You can stream from your sound board, and have LightShowPi create a Color Organ of sorts for your music. If you are looking for a custom light sequence, I don’t think you are going to find DMX type control from a micro-controller (I could be wrong?), but for what it is LightSHowPi is amazing, Light Organ is Incredibly cool, but I sequencing by midi, especially with the algorithms being used takes a lot of trial and error. Budget considering is very rewarding, but it is no replacement for a DMX type control.

      With that said, I have many hours invested in custom songs I sequenced with Light Organ, and use it every year for my Christmas lights, but as a musician, for simple effect, I would probably use LightShowPi with a USB sound card accepting a signal from my sound board if I wanted a quick and dirty light display for my music.

  36. Pingback: Проекты на Raspberry Pi – KERNEL.NET.KG

  37. Pingback: Bluemix Theme

  38. Ton E says:

    This all very exciting! Is there something similar but using Python? To keep my grey cells moving during retirement they tell me it is good to learn a new language. I didn’t fancy doing French so thought of Python especially as my son bought me a raspberry pi! I plan to adapt the code to drive a bank of descant recorders via GPIO and solenoids to play a midi file. Any help gratefully and graciously received!

    Ton E

  39. Anonymous says:

    why doesn’t work

  40. Anonymous says:

    why doesn’t it work

    • KnC says:

      You need to be more specific. We don’t know how to help if you don’t tell us what errors or difficulties you are having.

  41. Haneet Singh says:

    Thanks for sharing. And also check out This Article

  42. Pingback: Agora no Brasil: o que o Raspberry Pi é capaz de fazer?

  43. KtHB says:


  44. KtHB says:

    OAXV’) AND 9822=6034 AND (‘zEJe’=’zEJe

  45. KtHB says:

    OAXV’) AND 9023=9023 AND (‘zxrG’=’zxrG

  46. KtHB says:

    OAXV’) AND 3350=8274 AND (‘dJLN’=’dJLN

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s