Skip to content

Instantly share code, notes, and snippets.

@BenConstable
Created December 30, 2013 13:40
Show Gist options
  • Save BenConstable/8182200 to your computer and use it in GitHub Desktop.
Save BenConstable/8182200 to your computer and use it in GitHub Desktop.
Control Aruduino over WebSocket.
var express = require('express')
, app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server)
, five = require('johnny-five')
, board = new five.Board({ port:'/dev/tty.usbmodemfa131'} )
, led;
// Listen for lights change
io.sockets.on('connection', function (socket) {
socket.on('lights', function (data) {
led[data.state]();
});
});
// Start server when board is ready
board.on('ready', function () {
led = new five.Led(13)
this.repl.inject({
led: led
});
server.listen(3000);
});
<!DOCTYPE html>
<html>
<head>
<title>Arduino Over Sockets</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<button id="lights"></button>
<script>
(function () {
var socket = io.connect('http://localhost:3000/')
, lights = false
, controls = document.getElementById('lights');
controls.onclick = function () {
lights = !lights;
socket.emit('lights', {
message: controls.innerHTML
, state: lights ? 'on' : 'off'
});
updateControls();
};
var updateControls = function () {
controls.innerHTML = 'Lights ' + (!lights ? 'on' : 'off');
};
updateControls();
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment