Sunday, March 3, 2013

Arduino Project - Screen's Brightness Determines Sound (or: JavaScript powered Light Theremin)

I just finished my first Arduino project. Its individual components are very basic, but I love the combination of them.

Check this out:

The Arduino code is fairly simple, it takes the light sensor's value (a value between 0 and 1024 (well, in fact it's a smaller range, because the screen's black is somewhere around 900, and white is about 200)) and maps it to various tones (again a value between 0 and 1024) that I send to the Piezo speaker.

What you can see on the screen is a simple HTML page, whose background is changed for each tone. Here's a sketch of how it works:


var c4 = 0, cs4 = 1, d4 = 2, ds4 = 3, e4 = 4, f4 = 5 ... as5 = 22, b5 = 23;

var melody = [  
  e5, ds5, e5, ds5, e5, b4, d5, c5, a4,a4,a4,
  c4, e4, a4, b4,b4,b4, e4, a4, b4, c5,c5,c5, ...];

function playSong() {
  var intervals = 24; // supports 2 octaves
  for(var i = 0; i < melody.length; i++) {
    var note = melody[i];
    var lumin = 100 - 100/intervals*note;

    // http://stackoverflow.com/a/6425113
    setTimeout( (function(lumin) { return function() { changeBackground(lumin); } })(lumin), i*250);
  }
}


function changeBackground(lum) {
  document.body.style.backgroundColor="hsl(0,0%,"+lum+"%)";
}


Edit 2013-03-09:
I put the source code on GitHub - https://github.com/bodnerdan/js-arduino-theremin  

Looking forward to get some feedback, or even pull requests.
As you can guess, it didn't take me very long to implement this code, but I'd rather see it as a seed for inspiration for better, bigger projects. Let me know if you have used my code as a basis to create something more sophisticated.

Thanks for reading!