Fun with Raspberry PI, Node.js and websockets

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.

Fredrik is moving

Node.js server code

var http = require("http");
var express = require("express");
var app = express();
var port = process.env.port || 3700;

var io = require('').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>
		body {
			background-color: #555555;
		    color: #fff;
		    font-family: Arial,Helvetica,sans-serif;
			text-align: center;
	<script src="/"></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"; = "green";
					status.innerHTML = "Fredrik rör sig inte"; = "red";
	<div id="status">?</div>

Raspberry PI Node.js code, deployed using pi js:

var socket = require('')('http://xxxxxxxxxxxxxx');
socket.emit('pirstatus', false);
var gpio = require("gpio");
var gpio7 = gpio.export(7, {
   direction: "in", 
   ready: function() {
gpio7.on("change", function(val) {
  if (val == 0) {
		socket.emit('pirstatus', false);    
		socket.emit('pirstatus', true);    

The PIR sensor used:

The pir is simply connected to GND, 5V and pin 7 on the Raspberry PI.

  • Carter

    I am trying to use your example and am a little new to node.js I think I have everything (dependencies), the webpage loads with no errors, but its just a gray question mark. Do i also need to run node raspberrypinode.js to get it to work?