Search code examples
htmlnode.jsarduinojohnny-five

Can't control the LED by a single html file and johnny five


I'm newbie for this one. I have found some code to controlling Arduino led by a single html file. They said that we must use the johnny-five and node-js protocol to control it. But I found a problem with this way, I succeed to connect to Arduino and turn on the localhost. But, I just found a couple of button, and it is useless to control the led. I'd try to solve it and nothing happened.

This where my source code The code

<html>
   <head>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
      <script src="/socket.io/socket.io.js"></script>
      <script>
         $(document).ready(function() {
           var socket = io.connect('http://localhost');
           $('#button').click(function(e){
             socket.emit('click');
             e.preventDefault();
           });
         });  
      </script>
   </head>
   <body>
      <button id="button" href="#">LED ON/OFF</button>
   </body>
</html>

And

var app = require('http').createServer(handler),
    io = require('socket.io').listen(app),
    fs = require('fs'),
    five = require('johnny-five');

app.listen(8080);

function handler(req, res) {
    fs.readFile(__dirname + '/index.html',
        function(err, data) {
            if (err) {
                res.writeHead(500);
                return res.end('Error loading index.html');
            }

            res.writeHead(200);
            res.end(data);
        });
}

board = new five.Board();

board.on("ready", function() {
    led = new five.Led(13);

    io.sockets.on('connection', function(socket) {
        socket.on('click', function() {
            led.toggle();
        });
    });
});

Solution

  • You run your server on port '8080' but you connect to socket.io on the default port (80). I believe it may be the problem. Try changing the line in html to:

          var socket = io.connect('http://localhost:8080');
    

    Also if you have any error in your browser console it would be helpful to show this message.