A Brief History of Windows Audio APIs

A few months ago, the audio programming bug bit me pretty hard. I’m not entirely sure why it took so long really. I’ve been recording and mixing music since college. And much of my software development career has been built on a giant mass of C/C++ code. But somehow these worlds never converged. Somehow, with all of the time I’ve spent in front of tools like Cakewalk Sonar and FruityLoops, it never occurred to me that I might be able to learn what these applications are doing under the hood.

Then my nightstand began accumulating books with titles like “The Theory of Sound” and “Who Is Fourier? A Mathematical Adventure”. I absorbed quite a bit of theoretical material in a relatively short amount of time. But as with anything, you must use it to learn it. So I looked to the platform I already use for all of my audio recording – Windows.

What I found was a dark, mysterious corner in the Windows platform. There’s not a lot in the way of introductory material here. As of this writing, I could find no books dedicated to Windows audio programming. Sure, there’s MSDN, but, um, it’s MSDN. I also spent some time digging through back issues of Windows Developer’s Journal, MSDN Magazine, Dr. Dobbs, etc. and the pickings were slim. It seemed the best sources of information were blogs, forums, and StackOverflow. The trick was wading through the information and sorting it all out.

Developers new to Windows audio application development, like me, are often overwhelmed by the assortment of APIs available. I’m not just talking about third party libraries. I’m talking about the APIs baked into Windows itself. This includes weird sounding things like MME, WASAPI, DirectSound, WDM/KS, and XAudio2. There are a lot different paths a developer could take. But which one makes the most sense? What are the differences between them all? And why are there so many options?

I needed a bit more information and context in deciding how I was going to spend my time. And for this, I had to go back to 1991.

1991 – Windows Multimedia Extensions (aka MME, aka WinMM): Ahhh…1991. That was the year both Nirvana’s “Nevermind” and “Silence of the Lambs” entered pop culture. It was also the year of the first Linux kernel and the very first web browser. Most of us didn’t realize it at the time, but a lot of cool stuff was happening.

Most PCs of this vintage had tiny little speakers that were really only good at producing beeps and bloops. Their forte was square waves. They could be coerced into producing more sophisticated sounds using a technique called Pulse Width Modulation, but the quality wasn’t much to get excited about. That “Groove is the Heart” sound file being played through your PC speaker might be recognizable, but it certainly wasn’t going to get anybody on the dance floor.

Sound cards didn’t usually come bundled with name brand PCs, but they were becoming more and more popular all the time. Independently owned computer shops were building and selling homebrew PCs with sound cards from companies like Creative Labs and Adlib. Folks not lucky enough to buy a computer bundled with a sound card could buy an add-on card out of the back of a magazine like PC Computing or Computer Shopper and be up and running in no time.

The 90’s was also the golden age for the demo scene. Programmers pushed the limits of graphics and audio hardware in less bytes than most web pages are today. Amiga MOD files were a big deal too. They even inspired many audio enthusiasts to build their own parallel port DACs for the best audio experience. And then there were the video games. Game publishers like Apogee and Sierra Entertainment were cranking out awesome game titles, most of which could take advantage of Sound Blaster or Adlib cards if they were available.

Professional audio on the PC existed, but it was usually implemented using external hardware solutions, proprietary software, and proprietary communications protocols. Consumer grade sound card manufacturers were adding MIDI support in the form of a dual purpose joystick port that seemed oddly out of place. It was more of a marketing tactic than a useful feature. Most consumers had no idea what MIDI was.

It was at this point when Microsoft decided to add an audio API for Windows. Windows 3.0 had been out for a year and was in widespread use. So Microsoft released a version of Windows 3.0 called Windows 3.0 with Multimedia Extensions (abbreviated MME, sometimes referred to in software development circles as the waveOut API). MME has both a high-level and low-level API. The low-level API supports waveform audio and MIDI input/output. It has function names that start with waveIn, waveOut, midiIn, midiStream, etc. The high-level API, the Media Control Interface (MCI), is REALLY high level. MCI is akin to a scripting language for devices.

MME was the very first standard audio API for Windows. It’s evolved a bit over the years, to be sure. But it’s still around. And it works well, but with some caveats.

Latency is a problem with MME. Dynamic, near-real time audio (e.g., game event sounds, software synthesizers, etc.) is a bit harder to do in a timely fashion. Anything that occurs 10ms later than the brains thinks it should is perceived to be out of sync. So that kind of programming is pretty much out of the question. However, pre-generated content (e.g., music files, ambient sounds, Windows system sounds, etc.) works well with MME. At the time, that was good enough.

