Nazanin De's Blog

Projects, Ideas and thoughts

Javascript Robotics - Controlling LEDs with

If you have you Javascript you can use your knowledge and build some robots. Isn't it so cool?!

Now you might ask how and I am gonna let you know.

There are several Javascript programming frameworks out there which you can easily leverage to code your machine for these I have used Johnny-Five.

What you need:

  • Arduino Uno
  • LEDs
  • Install and Johnny-Five

The code gets divided into two parts:

  • Browser side
  • Johnny-Five code side

The browser will emit some events through to your board and then your board should catch those events and handle them.

Imagine you click on a color square in your browser. The click handler on your color picker will emit the 'changeColor' event and then your board which has already registered a 'changeColor' handler will capture and handle the event.

Let's dive deep into the code now.

Browser side

Let's put a simple color picker in our HTML. It can be a button, div with background or anything else you would prefer. I have used a jQuery color picker plugin while I was experimenting with this. But as an example we will go with a button.

<button type="button" class="btn btn-red">Red</button>  
<button type="button" class="btn btn-green">Green</button>  

Now we need to register some onClick events for these buttons:

$('.btn-red').click(function() {
  socket.emit('changeEyeColor', '#ff0000');

$('.btn-green').click(function() {
  socket.emit('changeEyeColor', '#00ff00');

Johnny-Five side

First we need to import and configure the port it is listening on.

Then when the board is ready and socket is connected we write a handler for 'chaneEyeColor" event and in that we change the LED color to the color passed through the socket.

var five = require('johnny-five'),  
    io   = require('').listen(8081),

five.Board().on("ready", function(){  
   //Initializing RGB LED
   eye = new five.Led.RGB([9, 10, 11]);

   io.sockets.on("connection", function(socket) {
       socket.on("changeEyeColor", function(color){
            console.log("Changing right eye color: " + color);


You can do so many cool things with Johnny-Five and combination. What I have done during my experimentation was to change the eye color based on the robot distance from any barrier and display the status on the browser.
You can use Ultrasonic sensor to detect the distance. Here is a piece of code used to change the eyes color based on distance:

   sensor.on("data", function() {
            if( < 10) {
                console.log('Very near!')
            } else if(10 <= && <= 20) {
            }else if(20 < && <= 30) {
            }else if( > 30){
        }); and Johnny-Five make a great combination if you would like to control your machine/robot through the browser.

You can find the source code on my github