Programming the BeagleBone Black with BoneScript

This entry is part 3 of 4 in the series Getting Started with BeagleBone Black. This post was written by Rui Santos and Luís Perestrelo authors of BeagleBone For Dummies *

 

This part introduces BoneScript, a Node.js library containing functions specially created for the BeagleBone Black *. This library simplifies the process of accessing and configuring the pins of your BeagleBone Black.

Controlling an output, reading a button/sensor, controlling a motor are quite easy with BoneScript. If you used an Arduino before, you’ll find most functions very similar.

Introduction

The BeagleBone is quite a powerful tool when it comes to home automation, because it provides easy access to the web and lots of GPIOs.

In this project you’ll create a web server that controls outputs and it can be accessed remotely with your smartphone, tablet or laptop.

The Framework

Your BeagleBone will be hosting a web server, establishing a communication between your device’s web browser and your BeagleBone GPIOs.

Your web server is created with some Node.js code, and when you access IP address http://192.168.7.2:8888, your web browser requests your index.html file that is stored on your BeagleBone.

framework web server beaglebone black

192.168.7.2 is the local USB address of your BeagleBone and 8888 is the port that you’ll be using.

When you click one of the buttons on your web page, an event triggers and talks with your Node.js code, which has the package socket.io listening for an event to occur. Based on that event message, your Node.js code interacts your BeagleBone’s pins.

Parts required

For this project you need:

Wiring your circuit

Turning an LED on or off is the first thing you do when experimenting with a new technology. After completing this project you control any electronic component — such as relay — through a web page that you can access with your smartphone from the comfort of your sofa.

Web Server LED

Installing socket.io

You have to install a Node.js package called socket.io. Having your BBB connected to the internet, type the following commands in your terminal:

sudo npm install update
 sudo npm install -g socket.io

The first command updates the list of all available packages to the latest version, and the second one installs socket.io globally.

This package allows real-time communication between your web browser events and your BeagleBone. In other words, as soon as you click a button on your web page, your Node.js code that was listening acts immediately according to the message sent in that event.

Creating a folder and your files

We encourage you to use the Cloud9 IDE as often as possible to program your BeagleBone. First read the previous part: Cloud 9 IDE on the BeagleBone Black.

With the Cloud9 IDE open, you can create a folder and file in your workspace. Follow these steps:

  1. Right-click the cloud9 folder and choose New Folder from the shortcut menu.
  2. Name the new folder Projects.
  3. Right-click the Projects folder and choose New File from the shortcut menu.
  4. Name your file index.html.
  5. Repeat step number 3. and name your new file server.js.

This is how it should look like in the end:

bbb_bonescript_cloud9

Writing your Web Page

Your index.html file is very straight forward. It contains: a heading 2, a paragraph to output the current status of the LED and two buttons. Then you load your socket.io module and write a simple JavaScript script to send a message to your server.js. The code is well commented below:

<!DOCTYPE html>
<html>
<head>
    <title>Home Automation Web Server with BeagleBone</title>
    <script src = "/socket.io/socket.io.js" ></script>
    <script>
        // Establishing connection with server
        var socket = io.connect();

        // Changes the led state
        function changeState(state){
            if (state==1){
                // Emit message changing the state to 1
                socket.emit('changeState', '{"state":1}');
                // Change led status on web page to ON
                document.getElementById("outputStatus").innerHTML = "Status: ON";
            }
            else if (state==0){
                // Emit message changing the state to 0
                socket.emit('changeState', '{"state":0}');
                // Change led status on web page to OFF
                document.getElementById("outputStatus").innerHTML = "Status: OFF";
            }
        }
    </script>
</head>
    <h2>LED</h2>
    <p id="outputStatus">Status</p>
    <button type="button" onclick="changeState(1);">ON</button>
    <button type="button" onclick="changeState(0);">OFF</button>
</div>
</body>
</html>

View raw code

Creating your Web Server

Your server.js file is the last piece of the puzzle. First you have to load all the required modules and  configure your BeagleBone Black’s pin. You also initialize a web server on port 8888. Then you establish the communication between server.js and index.html files using socket.io.

The  function called handleChangeState() turns your LED either on or off according to the message received from your index.html. The code is also commented so you can understand exactly what each line is doing:

//Loading modules
var http = require('http');
var fs = require('fs');
var path = require('path');
var b = require('bonescript');

// Create a variable called led, which refers to P9_14
var led = "P9_14";
// Initialize the led as an OUTPUT
b.pinMode(led, b.OUTPUT);

// Initialize the server on port 8888
var server = http.createServer(function (req, res) {
    // requesting files
    var file = '.'+((req.url=='/')?'/index.html':req.url);
    var fileExtension = path.extname(file);
    var contentType = 'text/html';
    // Uncoment if you want to add css to your web page
    /*
    if(fileExtension == '.css'){
        contentType = 'text/css';
    }*/
    fs.exists(file, function(exists){
        if(exists){
            fs.readFile(file, function(error, content){
                if(!error){
                    // Page found, write content
                    res.writeHead(200,{'content-type':contentType});
                    res.end(content);
                }
            })
        }
        else{
            // Page not found
            res.writeHead(404);
            res.end('Page not found');
        }
    })
}).listen(8888);