MME is still around. Some might even use the word thriving. Historically, support for high quality audio has been a pain point for MME. Parts of the MME API (e.g., anything that deals with the device capability structures WININCAPS and WINOUTCAPS) can only handle a maximum of 96kHz and 16-bit audio. However, in modern versions of Windows, MME is built on top of Core Audio (more on this later). You may find that even though a device can’t report itself as capable of higher quality audio, higher sample rates and bit depths work anyway.

1995 – DirectSound (aka DirectX Audio): When Windows 3.1 came out in 1992, MME was officially baked in. But Windows still left game developers uninspired. All versions of Windows up to this point were effectively shells on top of DOS. It was in the way. It consumed memory and other resources that the games desperately needed. DOS was well known and already a successful platform for games. With DOS, games didn’t have to compete for resources and they could access hardware directly. As a result, most PC games continued to be released as they had been – DOS only.

Along came Windows 95. Besides giving us the infamous “Start” button and the music video for Weezer’s “Buddy Holly”, Windows 95 brought with it DirectX. DirectX was core to Microsoft’s strategy for winning over game developers, whom they saw as important for the success of Windows 95.

DirectX was the umbrella name given to a collection of COM-based multimedia APIs, which included DirectSound. DirectSound distinguished itself from MME by providing things like on the fly sample rate conversion, effects, multi-stream mixing, alternate buffering strategies, and hardware acceleration where available (in modern versions of Windows, this is no longer the case. See the discussion on Core Audio below). Because DirectSound was implemented using VxDs, which were kernel mode drivers, it could work extremely close to the hardware. It provided lower latency and support for higher quality audio than MME.

DirectSound, like the rest of DirectX, wasn’t an instant hit. It took game developers time, and a bit of encouragement on the part of Microsoft, to warm up to it. Game development under DOS, after all, was a well worn path. People knew it. People understood it. There was also a fear that maybe DirectX would be replaced, just as its predecessor WinG (a “high-performance” graphics API) had been. But eventually the gaming industry was won over and DirectX fever took hold.

As it relates to professional audio, DirectSound was a bit of a game changer. There were PC-based DAW solutions before DirectX, to be sure. From a software perspective, most of them were lightweight applications that relied on dedicated hardware to do all of the heavy lifting. And with their hardware, applications did their best at sidestepping Windows’ driver system. DirectSound made it practical to interact with hardware through a simple API. This allowed pro-audio applications to decouple themselves from the hardware they supported. The umbilical cord between professional grade audio software and hardware could be severed.

DirectX also brought pluggable, software based audio effects (DX effects) and instruments (DXi Instruments) to the platform. This is similar in concept to VST technology from Steinberg. Because DX effects and instruments are COM based components, they’re easily discoverable and consumable by any running application. This meant effects and software synthesizers could be developed and marketed independently of recording applications. Thanks to VST and DX effects, a whole new market was born that continues to thrive today.

Low latency, multi-stream mixing, high resolution audio, pluggable effects and instruments – all of these were huge wins for DirectSound.

1998 – Windows Driver Model / Kernel Streaming (aka WDM/KS): After the dust settled with Windows 95, Microsoft began looking at their driver model. Windows NT had been around for a few years. And despite providing support for the same Win32 API as it’s 16-bit/32-bit hybrid siblings, Windows NT had a very different driver model. This meant if a hardware vendor wanted to support both Windows NT and Windows 95, they needed to write two completely independent drivers – drivers for NT built using the the Windows NT Driver Model and VxDs for everything else.

Microsoft decided to fix this problem and the Windows Driver Model (WDM) was born. WDM is effectively an enhanced version of the Windows NT Driver Model, which was a bit more sophisticated than the VxDs used by Windows 95 and 3.x. One of the big goals for WDM, however, was binary and source code compatibility across all future versions of Windows. A single driver to rule them all. And this happened. Sort of.

Windows 98 was the first official release of Windows to support WDM, in addition to VxDs. Windows 2000, a derivative of Windows NT followed two years later and only supported WDM drivers. Windows ME, the butt of jokes for years to come, arrived not long after. But ME was the nail in the coffin for the Windows 9.x product line. The technology had grown stale. So the dream of supporting a driver model across both the NT and the 9.x line was short lived. All versions of Windows since have effectively been iterations of Windows NT technology. And WDM has since been the lone driver model for Windows.

So what’s this WDM business got to do with audio APIs? Before WDM came about, Windows developers were using either DirectSound or MME. MME developers were used to dealing with latency issues. But DirectSound developers were used to working a bit closer to the metal. With WDM, both MME and DirectSound audio now passed through something call the Kernel Audio Mixer (usually referred to as the KMixer). KMixer was a kernel mode component responsible for mixing all of the system audio together. KMixer introduced latency. A lot of it. 30 milliseconds, in fact. And sometimes more. That may not seem like a lot, but for a certain class of applications this was a non-starter.

Pro-Audio applications, such as those used for live performances and multitrack recording, were loathe to embrace KMixer. Many developers of these types of applications saw KMixer as justification for using non-Microsoft APIs such as ASIO and GSIF, which avoided the Windows driver system entirely (assuming the hardware vendors provided the necessary drivers).

Cakewalk, a Boston-based company famous for their DAW software, started a trend that others quickly adopted. In their Sonar product line starting with version 2.2, they began supporting a technique called WDM/KS. The WDM part you know. The KS stands for Kernel Streaming.

Kernel streaming isn’t an official audio API, per se. It’s something a WDM audio driver supports as part of its infrastructure. The WDM/KS technique involves talking directly to the hardware’s streaming driver, bypassing KMixer entirely. By doing so, an application could avoid paying the KMixer performance tax, reduce the load on the CPU, and have direct control over the data delivered to the audio hardware. Latency wasn’t eliminated. Audio hardware introduces its own latency, after all. But the performance gains could be considerable. And with no platform components manipulating the audio data before it reached the hardware, applications could exert finer control over the integrity of the audio as well.

The audio software community pounced on this little trick and soon it seemed like everybody was supporting WDM/KS.

It’s worth noting at this point in the story that, in special circumstances, DirectSound could actually bypass KMixer. If hardware mixing was supported by both the audio hardware and the application, DirectSound buffers could be dealt with directly by the audio hardware. It wasn’t a guaranteed thing, though. And I only mention it here in fairness to DirectSound.

2007 – Windows Core Audio: It was almost 10 years before anything significant happened with the Windows audio infrastructure. Windows itself entered an unusually long lull period. XP came out in 2001. Windows Vista development, which had begun development 5 months before XP had even been released, was fraught with missteps and even a development “reboot”. When Vista finally hit the store shelves in 2007, both users and developers were inundated with a number of fundamentals changes in the way things worked. We were introduced to things like UAC, Aero, BitLocker, ReadyBoost, etc. The end user experience of Vista wasn’t spectacular. Today, most people consider it a flop. Some even compare it to Windows ME. But for all of its warts, Vista introduced us to a bevvy of new technologies that we still use today. Of interest for this discussion is Windows Core Audio.

Windows Core Audio, not to be confused with OSX’s similarly named Core Audio, was a complete redesign in the way audio is handled on Windows. KMixer was killed and buried. Most of the audio components were moved from kernel land to user land, which had an impact on application stability. (Since WDM was accessed via kernel mode operations, WDM/KS applications could easily BSOD the system if not written well). All of the legacy audio APIs we knew and loved were shuffled around and suddenly found themselves built on top of this new user mode API. This included DirectSound, which at this point lost support for hardware accelerated audio entirely. Sad news for DirectSound applications, but sadder news was to come (more on this in a bit).

Core Audio is actually 4 APIs in one – MMDevice, WASAPI, DeviceTopology, and EndpointVolume. MMDevice is the device discovery API. The API for interacting with all of the software components that exist in the audio path is the DeviceTopology API. For interacting with volume control on the device itself, there’s the EndpointVolume API. And then there’s the audio session API – WASAPI. WASAPI is the workhorse API. It’s where all of the action happens. It’s where the sausage, er, sound gets made.

Along with new APIs came a number of new concepts, such as audio sessions and device roles. Core Audio is much better suited to the modern era of computing. Today we live in an ecosystem of devices. Users no longer have a single audio adapter and a set of speakers. We have headphones, speakers, bluetooth headsets, USB audio adapters, webcams, HDMI connected devices, WiFi connected devices, etc. Core Audio makes it easy for applications to work with all of these things based on use-case.

Another significant improvement Core Audio brings us is the ability to operate in either shared mode or exclusive mode.

Shared mode has some parallels with the old KMixer model. With shared mode, applications write to a buffer that’s handed off to the system’s audio engine. The audio engine is responsible for mixing all applications’ audio together and sending the mix to the audio driver. As with KMixer, this introduces latency.

Exclusive mode is Microsoft’s answer to the pro-audio world. Exclusive mode has much of the same advantages of WDM/KS. Applications have exclusive access to hardware and audio data travels directly from the application to the driver to the hardware. You also have more flexibility in audio formats with exclusive mode as compared to shared mode. The audio data format can be whatever the hardware supports – even non-PCM data.

At this point, you might assume WDM/KS can go away. Well, it can’t. As I said before, it’s not really an API. It’s part of the WDM driver infrastructure, so it will continue to exist so long as WDM exists. However, there’s no compelling reason to use WDM/KS for modern audio applications. An exclusive mode audio session in Core Audio is safer and just as performant. Plus it has the advantage of being a real audio API.

