Skip to content

Instantly share code, notes, and snippets.

@dan-mckay
Created April 16, 2013 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dan-mckay/5394605 to your computer and use it in GitHub Desktop.
Save dan-mckay/5394605 to your computer and use it in GitHub Desktop.
This is a Node.js server script using johnny-five and socket.io that updates a web page with values taken from an Arduino with a LDR and potentiometer connected.
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
five = require('johnny-five'),
board,
photoresistor;
app.listen(8000);
// function for serving the static HTML page
function handler(request, response) {
fs.readFile(__dirname + '/index.html',
function (error, data) {
if(error) {
response.writeHead(500);
return response.end('Error loading index.html');
}
// If all is well, serve up the file
response.writeHead(200);
response.end(data);
}
);
}
board = new five.Board();
board.on('ready', function() {
// Create a new photoresistor instance on pin A0
photoresistor = new five.Sensor({
pin: "A0",
freq: 250
});
// Create a new `potentiometer` hardware instance.
potentiometer = new five.Sensor({
pin: "A5",
freq: 250
});
// "read" get the current reading from the potentiometer
potentiometer.scale([0, 10]).on('read', function(error, potVal) {
board.emit('potVal', Math.floor(this.scaled) );
});
// Get the reading from photoresistor (scaled between 0 and 255)
photoresistor.scale([0, 255]).on('read', function(error, photoVal) {
board.emit('photoVal', Math.floor(this.scaled));
//console.log("value from johnny-five" + value);
});
});
// Broadcast reading to web page using socket.io
io.sockets.on('connection', function(socket) {
board.on('photoVal', function(val) {
socket.emit('value', { val: val });
});
board.on('potVal', function(value) {
socket.emit('reading', { value: value });
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment