Fun with Raspberry PI, Node.js and websockets
Posted 2014-10-01 by cornbeast
I recently did a cool proof of concept; a raspberry PI running Nodje.js with a PIR sensor that emits messages if there is movement, and a Node.js webserver that serves a webpage that connects via websockets and displays the current movement status.
Node.js server code
var http = require("http");
var express = require("express");
var app = express();
var port = process.env.port || 3700;
var io = require('socket.io').listen(app.listen(port));
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/client.html')
});
io.sockets.on('connection', function (socket) {
socket.on('pirstatus', function (data) {
io.sockets.emit('pirstatus', data);
});
});
console.log("Listening on port " + port);
Web browser client code (served by Node.js server):
<!DOCTYPE html> <html> <head> <style> body { background-color: #555555; color: #fff; font-family: Arial,Helvetica,sans-serif; } #status{ margin-top:50px; text-align: center; font-size:150px; } </style> <script src="/socket.io/socket.io.js"></script> <script> window.onload = function() { var messages = []; var socket = io.connect('http://xxxxxxxxxxxxxx'); var status = document.getElementById("status"); socket.on('pirstatus', function (data) { if(data) { status.innerHTML = "Fredrik rör sig"; document.body.style.backgroundColor = "green"; } else{ status.innerHTML = "Fredrik rör sig inte"; document.body.style.backgroundColor = "red"; } }); } </script> </head> <body> <div id="status">?</div> </body> </html>
Raspberry PI Node.js code, deployed using pi js:
var socket = require('socket.io-client')('http://xxxxxxxxxxxxxx');
socket.emit('pirstatus', false);
var gpio = require("gpio");
var gpio7 = gpio.export(7, {
direction: "in",
ready: function() {
console.log('ready');
}
});
gpio7.on("change", function(val) {
console.log(val)
if (val == 0) {
socket.emit('pirstatus', false);
}
else{
socket.emit('pirstatus', true);
}
});
The PIR sensor used: http://www.kjell.com/sortiment/el/elektronik/mikrokontroller/arduino/rorelsedetektor-p87892
The pir is simply connected to GND, 5V and pin 7 on the Raspberry PI.