As of this writing, Windows 10 is the latest version of Windows and Core Audio still serves as the foundation for platform audio.

2008 – XAudio2: Over the years, DirectX continued to evolve. The Xbox, which was built on DirectX technologies, was a significant source of influence in the direction DirectX took. The “X” in Xbox comes from DirectX, after all. When DirectX 10 came out in 2007, it was evident that Microsoft had gone into their latest phase of DirectX development with guns blazing. Many APIs were deprecated. New APIs appeared that started with the letter “X”, such as XInput and XACT3.

XAudio2 appeared in the DirectX March 2008 SDK and was declared the official successor to DirectSound. It was built from the ground-up, completely independent of DirectSound. Its origins are in the original XAudio API which was part of XNA, Microsoft’s managed gaming framework. And while XAudio was considered an Xbox API, XAudio2 was targeted at multiple platforms, including the desktop. DirectSound was given “deprecated” status (this is the sadder news I mentioned earlier).

XAudio2 offers a number of features missing from DirectSound, including support for compressed formats like xWMA and ADPCM, as well as built-in, sophisticated DSP effects. It’s also considered a “cross-platform” API, which really just means it’s supported on the Xbox 360, Windows, and Windows Phone.

It’s worth mentioning that while XAudio2 is considered a low-level API, it’s still built on other technology. For the desktop, XAudio2 sits on top of Core Audio like everything else.

You might read all of this business about XAudio2 and assume that DirectSound is dead. We’re quite a way off from that, I think. There’s still a lot of DirectSound based software out there. Given Microsoft’s commitment to backwards compatibility, some level of DirectSound support/emulation is liable to exist in perpetuity. However, unless you’re determined to support versions of Windows that even Microsoft has stopped supporting, there’s no compelling reason to support DirectSound in modern audio applications.

Honorable Mention – ASIO: There are plenty of third party audio APIs available for Windows that weren’t invented by Microsoft. Some of them, like GSIF used by TASCAM’s (formerly Nemesys) GigaStudio, are tied to specific hardware. Some of them, like PortAudio and JUCE (more than just an audio API), are open-source wrappers around platform specific APIs. Some of them like OpenAL are just specifications that have yet to gain widespread adoption. But none has had quite the impact on the audio industry as ASIO.

Steinberg, the same forward-thinking company that gave us VSTs and Cubase, introduced us to ASIO all the way back in 1997. ASIO was originally a pro-audio grade driver specification for Windows. Its popularity, however, has allowed it to gain some level of support on Linux and OSX platforms. Its primary goal was, and still is, to give applications a high quality, low latency data path direct from application to the sound hardware.

Of course, the power of ASIO relies on hardware manufacturers providing ASIO drivers with their hardware. For applications that can support ASIO, all of the business of dealing with the Windows audio stack can be completely avoided. Conceptually, ASIO provides applications with direct, unfettered access to the audio hardware. Before Windows Vista, this could allow for some potentially significant performance gains. In the Core Audio world, this is less of a selling point.

The real-world performance of ASIO really depends on the quality of driver provided by the manufacturer. Sometimes an ASIO driver might outperform its WDM counterpart. Sometimes it’s the other way around. For that reason, many pro-audio applications have traditionally allowed the user to select their audio driver of choice. This, of course, makes life complicated for end-users because they have to experiment a bit to learn what works best for them. But such is life.

The waters get muddied even further with the so-called “universal” ASIO drivers, like ASIO4ALL and ASIO2KS. These types of drivers are targeted at low cost, consumer-oriented hardware that lack ASIO support out-of-the-box. By installing a universal ASIO driver, ASIO-aware applications can leverage this hardware. In practice, this type of driver merely wraps WDM/KS or WASAPI and only works as well as the underlying driver it’s built on. It’s a nice idea, but it’s really contrary to the spirit of the ASIO driver. Universal drivers are handy, though, if the audio application you’re trying to use only supports ASIO and you’ve got a cheap sound card lacking ASIO support.

ASIO, like MME is an old protocol. But it’s very much still alive and evolving. Most pro-audio application professionals hold it in high regard and still consider it the driver of choice when interfacing with audio hardware.

Conclusion: “Shane, where’s the code?” I know, I know. How do you talk about APIs without looking at code? I intentionally avoided it here in the interest of saving space. And, yet, this article still somehow ended up being long winded. In any case, I encourage you to go out on the Interwebs and look at as much Windows audio source code as you can find. Browse the JUCE and Audacity source repos, look at PortAudio, and peruse the sample code that Microsoft makes available on MSDN. It pays to see what everybody else is doing.