// Loading socket io module
var io = require('socket.io').listen(server);

// When communication is established
io.on('connection', function (socket) {
    socket.on('changeState', handleChangeState);
});

// Change led state when a button is pressed
function handleChangeState(data) {
    var newData = JSON.parse(data);
    console.log("LED = " + newData.state);
    // turns the LED ON or OFF
    b.digitalWrite(led, newData.state);
}

// Displaying a console message for user feedback
server.listen(console.log("Server Running ..."));

View raw code

Download all the code

Instead of copying and pasting you can click here to download all the code used in this project. Then you unzip that folder and upload the code into your BeagleBone Black.

Launching your web server

Launching your web server is easy. You simply save all two files. Click the green button “Run” in the Cloud9 IDE, and you should see a message in your output window that says “Server Running . . . “.

That’s it, your web server is up and running! Open a tab in your web browser, and type http://192.178.7.2:8888. You see a web page similar to the following figure.

bbb_bonescript_web_page

This web page only opens only if your computer is connected directly to the BeagleBone Black by USB. If that’s not the case, read the next section to see how to access the BeagleBone through a device connected in your workspace network.

Accessing your Web Server with another device

To access your web page in any device inside your network, you need your BeagleBone Black’s Ethernet IP address. Open your terminal and type the following command:

ifconfig

Our Ethernet IP address is highlighted in the following figure.

bbb_bonescript_ifconfig

Now you can type your Ethernet IP address followed by the port number (example http://192.168.1.80:8888) in a web browser of any device.

Now you can control any outputs remotely!

bonescript web server led

Conclusion

That’s all for now! In the next part you’ll learn about programming the Beaglebone Black with Python. If you enjoy this series make sure you subscribe here so you don’t miss our next blogs posts using this board.

Special thanks to LuĂ­s Perestrelo for helping Rui Santos putting this series together!

This is part 3, read part 4 now! ->

* We are a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for us to earn fees by linking to Amazon.com and affiliated sites.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

12 thoughts on “Programming the BeagleBone Black with BoneScript”

  1. Hi,
    i want to run my web server without cloud9 when BBB boots when i connect it to my laptop via usb.
    Any ideas how can i do this?

    Thanks in advance! 🙂

    Reply
  2. I am trying to do this tutorial but I can’t seem to get socket.io to work. I am using a beaglebone black and the cloud 9 IDE and I’m on Debian linux. I don’t understand where to run the npm install command or the socket.io install command. Do I run that from the Cloud 9 terminal on the Beaglebone black? I tried this and got some error messages. I am really at a loss and tried doing it locally on my machine and that didn’t work either.

    Reply
  3. I`m trying to get socket.io via putty and cloud9 but I always get the error like bellow,

    root@beaglebone:~# sudo npm install update
    npm http GET https://registry.npmjs.org/update
    npm http GET https://registry.npmjs.org/update
    npm http GET https://registry.npmjs.org/update
    npm ERR! network getaddrinfo ENOTFOUND
    npm ERR! network This is most likely not a problem with npm itself
    npm ERR! network and is related to network connectivity.
    npm ERR! network In most cases you are behind a proxy or have bad network settings.
    npm ERR! network
    npm ERR! network If you are behind a proxy, please make sure that the
    npm ERR! network ‘proxy’ config is set properly. See: ‘npm help config’

    npm ERR! System Linux 3.8.13-bone47
    npm ERR! command “/usr/bin/nodejs” “/usr/bin/npm” “install” “update”
    npm ERR! cwd /root
    npm ERR! node -v v0.10.25
    npm ERR! npm -v 1.3.10
    npm ERR! syscall getaddrinfo
    npm ERR! code ENOTFOUND
    npm ERR! errno ENOTFOUND
    npm ERR!
    npm ERR! Additional logging details can be found in:
    npm ERR! /root/npm-debug.log
    npm ERR! not ok code 0

    My Setting is just connected My BBB by USB only.

    Reply
  4. Hi Rui,
    I cant install download npm or socket.io via cloud9 terminal.. all I’m getting it the below error:

    debian@beaglebone:/var/lib/cloud9$ sudo npm install -g socket.io
    [sudo] password for debian:
    npm ERR! code EAI_AGAIN
    npm ERR! errno EAI_AGAIN
    npm ERR! request to https://registry.npmjs.org/socket.io failed, reason: getaddrinfo EAI_AGAIN registry.npmjs.org registry.npmjs.org:443

    npm ERR! A complete log of this run can be found in:
    npm ERR! /root/.npm/_logs/2020-04-06T20_22_00_421Z-debug.log
    debian@beaglebone:/var/lib/cloud9$ ^C
    debian@beaglebone:/var/lib/cloud9$

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.