{"id":5074,"date":"2015-02-04T21:17:45","date_gmt":"2015-02-04T21:17:45","guid":{"rendered":"http:\/\/randomnerdtutorials.com\/?p=5074"},"modified":"2020-03-05T01:25:18","modified_gmt":"2020-03-05T01:25:18","slug":"programming-the-beaglebone-black-with-bonescript","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/programming-the-beaglebone-black-with-bonescript\/","title":{"rendered":"Programming the BeagleBone Black with BoneScript"},"content":{"rendered":"<div style=\"padding: 10px; line-height: 1.2; text-align: center; background-color: #f5f5f5;\">This entry is part 3 of 4 in the series <a href=\"https:\/\/randomnerdtutorials.com\/category\/bbb-series\/\">Getting Started with BeagleBone Black<\/a>. This post\u00a0was written by\u00a0Rui Santos and Lu\u00eds Perestrelo authors of <a href=\"https:\/\/amzn.to\/2TrwWEJ\" target=\"_blank\" rel=\"noopener noreferrer\">BeagleBone For Dummies<\/a> *<\/div>\n<p>\u00a0<\/p>\n<p>This part introduces BoneScript, a Node.js library containing functions specially created for the <a href=\"http:\/\/amzn.to\/1xukLSK\" target=\"_blank\" rel=\"noopener noreferrer\">BeagleBone Black<\/a> *. This library simplifies the process of accessing and configuring the pins of your BeagleBone Black.<\/p>\n<p>Controlling an output, reading a button\/sensor, controlling a motor are quite easy with BoneScript. If you used an Arduino before, you\u2019ll find most functions very similar.<\/p>\n<h2>Introduction<\/h2>\n<p>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.<\/p>\n<p>In this project you\u2019ll create a web server that controls outputs and it can be accessed remotely with\u00a0your smartphone, tablet or laptop.<\/p>\n<h2>The Framework<\/h2>\n<p>Your BeagleBone will be hosting a web server, establishing a communication between your device\u2019s web browser and your BeagleBone GPIOs.<\/p>\n<p>Your web server is created with some Node.js code, and when you access IP address <a href=\"http:\/\/192.168.7.2:8888\" target=\"_blank\" rel=\"noopener noreferrer\">http:\/\/192.168.7.2:8888<\/a>, your web browser requests your<strong> index.html<\/strong> file that is stored on your BeagleBone.<\/p>\n<p><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter wp-image-5079\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/framework-web-server-beaglebone-black.png?resize=624%2C211&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"framework web server beaglebone black\" width=\"624\" height=\"211\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/framework-web-server-beaglebone-black.png?w=1006&amp;quality=100&amp;strip=all&amp;ssl=1 1006w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/framework-web-server-beaglebone-black.png?resize=300%2C101&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 624px) 100vw, 624px\" \/><\/p>\n<p>192.168.7.2 is the local USB address of your BeagleBone\u00a0and\u00a08888 is the port that you\u2019ll be using.<\/p>\n<p>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\u00a0your BeagleBone\u2019s pins.<\/p>\n<h2>Parts required<\/h2>\n<p>For this project you need:<\/p>\n<ul>\n<li>1x BeagleBone Black (<a href=\"http:\/\/amzn.to\/1xukLSK\" target=\"_blank\" rel=\"noopener noreferrer\">Click to see on Amazon<\/a> *)<\/li>\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\">1x Breadboard<\/a><\/li>\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/3mm-5mm-leds-kit-storage-box\/\">1x LED<\/a><\/li>\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\">1x 220\u03a9 or 1x 470\u03a9 resistor<\/a><\/li>\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\">2x jumper cables<\/a><\/li>\n<li>Mini USB Cable<\/li>\n<li>Ethernet Cable<\/li>\n<\/ul>\n<h2>Wiring your circuit<\/h2>\n<p>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\u00a0\u2014 such as relay\u00a0\u2014 through a web page that you can access with your smartphone from the comfort of your sofa.<\/p>\n<p><img data-recalc-dims=\"1\" decoding=\"async\" class=\"aligncenter wp-image-5080\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/Web-Server-LED.png?resize=492%2C560&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Web Server LED\" width=\"492\" height=\"560\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/Web-Server-LED.png?w=1108&amp;quality=100&amp;strip=all&amp;ssl=1 1108w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/Web-Server-LED.png?resize=264%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 264w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/Web-Server-LED.png?resize=900%2C1024&amp;quality=100&amp;strip=all&amp;ssl=1 900w\" sizes=\"(max-width: 492px) 100vw, 492px\" \/><\/p>\n<h2>Installing socket.io<\/h2>\n<p>You have to install a Node.js package called socket.io. Having your BBB connected to the internet, type the following commands in your\u00a0terminal:<\/p>\n<pre>sudo npm install update\n sudo npm install -g socket.io<\/pre>\n<p>The first command updates the list of all available packages to the latest version, and the second one installs socket.io globally.<\/p>\n<p>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.<\/p>\n<h2>Creating a folder and your files<\/h2>\n<p>We encourage you to use the Cloud9 IDE as often as possible to program your BeagleBone. First read the previous part:\u00a0<a href=\"https:\/\/randomnerdtutorials.com\/cloud9-ide-on-the-beaglebone-black\/\">Cloud 9 IDE on the BeagleBone Black<\/a>.<\/p>\n<p>With the Cloud9 IDE open, you can create a folder and file in your workspace. Follow these steps:<\/p>\n<ol>\n<li>Right-click the <strong>cloud9<\/strong> folder and choose <strong>New Folder<\/strong> from the shortcut\u00a0menu.<\/li>\n<li>Name the new folder <strong>Projects<\/strong>.<\/li>\n<li>Right-click the <strong>Projects<\/strong> folder and choose <strong>New File<\/strong> from the shortcut\u00a0menu.<\/li>\n<li>Name your file <strong>index.html<\/strong>.<\/li>\n<li>Repeat step number 3. and name your new file <strong>server.js<\/strong>.<\/li>\n<\/ol>\n<p>This is how it should look like in the end:<\/p>\n<p><img data-recalc-dims=\"1\" decoding=\"async\" class=\"aligncenter size-full wp-image-5076\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/bbb_bonescript_cloud9.png?resize=567%2C756&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"bbb_bonescript_cloud9\" width=\"567\" height=\"756\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/bbb_bonescript_cloud9.png?w=567&amp;quality=100&amp;strip=all&amp;ssl=1 567w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/bbb_bonescript_cloud9.png?resize=225%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 225w\" sizes=\"(max-width: 567px) 100vw, 567px\" \/><\/p>\n<h2>Writing your Web Page<\/h2>\n<p>Your\u00a0<strong>index.html<\/strong> file is very straight forward. It\u00a0contains: 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 <strong>server.js<\/strong>. The code is well commented below:<\/p>\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n    &lt;title&gt;Home Automation Web Server with BeagleBone&lt;\/title&gt;\n    &lt;script src = &quot;\/socket.io\/socket.io.js&quot; &gt;&lt;\/script&gt;\n    &lt;script&gt;\n        \/\/ Establishing connection with server\n        var socket = io.connect();\n\n        \/\/ Changes the led state\n        function changeState(state){\n            if (state==1){\n                \/\/ Emit message changing the state to 1\n                socket.emit('changeState', '{&quot;state&quot;:1}');\n                \/\/ Change led status on web page to ON\n                document.getElementById(&quot;outputStatus&quot;).innerHTML = &quot;Status: ON&quot;;\n            }\n            else if (state==0){\n                \/\/ Emit message changing the state to 0\n                socket.emit('changeState', '{&quot;state&quot;:0}');\n                \/\/ Change led status on web page to OFF\n                document.getElementById(&quot;outputStatus&quot;).innerHTML = &quot;Status: OFF&quot;;\n            }\n        }\n    &lt;\/script&gt;\n&lt;\/head&gt;\n    &lt;h2&gt;LED&lt;\/h2&gt;\n    &lt;p id=&quot;outputStatus&quot;&gt;Status&lt;\/p&gt;\n    &lt;button type=&quot;button&quot; onclick=&quot;changeState(1);&quot;&gt;ON&lt;\/button&gt;\n    &lt;button type=&quot;button&quot; onclick=&quot;changeState(0);&quot;&gt;OFF&lt;\/button&gt;\n&lt;\/div&gt;\n&lt;\/body&gt;\n&lt;\/html&gt;\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/BeagleBone\/BBB-BoneScript-Web-Server\/index.html\" target=\"_blank\">View raw code<\/a><\/p>\n<h2>Creating your Web Server<\/h2>\n<p>Your <strong>server.js<\/strong>\u00a0file is the last piece of the puzzle. First you have to load all the required modules and \u00a0configure your BeagleBone Black&#8217;s pin. You also initialize a\u00a0web server on port 8888. Then you establish the communication between<strong> server.js<\/strong> and <strong>index.html<\/strong> files using socket.io.<\/p>\n<p>The \u00a0function called handleChangeState() turns your LED either on or off according to the message received from your <strong>index.html<\/strong>. The code is also commented so you can understand exactly what each line is doing:<\/p>\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/\/Loading modules\nvar http = require('http');\nvar fs = require('fs');\nvar path = require('path');\nvar b = require('bonescript');\n\n\/\/ Create a variable called led, which refers to P9_14\nvar led = &quot;P9_14&quot;;\n\/\/ Initialize the led as an OUTPUT\nb.pinMode(led, b.OUTPUT);\n\n\/\/ Initialize the server on port 8888\nvar server = http.createServer(function (req, res) {\n    \/\/ requesting files\n    var file = '.'+((req.url=='\/')?'\/index.html':req.url);\n    var fileExtension = path.extname(file);\n    var contentType = 'text\/html';\n    \/\/ Uncoment if you want to add css to your web page\n    \/*\n    if(fileExtension == '.css'){\n        contentType = 'text\/css';\n    }*\/\n    fs.exists(file, function(exists){\n        if(exists){\n            fs.readFile(file, function(error, content){\n                if(!error){\n                    \/\/ Page found, write content\n                    res.writeHead(200,{'content-type':contentType});\n                    res.end(content);\n                }\n            })\n        }\n        else{\n            \/\/ Page not found\n            res.writeHead(404);\n            res.end('Page not found');\n        }\n    })\n}).listen(8888);\n\n\/\/ Loading socket io module\nvar io = require('socket.io').listen(server);\n\n\/\/ When communication is established\nio.on('connection', function (socket) {\n    socket.on('changeState', handleChangeState);\n});\n\n\/\/ Change led state when a button is pressed\nfunction handleChangeState(data) {\n    var newData = JSON.parse(data);\n    console.log(&quot;LED = &quot; + newData.state);\n    \/\/ turns the LED ON or OFF\n    b.digitalWrite(led, newData.state);\n}\n\n\/\/ Displaying a console message for user feedback\nserver.listen(console.log(&quot;Server Running ...&quot;));\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/BeagleBone\/BBB-BoneScript-Web-Server\/server.js\" target=\"_blank\">View raw code<\/a><\/p>\n<h2>Download all the code<\/h2>\n<p>Instead of copying and pasting you can <a href=\"https:\/\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/BBB-BoneScript-Web-Server.zip\" target=\"_blank\" rel=\"noopener noreferrer\">click here to download<\/a> all the code used in this project. Then you unzip that folder and upload the code into your BeagleBone Black.<\/p>\n<h2>Launching your web server<\/h2>\n<p>Launching your web server is easy. You simply save all two\u00a0files. Click the green button &#8220;<strong>Run<\/strong>&#8221; in the Cloud9 IDE, and you should see a message in your <a href=\"https:\/\/randomnerdtutorials.com\/cloud9-ide-on-the-beaglebone-black\/\">output window<\/a> that says &#8220;<strong>Server Running . . .<\/strong> &#8220;.<\/p>\n<p>That\u2019s it, your web server is up and running! Open a tab in your web browser, and type <a href=\"http:\/\/192.168.7.2:8888\" target=\"_blank\" rel=\"noopener noreferrer\">http:\/\/192.178.7.2:8888<\/a>. You see a web page similar to the following figure.<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-5078\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/bbb_bonescript_web_page.png?resize=450%2C308&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"bbb_bonescript_web_page\" width=\"450\" height=\"308\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/bbb_bonescript_web_page.png?w=450&amp;quality=100&amp;strip=all&amp;ssl=1 450w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/bbb_bonescript_web_page.png?resize=300%2C205&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 450px) 100vw, 450px\" \/><\/p>\n<p><strong>This web page only opens\u00a0only if your computer is connected directly to the BeagleBone Black by USB. <\/strong>If that\u2019s not the case, read the next section to see how to access the BeagleBone through a device connected in your workspace network.<\/p>\n<h2>Accessing your Web Server with another device<\/h2>\n<p>To access your web page in any device inside your network, you need your BeagleBone Black&#8217;s Ethernet IP address. Open your terminal and type the following command:<\/p>\n<pre>ifconfig<\/pre>\n<p>Our\u00a0Ethernet IP address is highlighted in the following figure.<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-5082\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/bbb_bonescript_ifconfig1.png?resize=595%2C588&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"bbb_bonescript_ifconfig\" width=\"595\" height=\"588\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/bbb_bonescript_ifconfig1.png?w=785&amp;quality=100&amp;strip=all&amp;ssl=1 785w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/bbb_bonescript_ifconfig1.png?resize=300%2C297&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 595px) 100vw, 595px\" \/><\/p>\n<p>Now you can type your Ethernet\u00a0IP address followed by the port number (example\u00a0<a href=\"http:\/\/192.168.1.80:8888\" target=\"_blank\" rel=\"noopener noreferrer\">http:\/\/192.168.1.80:8888<\/a>)\u00a0in a web browser of any device.<\/p>\n<p>Now you can control any outputs remotely!<\/p>\n<p><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-5073\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/bonescript-web-server-led.gif?resize=474%2C335&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"bonescript web server led\" width=\"474\" height=\"335\" \/><\/p>\n<h2>Conclusion<\/h2>\n<p>That\u2019s all for now! In the next part you\u2019ll learn about programming the Beaglebone Black with Python. If you enjoy this series make sure you subscribe\u00a0<a href=\"https:\/\/randomnerdtutorials.com\/download\">here<\/a>\u00a0so you don\u2019t miss our next blogs posts\u00a0using this board.<\/p>\n<p>Special thanks to Lu\u00eds Perestrelo for helping Rui Santos putting this series together!<\/p>\n<p><a href=\"https:\/\/randomnerdtutorials.com\/programming-the-beaglebone-black-with-python\/\">This is part 3, read part 4 now! -&gt;<\/a><\/p>\n\n\n<p><em>* 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<\/em>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This entry is part 3 of 4 in the series Getting Started with BeagleBone Black. This post\u00a0was written by\u00a0Rui Santos and Lu\u00eds Perestrelo authors of BeagleBone For Dummies * \u00a0 &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Programming the BeagleBone Black with BoneScript\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/programming-the-beaglebone-black-with-bonescript\/#more-5074\" aria-label=\"Read more about Programming the BeagleBone Black with BoneScript\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":1,"featured_media":5078,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[305,217,204,270,205,213,264,206],"tags":[],"class_list":["post-5074","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-0-other","category-bbb-series","category-beaglebone","category-beaglebone-project","category-beaglebone-black","category-nodejs","category-project","category-b-tutorials"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2015\/02\/bbb_bonescript_web_page.png?fit=450%2C308&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/5074","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=5074"}],"version-history":[{"count":0,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/5074\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/5078"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=5074"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=5074"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=5074"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}