For new developers, the choice of audio API may or may not be clear. It’s tempting to make the following generalization: games should go with XAudio2, pro-audio should go with ASIO and/or Core Audio, and everybody else should probably go with MME. Truth is, there are no rules. The needs of every application are different. Each developer should weigh their options against effort, time, and money. And as we see more often than not, sometimes the solution isn’t a single solution at all.

(Shameless Plug: If you’re interested in learning how to use Core Audio, consider purchasing an early draft of “Appendix B: Introduction to Windows Core Audio” from the book I’m currently working on entitled, “Practical Digital Audio for C++ Programmers.”)

Back from CppCon 2015

Now that the dust has settled a bit and I’ve adjusted to being back on east coast time, I thought it’d be worth talking a little bit about CppCon 2015. CppCon, for those who haven’t heard about it, is a five day conference devoted to C++ (seven if you pay for an extra class). It’s a relatively new kid on the block, this year being only the second year. It’s certainly not the only C++ conference in town. But CppCon distinguishes itself from all the others in terms of scale. Attendance to C++Now, for example, is capped at around 150 people and features three tracks at any given time. C++ and Beyond describes itself as “small” and features only one track at a time over three days. This year, CppCon saw nearly 700 people in attendance. That’s a nearly 15% growth over last year’s 600 attendee count. The days start early and end late. And at any given point, there could be up to six separate tracks going on. Presenters include folks from Google, Microsoft, Boost, Adobe, etc. As you can imagine, there’s enough content at CppCon to satiate even the thirstiest of minds.

Just like last year, CppCon was held at the Meydenbauer Center in beautiful Bellevue, Washington, a Seattle “suburb” (I use that word loosely. See Wikipedia.) that just so happens to be in Microsoft’s backyard. The conference center itself has four levels. The bottom two floors have amphitheatre-sized conference rooms that are used for keynotes and larger talks. The top floor has a number of smaller classroom sized conference rooms and is where most of the action actually takes place.

Most of the rock stars showed up again this year – Bjarne Stroustrup, Herb Sutter, Andrei Alexandrescu, John Lakos, etc. (Scott Meyers was noticeably MIA this year). Bjarne’s keynote, “Writing Good C++14”, set the tone for everything that was to come. The theme seemed to be “move forward” – abandon your old compilers, modernize your legacy codebase, and leave the past in the past. This was reflected by the significant number of talks that revolved around C++17 proposals and technical previews that will be appearing in a compiler near you.



Me with Bjarne Stroustrup

Like any conference, the quality of presentations was a mixed bag. There were great speakers and some not so great. Some presentations were practical, some were meta, and some were sales pitches for third party libraries. All tech conferences are like this to some degree. For conferences with only one or two tracks, this can be a mild annoyance. But the fact that there was so much happening at the same time allowed attendees to be a bit more discerning.

What about schwag? Schwag is something we all pretend to not care about. After all, we’re only there for the knowledge right? Mmhmm. 🙂 There actually wasn’t much schwag to speak of. This year, attendees received a plastic bag containing some flyers, a deck of “Woman in Tech” playing cards, and a thumb drive containing an offline version of cppreference.com. There were no free shirts, despite being asked to provide shirt size at registration time. At one point, JetBrains started giving away yo-yos, CLion stickers, and copies of a mini-book entitled “C++ Today: The Beast is Back”, which happened to serve as the basis for Jon Kalb’s highly entertaining presentation of the same name.That was about it. Not even the meals were free, which seemed to surprise a lot of folks.

Apart from that, there weren’t many disappointments at CppCon. This conference has a lot to offer. The talks were great. All of the presenters were approachable and very personable. The atmosphere was positive. And, most importantly, it was FUN. Would I go back again?
Definitely. Should you go? Absolutely.

Project: Bed Lights

A few months ago, my wife and I were in the market for a new mattress. We popped into a local mattress store and spent the better part of the afternoon stretching out on almost everything they had. Before we left, we tried a really nice, we’ll-probably-never-afford kind of bed. It had controls for firmness and head and foot elevation. There were temperature and massage controls. Memory foam. There were even ground lights. That’s right. Ground lights! What a brilliant idea?!

We left the store empty handed. But the thought of those ground lights stuck with me. How fantastic it would be to have such a thing for a midnight pee run. Something bright enough to help you find your way, but dim enough as to not wake the blanket-stealing snore-machine sleeping next to you (To My Wife: Baby, your snores are like lullabies. Truly.). Of all of the things that fancy bed had, it was the ground lights I wanted the most.

