NodeJS Raspberry Pi Rover

My typical Raspberry Pi projects are done in Python. I thought that I’d try some Node.js testing because I find the standalone Python Webserver (http.server library) to be a little slow on the Pi hardware.

Getting Started with Node.js on Raspberry Pi

Node.js can be installed on your Pi by:

$ sudo apt-get update
$ sudo apt-get install -y nodejs

There are a few options on how to talk to the GPIO (General Purpose Input/Output) pins on the Pi. I tested a few and I found that pigpio worked well for my setup. It is installed by:

sudo apt-get install pigpio

To set a GPIO pin to be an output and next to turn it on, a simple Node.js program (gpio.js) would be:

// gpio.js - set GPIO pin 4 to ON

const Gpio = require('pigpio').Gpio; 
const led = new Gpio(4, {mode: Gpio.OUTPUT});

To run the program:

sudo node gpio.js

It is important to note that access to the GPIO pins require admin rights so you will need to run your scripts with sudo (super user do).

Node.js Webserver

To make a simple webserver (mywebserver.js) :

// mywebserver.js - a simple websever on port 8080
var http = require('http').createServer(handler); //require http server, and create server with function handler()
var fs = require('fs'); //require filesystem module

http.listen(8080); //listen to port 8080

function handler (req, res) { //create server
  fs.readFile(__dirname + '/index.html', function(err, data) { //read file index.html in public folder
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'}); //display 404 on error
      return res.end("404 Not Found");
    res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
    res.write(data); //write data from index.html
    return res.end();

This script references the http and the fs (file system) modules, and this allow us to reference an external index.html page. The handler function is used to manage the HTTP requests.

Next you’ll need to make an index.html page, below is a simple example:

<!DOCTYPE html>
<h1>Dummy HTML Test Page</h1><hr>

To test this page run: node mywebserver.js , and from a browser use your Pi’s IP address with port 8080, for example : 


Make the Web Page Dynamic

To make the Web Page dynamic we can use the package. It is installed by:

$ npm install --save

By using, javascript functions on the web page can communicate to functions running on the Node.js web server.socketio

Once a function is created in the Node.js webserver application the Web page can pass data to that function.

The Raspberry Pi Rover

There are some low cost Arduino car frames that cost under $10. These car frames can be used with a Raspberry Pi but you will need to be careful on how the motors are powered. Depending on the motors you might be able to drive them directly from Pi GPIO pins, however it is recommended that you use some external hardware to protect your Pi. There are some good Pi motor top options available, for my project I used the Pimoroni Explorer Hat Pro


My hardware setup used a Pi 3 with a portable phone charger. I used some duct tape to secure the wiring, charger and Pi together.

The motor pins will vary based on hardware that you use, so my code my need to be tweeked for your setup. The ‘control’ function is what I used to define the motor state. Some key words : forward, left, right, stop or back were passed between the web page and the server app to define the rover’s motor action. 

// ws_2_rover.js - NodeJS WebServer App to control a Rover

var http = require('http').createServer(handler); //require http server, and create server with function handler()
var fs = require('fs'); //require filesystem module
var io = require('')(http) //require module and pass the http object (server)

const Gpio = require('pigpio').Gpio;
// modify for your motor pinouts
const MOTOR1 = new Gpio(21, {mode: Gpio.OUTPUT}); 
const MOTOR2 = new Gpio(19, {mode: Gpio.OUTPUT}); 
const MOTOR3 = new Gpio(20, {mode: Gpio.OUTPUT}); 
const MOTOR4 = new Gpio(26, {mode: Gpio.OUTPUT}); 

// Ensure that the rover app starts without the motors running
function rover_stop() {

http.listen(8080); //listen to port 8080

function handler (req, res) { //create server

  fs.readFile(__dirname + '/web_2_rover.htm', function(err, data) { //read file index.html in public folder
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'}); //display 404 on error
      return res.end("404 Not Found");
    res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
    res.write(data); //write data from index.html
    return res.end();


io.sockets.on('connection', function (socket) {// WebSocket Connection
  console.log('A user connected');
  var controlvalue = ""; // variable for current status of the rover

  socket.on('control', function(data) { //get light switch status from client
    controlvalue = data;
    console.log('control input: ' + data);

    rover_stop(); // stop the motors, and then do the required action

    if (controlvalue == "forward") { 
    if (controlvalue == "left") { 
    if (controlvalue == "right") { 

    if (controlvalue == "backward") { 


I used the Bootstrap template to offer a mobile friendly web interface. A button onclick function was used to pass the requested motor action (forward, left, right, stop, backward) to the control socket function. Below is my web page (web_2_rover.htm):

<!DOCTYPE html>
<title>NodeJS Web Rover Control</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
<script src=""></script>

<script src=""></script>

var socket = io(); //load and connect to the host that serves the page

<div class="container">
  <h1>NodeJS Web Rover Control</h1>
  <button onclick="socket.emit('control','forward')" class="btn btn-success" style="width: 100%">Forwards</button>
  <button onclick="socket.emit('control','left')" class="btn btn-primary" style="width: 49%">Left</button>
  <button onclick="socket.emit('control','right')" class="btn btn-primary" style="width: 49%">Right</button>
  <button onclick="socket.emit('control','stop')" class="btn btn-danger" style="width: 100%">Stop</button>
  <button onclick="socket.emit('control','backward')" class="btn btn-warning" style="width: 100%">Backwards</button>     

To run the rover app enter:

sudo node ws_2_rover.js

Final Comments

I have done this project also in Python. The Python code is a little cleaner because the Pimoroni Explorer Hat has a Python library so I could easily adjust the motor speeds. However I found that the Node.js web interface to be a little faster than Python on the Pi.



Pi PHP Controls

I’ve been trying to teach my kids PHP,  below are some notes on how to get a PHP page to control Pi GPIO outputs. For motor controls we use the Pimoroni ExplorerHat Pro and it is possible to address the ExplorerHat pins directly with gpio calls. However other shields or tops like PiFace Digital could also be used.

Loading PHP

On the Raspberry Pi you will need to load both a web server and PHP. There are a number of good web servers to load. We picked Apache because it is well documented and more mainstream.

There are some good installation procedure for installing Apache and PHP on the Raspberry Pi. A minimalist installation would be:

sudo apt-get install apache2 -y
sudo apt-get install php5 libapache2-mod-php5 -y</pre>
<div class="highlight highlight-source-shell">

If everything is installed correctly the Apache home directory should be: /var/www/html.

To test that your installation is working open a browser on the Pi and go to: http://localhost. If the default (index.html) page comes up then you’ve install Apache correctly.

ExplorerHat Pro GPIO Pinouts

Typically we use the Python interface to talk to the ExplorerHat Pro. If you use PHP you will need to address the ExplorerHat Pro GPIO pins directly.

ExplorerHat  BCM wPi
Motor 1 Forward 19 24
Motor 1 Backward 20 28
Motor 2 Forward 21 29
Motor 2 Backward 26 25
LED 1 4 7
LED 2 17 0
LED 3 27 2
LED 4 5 21
Output 1 22 31
Output 2 26 32
Output 3 23 33
Output 4 27 36

PHP Interfacing to Pi GPIO

There are a few ways to access the GPIO pins in PHP:
1. use a PHP library
2. shell to the gpio command

Using a PHP library allows for a standard PHP interface, with an object model.

From testing I found that the PHP libraries were not as flexible as the standard gpio command. For example you could not access extended GPIO pin numbers (i.e. 200).

GPIO Command Line Utility

PHP can shell out to the gpio command line utility. I liked this approach because I could test the actions manually before putting them into a PHP web page.

A simple gpio read example would be:

<html lang="en">
<?php $ret = shell_exec('gpio read 7'); echo "Pin 7 status = " . $ret; ?>

A simple gpio write example would be:

<?php exec("gpio write 7 1"); $ret = shell_exec('gpio read 7'); echo "Pin 7 status = " . $ret; ?>

PHP Forms

For many Pi projects button interfaces are all that is required. In the Web design this is not typical so it is important to determine which button is pushed. One approach to this problem is to give all the buttons the same name:

<form action="" method="post">
  <input type="submit" name="submit" value="go">
  <input type="submit" name="submit" value="left">
  <input type="submit" name="submit" value="right">
  <input type="submit" name="submit" value="stop">

Then in the PHP code look for a value for this form variable:

<?php // define the GPIO pins for the motor ouptput (Note: PiFace pins start at 200) 
$leftpin = 24; 
$rightpin = 29; 
if (isset($_POST['submit'])) {
 	switch ($_POST['submit']) {
 		case "go": 
                     exec("gpio write " . $leftpin . " 1");
 	             exec("gpio write " . $rightpin . " 1"); 
                case "stop":
 		     exec("gpio write " . $leftpin . " 0");
 		     exec("gpio write " . $rightpin . " 0"); 
                case "left": 
		     exec("gpio write " . $leftpin . " 1"); 
		     exec("gpio write " . $rightpin . " 0"); 
                case "right": 
		     exec("gpio write " . $leftpin . " 0"); 
		     exec("gpio write " . $rightpin . " 1");

Some of the key items are:

  • Add references in to the bootstrap ccs and js files
  • Add tags with the required class definitions:
    • the btn-lg class will make a large button, instead of standard sized btn 
    • different button colours are possible using btn-info, btn-success. btn-danger
    • Button width is defined with style=”width: xx%” . For multiple buttons the sum of the width needs to <100%

Further Examples

Below are some pictures of a mobile rocket launcher project.  The Web page had two sections. The top section controlled bi-directional motors that were connected to a Explorer HAT Pro shield. The bottom section controlled the rocket launcher turret. The missile launcher was connected via a USB cable to the Pi. For the missile launcher program we created a Python app with command line options to set the action.



Le gocart (Python Tkinter GUI)

For this project we wanted to control a Lego vehicle with a Python Tkinter app. Next we added a short cut to the Pi desktop and then we used VNC to see the Pi desktop and our app on a tablet.

Hardware Setup

Our hardware components were:

  • Raspberry Pi 3
  • Pimoroni ExplorerHat Pro – supports bi-directional DC motors
  • Dexter Connectors – allow 2 wire connections to Lego Mindstorms parts
  • 2 Lego Mindstorms motors
  • Portable USB charger
  • lots of Lego parts
  • 4 jumpers


The Lego Mindstorms parts are little pricey but they allow you to make some pretty funky contraptions. The other thing that we like about the Mindstorms motors is that they have a lot of torque for a 5V DC motor.

There are a few options for the cabling (like cutting the cable and exposing the individual wires) we used the Dexter connectors that are breadboard friendly. ANA and GND connections on the Dexter side go to Motor + and Motor – on the ExplorerHat Pro board.



Python Tkinter

The Tkinter library allows you to create a simple graphic user interface (GUI) with components like: buttons, sliders, lists, text, labels etc.

For our interface we created a grid of 3 rows and 2 columns with 5 buttons. We made a simple motor function where we passed the speed and direction of the wheels. A negative speed is backwards, zero is stop, and a positive speed is forward.

import Tkinter
import explorerhat 

top = Tkinter.Tk()
top.title("Car Control")

#Define the buttons

def motor(Left,Right):

B_Left = Tkinter.Button(top, text ="Left", bg = "green", fg = "white", width= 15, height= 5, command = lambda: motor (50,0)).grid(row=1,column=1)
B_Right = Tkinter.Button(top, text ="Right", bg = "green", fg = "white", width= 15, height= 5, command = lambda: motor (0,50)).grid(row=1,column=2)
B_Forward= Tkinter.Button(top, text ="Forward", bg = "green", fg = "white", width= 15, height= 5, command = lambda: motor (50,50)).grid(row=2,column=1)
B_Backward = Tkinter.Button(top, text ="Backward", bg = "green", fg = "white", width= 15, height= 5, command = lambda: motor (-50,-50)).grid(row=2,column=2)
B_Stop = Tkinter.Button(top, text ="Stop", bg = "red", fg = "white", width= 33, height= 3, command = lambda: motor (0,0)).grid(row=3,column=1,columnspan=2)



Pi Shortcut

To create a Pi shortcut, create a file:

nano $HOME/desktop/pi.desktop

Inside this file define the name, path, and icon info for your new application:

[Desktop Entry]
Name=Car Controls
Comment=Python Tkinter Car Control Panel
Exec=python /home/pi/

VNC (Virtual Network Computing)

VNC is install on the Raspbian image. To enable VNC run:

sudo raspi-config

Then select the interfacing option, and then select VNC and enable.


Finally you will need to define a VNC password and load some VNC software on your Tablet. There are a lot of packages to choose from. We have an Android table and we used RemoteToGo without any problems.

Note, when your Pi boots without a HDMI monitor connected the desktop resolution will be at a low setting (probably 800×600) this can be adjusted. For us we simply resized the desktop to fit our tablet screen.

Pi/Node-Red Car

The goal of the Pi/Node-Red car project was to create a small vehicle that can be controlled from a smart phone . For the project we used:

  • 1 Car chassis for Arduino ($15)
  • 1 Pimoroni Explorer HAT Pro  ($23)
  • 1 Portable microUSB charger
  • 1 USB WiFi Adapter
  • 4 short alligator clips and 4 connectors
  • Duct tape

The Arduino car chassis may require a small amount of assembly. Rather than soldering connections we like to use short alligator clips. It is not recommended to wire DC motors directly to a Raspberry Pi so the Pimoroni Explorer HAT Pro is used to connect the 2 DC motors.

The Raspberry Pi and the portable microUSB charger are secured to the top of the car chassis with duct tape. The left motor is wired to the motor 1 connectors on the Explorer Hat, and the right motor is wired to motor 2 connectors. Note you may have to do a little trial and error on the Explorer HAT “+” and “-” motor connections to get both wheels spinning in a forward direction.

The Explorer HAT Node-Red library is installed by:

 cd $HOME/.node-red
npm install node-red-dashboard 

The Web dashboard presentation is configured in the “dashboard” tab. For this example we create 2 groups: a control group to drive the vehicle, and a light group to turn on the Explorer Pro lights. Use the “+group” button to add a group, and the “edit” to change an existing group.

To control a motor, an “Explorer HAT” node and a dashboard button node are dropped and connected together. All the configuration is done in the button node . The button configure options are:

  • the group the button will appear in (Controls)
  • the size of the button (3×1 = 50% of width and narrow)
  • Topic, or motor.twois used for motor control
  • Payload, -100 = reverse, 0=stop, 100 = forward


The Explorer HAT has 4 colored LEDs. To toggle the LEDS, the topic is light.color with 1=ON, and 0=OFF . We thought that it would be fun to also add some Web dashboard button to control the colored lights.


The Node-Red dashboard user interface is accessed by: ipaddress:1880/UI, so for example Below is a picture that shows the final vehicle logic and the Web dashboard.






Remote Controlled Rocket Launcher

We’ve made a number of different versions of the mobile rocket launcher, and all of them have been fun. The version above is using the a PI 1 with a PiFace Digital module for the motor controls and a wireless keyboard for the controls.

The version shown below is using a PI 3, with an ExploreHAT Pro for the motor controls and a Python Web Server program for the controls. By using some simplified HTML tagging we were able to use an old PSP as a remote interface console.


Rocket Launcher Sample Code

We found the rocket launcher in a sale bin, but they call be purchased at: The rocket launcher comes with it’s own Windows based program.

Below is some Python code that will control the rockets launchers turret and fire a missile. Based on this sample code you should be able to make some cool projects. A couple of notes from our testing:

  • you need to manually stop the turret motion once you start it. So you need to set your own wait time
  • you need 3-4 seconds between each missile firing. It might be a coincident but we damaged our first rocket launcher trying to issue fast firing commands.
 import usb
import sys
import time

device = usb.core.find(idVendor=0x2123, idProduct=0x1010)

# On Linux we need to detach usb HID first
# except Exception, e:
except Exception:

pass # already unregistered


endpoint = device[0][(0,0)][0]

down = 1 # down
up = 2 # up
left = 4 # rotate left
right = 8 # rotate right
fire = 16 # fire
stop = 32 # stop

#device.ctrl_transfer(0x21, 0x09, 0x0200, 0, [signal])

while True:

print('r = right, l = left, u = up, d = down, f = fire ')
key = raw_input ('enter key:')
if (key == 'l'):
device.ctrl_transfer(0x21, 0x09, 0, 0, [0x02, left, 0x00,0x00,0x00,0x00,0x00,0x00])
if (key == 'u'):
device.ctrl_transfer(0x21, 0x09, 0, 0, [0x02, up, 0x00,0x00,0x00,0x00,0x00,0x00])
if (key == 'r'):
device.ctrl_transfer(0x21, 0x09, 0, 0, [0x02, right, 0x00,0x00,0x00,0x00,0x00,0x00])
if (key == 'd'):
device.ctrl_transfer(0x21, 0x09, 0, 0, [0x02, down, 0x00,0x00,0x00,0x00,0x00,0x00])
if (key == 'f'):
device.ctrl_transfer(0x21, 0x09, 0, 0, [0x02, fire, 0x00,0x00,0x00,0x00,0x00,0x00])
device.ctrl_transfer(0x21, 0x09, 0, 0, [0x02, stop, 0x00,0x00,0x00,0x00,0x00,0x00]) 




Wii Controlled Lego Rover

Use your Raspberry Pi (or a Linux PC) to talk to a Lego NXT rover and then use a Wii remote to drive the rover.

Python Libraries

There are 2 sets of libraries that we used:

  • nxt-python : to talk to the Lego Mindstorm NXT
  • cwiid : to talk to Wii remotes

To install these libraries:

tar -zxvf nxt-python-2.2.2.tar.gz
cd nxt*
sudo python install
sudo apt-get install python-cwiid

The Lego NXT brick needs to have Bluetooth turned on. Check the top left corner of the Brick’s screen to see if the Bluetooth symbol is showing. If it is not showing go into the Bluetooth options and turn it on.


The next step is to ensure that the Raspberry Pi can see the Lego NXT. The Pi can scan Bluetooth devices with the command:

hcitool scan

If the Bluetooth is working then you will see the Bluetooth address of the NXT., (for example: 00:16:53:04:23:3D). Using the NXT’s Bluetooth address you can pair the Pi and the Lego NXT by:

sudo bluez-simple-agent hci0 00:16:53:04:23:3D

For the pin code use the default of: 1234
The NXT will beep and prompt you for the pairing passkey.


After the Raspberry Pi is paired with the Lego NXT brick you are able to use Python to read the NXT sensors and control the motors. No NXT coding is required. In the Python NXT directory there are some examples,  is a good test example because it does not require any sensors or motors.

Our full Python code to control the NXT Rover with a Wii remote is below:

import cwiid
import time
import nxt.locator
from nxt.motor import *

print 'Looking for a Lego NXT ... may take up to 15 seconds...'
b = nxt.locator.find_one_brick()
print 'Lego NXT Connected'

left = Motor(b, PORT_B)
right = Motor(b, PORT_C)

print 'Press 1+2 on your Wiimote now...'
wii = cwiid.Wiimote()
wii.rpt_mode = cwiid.RPT_BTN 
print 'WII Remote Connected'

while True:
 buttons = wii.state['buttons']
 if (buttons & cwiid.BTN_LEFT):
 right.brake() = 100,regulated=False)

if (buttons & cwiid.BTN_RIGHT):
 left.brake() = 100,regulated=False)

if (buttons & cwiid.BTN_UP): = 100,regulated=False) = 100,regulated=False)

if (buttons & cwiid.BTN_DOWN):



littleBits Rover

Create a remote control littleBits rover using the littleBits wireless transmitter (w12) Bit ($40) and the wireless receiver (w11) Bit ($40). These wireless bits can also be  found in some of the littleBits kits, (for example the Gizmo and Gadgets kit).

The wireless modules can pass up to 3 signals. Depending on what you are trying to remotely control you could mix and match between dimmers, buttons and toggle switches. If you add some littleBits proto modules you could come up with some interesting designs.

Step 1 : Build the Remote

To create the wireless remote for the a Rover we needed to control the left and right motors , for this we used the following components:

  •  1- littleBits mounting plate (comes with base set)
  • 1 – littleBits fork module ($12)
  • 2 – littleBits dimmer($8) or slide switches ($10)
  • 1 – littleBits wireless transmitter
  • 1-  littleBits power module with battery ($6)

We connected the power module to a fork module and then the fork module powered our dimmer modules. We mounted all the components on a littleBits mounting plate, and we taped the battery to the back.



The littleBits motor circuit is quite simple, the only important thing is to ensure that you have the wheels turning in the same direction.