So I decided to make my own, but with a couple of enhancements. I definitely wanted motion activated lights. Who wants to bother feeling around for a on/off button at 3 AM? I also wanted an adjustable brightness control. It’s hard to gauge how bright is too bright until you actually start to use it. I knew it would need to be tuned.

This blog describes my little bed-lights project. I’ll detail everything you need to know to build your own. Note that if you attempt this project, some of your parts will probably vary. As a result, you’ll need to adjust values of other components accordingly. I’ll try to help you out where I can.

[Disclaimer: If you choose to tackle this project, I take no responsibility for any bad things that might happen. If you wire something up wrong or take a shortcut that results in a fire, that’s not my fault. As the folks keen on legalese say, this blog is for informational purposes only.]

Parts List

Here is the parts list for the project

Component Qty Approx. Price
½” 10’ PVC Pipe (Home Depot or Lowes) 2 $5
½” PVC End Caps (Home Depot or Lowes) 4 $1.50
LED Holders, 5mm 12 $1.50
2.1mm Female DC Power Barrel Connectors, Panel Mount 5 $15.00
2.1mm Male DC Power Connectors 4 $6.50
20 AWG wire 1 Spool, 100ft. $10.00
20 AWG 25′ Hook-Up Wire(For convenience in building power cables. Not entirely necessary. You could just use wire from the previous item. You’ll definitely have plenty of leftover if you buy 100′. ) 1 $4.30
Rustoleum Flat, Black Spray Paint 1 $6.00
Heat Shrink Tubing 1 Pack (Won’t Use It All) $7.00
9V 2.1mm wall wart, at least 500mA 1 $11.00
500mA Fuse 1 $2.20
Fuse Holder 1 $1.00
White LEDs, 5mm 3Vf (Mine came from EBay in a 300pcs assortment pack) 12 $0.25
330 Ohm Resistors 14 $1.40
2.2k Ohm Resistors (Specific to the current needs of my light rails – see notes below on how you might need a different value) 2 $0.20
2N3904 Transistors (NPN) 2 $0.50
1N4001 Diodes 2 $0.50
1 M Ohm Potentiometer 1 $5.00
Adafruit PIR Sensor 2 $20.00
Perfboard 1 $3.00
Enclosure for Controller 1 $6.00
Enclosures for PIRs and lids 2 $3.50
Velcro Straps 1 Pack $4
Velcro Tape 1 Pack $5

Total Project Cost: ~$120.00

Granted, this is just an estimate. All of the passive components I had laying around. You might find much of what you need by poaching old busted electronics.

Overview

There are 3 basic components to the bed lights. The first, and most obvious one, is the pair of light rails – one for either side of the bed. The second component is the motion sensor (PIR). There are two of these as well. The third component is the controller box. This is where power gets distributed, motion sensor input is handled, and lights get switched on. It’s also where the control knob for the brightness control lives. The basic configuration is like so.

Something that’s not obvious from the sketch is that each PIR controls both light rails. If one of the PIRs is triggered, both rails light up. And if both PIRs are triggered at the same time, both rails still light up.

Building the Light Rails

The first step to building the light rails is cutting the PVC pipe down to size. The ½” pipe that I bought came in 10 ft. lengths. That’s way too long for my bed. So, using a hacksaw, I cut both pieces down to 7ft.

Next, I drilled 6 evenly spaced holes for the LED holders in each pipe. The trick here is to initially start with a small drill bit and then work up to larger ones, testing the LED holders as you go. It was important that the LED holder was able to pop in, feel somewhat snug, and then pop out easily again.

For each pipe, I planned to cap both ends. But in the cap for one end, I drilled a center hole large enough to accommodate one of the female 2.1mm barrel connectors. This is where power will be supplied to the rail. Actually mounting the connectors and attaching the end caps should happen last, after the rail is wired up and ready to report for duty.

At this point, I painted both the pipes and the end caps by applying a couple of coats of flat black Rustoleum spray paint.

Next up – the wiring.

Each LED on the rail has an associated 330 ohm resistor and each LED/resistor combination is wired in parallel. If one LED dies, the rest will continue to light up. As shown in the photo below, I merely soldered a resistor to one of the legs of the LED and then connected wire as appropriate (Note: The PVC in the photo below is unpainted. This photo was taken as I was still experimenting.) I then tidied things up with heat shrink tubing.

I should point out that it’s much easier to snake the wire through the pipe a segment at a time between holes and wire up the LEDs in-place, than it is to try to wire up everything outside of the PVC pipe and then to try to snake the whole thing through the PVC in one fell swoop. I learned this quickly. Trying to assemble everything outside of the PVC pipe just leads to headaches as you try to fish the LEDs/resistors out through the holes. It’s time consuming and not worth it.

It’s important to make sure the LEDs are wired up properly. They have polarity. And because we’re wiring things up in parallel, 5 of the 6 LED combinations will be connected to 4 wires. If you’re having trouble visualizing this, here’s a diagram to help you out. 5 of the 6 LED/resistor pairs have an incoming positive connection as well as an outgoing positive connection. The same is true of the negative connections. Only the last LED/resistor pair has single connections for the positive and negative terminals.

After the LEDs were wired up, I tested each rail with a nine volt battery to ensure everything lit up. I then popped the LEDs in their holders, put a dab of superglue on each holder, and pushed everything down in their holes. Some LED/resistors didn’t appreciate being pushed down into tight quarters, so I tested the LEDs again as I went along to ensure I didn’t break something or short a connection.

Next up, the DC power connectors. I soldered the leads appropriately to the power connectors, being careful to get the polarity right. A multimeter is handy for that. If you’re uncertain what’s negative and what’s positive, plug in your power supply directly to the jack and find out. If you don’t have a multimeter (God, help you), you can always test using another LED resistor pair separate from your light rails. If everything is connected up properly, the LED should light right up. If it’s backwards, the LED will go up in smoke or won’t light at all.

With the jacks wired up, I mounted them into the PVC end caps and superglued all caps to the pipes. The light rails were finished.

Building the Controller

As mentioned before, the controller serves three purposes – 1) Distribute power to all the other components. 2) Switch on the lights when the motion sensors are triggered. And 3) provide a mechanism that allows me to adjust the brightness of the light rails. All three of these goals are accomplished in the following circuit


Click to Enlarge

How It Works

Power is distributed to the light rails and PIRs after passing through the 500mA fuse. The fuse is there just in case we get a short anywhere. It would probably be better to go with a fuse closer to the current rating of the actual circuit. 500mA is what I had on hand.

The negative sides of the light rails are connected to the collector of an NPN transistor. In my configuration, the transistor works like a switch. When the appropriate voltage is applied to the transistor’s base, current will be allowed to flow from the collector, through the emitter, and on to ground. This will allow the light rails to light up.

I should note that transistors could have been replaced with simple relays. If you prefer to go that route, you won’t need the resistors attached the the transistors’ bases. However, relays are clicky. And this is a bed/sleep related application. The sound of relays might be a little annoying in the middle of the night.

Determining the resistor values for the transistors’ bases depends entirely on the power needs of your light rails. On paper, each rail draws 109mA each at 9V. The magic formula for determining the base resistor value is:

R = switching_voltage * Hfe / (1.3 * load_current)

The switching voltage is the signal voltage from the PIRs (3.3v). I’ll have more to say about the PIRs shortly. I have to confess, the Hfe of a transistor is somewhat of a magic number to me. Technically, it’s the ratio of the load current to the base current. Given I didn’t know my base current, I wasn’t quite sure how to calculate this. Most folks on the Interwebs claim that 100 is a good number to use for the 2N3904. So that’s what I went with. Plugging the numbers into the formula gives us:

R = 3.3V * 100 / (1.3 * 0.109A)
R = Approx. 2329 Ohms

I didn’t have such a resistor in my Box-O-Electronic-Thingamabobs, so I went with a combination of a 2.2k Ohm and a 330 Ohm to get me close. Better to be over than under (I think).

The diodes in the circuit are used to protect the signal pins of the PIRs. These may not actually be needed. I’m not entirely sure. Without them, I worried that if one PIR goes high and the other is low, a voltage would be placed across the signal pin of the low PIR and damage it. Would this actually happen? No clue. But I decided to play it safe and add diodes to the mix. The diodes allow current to flow in only one direction – out through the transistor.

The 1M Ohm potentiometer is used to limit the current that can pass through the transistor’s base. This component allows the transistor to work like an amplifier as well as a switch. By decreasing the amount of current through the transistor’s base pin, we decrease the amount of current that can flow in from the light rails and out through the emitter. Turning the potentiometer clockwise increases the resistance on the transistor’s base. Increasing resistance lowers the current. And, voila, we have an adjustable dimmer.

Assembling the Controller

With regards to the circuit, I can’t really give much advice. Just follow the circuit shown above and arrange the components in a way that works for you. I used a perfboard without any traces. I connected components using a combination of jumper wires and solder bridges. None of the power connectors, nor the potentiometer were mounted directly to the perfboard. If I had a perfboard that was perfectly fitted for my enclosure I might have gone that route, but I didn’t. So those components were connected using wire.

As for the enclosure, I strongly recommend planning out the component positioning before going anywhere near it with a drill. It’s EXTREMELY frustrating to drill a bunch of holes only to discover that there’s not enough space inside the enclosure to fit everything safely. Space on the inside fills up quickly.

A fellow by the name of John Cooper has an excellent YouTube tutorial on using Sketchup to layout enclosures for guitar effects pedals. I do something similar for my enclosures using 3DS Max. I encourage you to check out John’s video, learn something new, and apply this practice to all of your enclosures. It’ll save you a world of pain.

I discuss the PIR sensors below. But I should mention here that I didn’t have any compatible connectors on hand that I could mount onto the enclosure. The PIRs require three pins – power, ground, and signal. All of my connectors are of the two wire variety. So I just drilled a couple of holes in the side of the enclosure for the PIR cables and soldered them directly onto the perfboard. As a result, the PIR cables are the only cables that aren’t detachable from the controller enclosure. I may fix this at a later time. Or I may not. It’s not that big of a deal.

Motion Sensors (PIRs)

The motion sensors I selected for this project are $10 PIR sensors from Adafruit. PIR sensors detect changes in infrared light. You can find them at just about any electronics outlet. The Adafruit version is interesting in that it has 2 adjustment pots – one for sensitivity and one for a time delay. Adafruit’s website recommends these things be powered at 5v, but claims that 9v is an acceptable upper limit. Since I’m running everything else off of 9v, that wins by default. There’s always a risk I’ll burn these things out quicker. Time will tell, I guess. If you’re following along with my project and you’d rather go with the suggested 5v, just create a voltage divider out of 2 resistors.

The sensitivity adjustment seems to correlate to range. The most sensitive setting comes in at around 20 ft.

The time delay adjustment affects how long the signal will remain high after the PIR has stopped detecting motion. I’ve adjusted both of mine to be around 15 seconds. By using two sensors (one for either side of the bed), this gives a person plenty of time to get from one side of the bed to the other and out of the room before the light rails shut off.

The Adafruit PIRs come with a 1ft long 3-wire 26 AWG cable attached to a 2510 Molex connector. 1 ft. is obviously not long enough, so I fashioned extension cables out of leftover wiring from the light rails and some heat shrink tubing. If you want to get fancy, find yourself some more 2510 Molex connectors for your controller enclosure so you can have detachable PIR cables. I didn’t have any available. As I said before, I just soldered the cables directly to the controller board. Not pretty, but it works.

The enclosures I used for the PIRs weren’t ideal, but they were the best I could find. Here’s a picture of what they look like.

With a stepper drill bit, I drilled holes in the front of the enclosure large enough to accommodate the PIR sensor. A used a dremel to carve out a hole in the back just big enough for the Molex connector. Once everything was connected, I taped the thing shut.

Light Rail Cables

The last thing you’ll need to construct is a set of power cables for the light rails. You might be able to find some long 2.1mm male/male cables online if you’d rather not fuss this step. But creating power cables for the light rails is probably the easiest part of the entire project.

For a single cable, all you need are 2 2.1mm male DC connectors and some 20 AWG wire. The connectors unscrew to reveal terminals for soldering. Make sure you wire one end of the cable up the same way as you do the other end (negative to negative, positive to positive).

Installation

Attaching the setup to the bed involved lots and lots of velcro. Both the controller and the light rails were attached with velcro straps. The motion sensors were attached to the footboards using velcro tape.

The light rails were angled such that the light pointed down and away from the bed. The PIRs were mounted near the headboard, but angled so they pointed towards the footboard and slightly out. Hopefully that shows in the photos below.

Conclusion

All in all, this is a pretty simple project. And a lot of fun. We’ve been using these bed lights for well over a week now. I think I can say this project has been a tremendous success. The brightness level took a little tuning. It’s amazing how bright light can seem once your eyes adjust to darkness. It took three nights of dimming the LEDs before I found a brightness level that didn’t wake one of us up. But I found it. No more feeling around for the cell phone to light my way to the bathroom in the “wee” hours (cue rimshot).

Something I hadn’t anticipated, but worth mentioning, is the psychological effect of having the lights switch on in the middle of the night when they shouldn’t have. Ghosts? Mice? Dust bunnies on the move? It stirs up anxiety, which doesn’t bode well for the sleep-deprived mind. Just be aware that if you’re sensitive to such things, you’ll probably need to adjust the sensitivity of the PIRs (glad we only taped those shut :-)).

Some specs you might find interesting. When idle (the light rails off), I measured the current draw at around .1mA. That’s barely anything. With the lights on at full brightness, the current draw is around 130mA. That’s almost half of my original full-on value for both rails. I’m sure there was a fudge factor in my transistor base calculation. The lights could have been a bit brighter. But that’s fine. Even at max power now, the light rails are too bright to be practical.