Chapter 2. Basic Programming Recipes
As the next step in learning how to control and manipulate your BeagleBone Black, we will take a look at the following languages, tools, and simple programming recipes in this chapter:
- Introduction to BoneScript
- Toggle LED
- Using the Cloud9 IDE
- Node.js basic recipes
- Adding a new module to Node.js
- Using Node.js with Johnny-Five
- Python basic recipes
- Adding libraries
- Running a Python script to control the LEDs
Introduction
In the first chapter, our objective was to ensure that all you new chefs were ready with sharpened knives and the right combination of seasonings, or at least equipped with a basic working environment with happy, flashing blue LEDs on your BeagleBone Black and some command-line controls.
In later chapters, you will learn how to use other physical pieces of the system, including controlling the physical pins on the board. Before we get there, however, you will need to take a quick dip into a handful of recipes using programming languages that are typical and essential for building robust, compelling projects on BeagleBone Black. So, give a big round of applause to your soon-to-be faithful friends: BoneScript, Node.js, and Python.
Introduction to BoneScript
BoneScript is BBB's handy Node.js library. What is Node.js, you ask? Also, why bother with another library? We will talk more about Node.js in the next section. However, as far as another library goes, we're bothering with it because it's designed to work seamlessly with the hardware of your board, making physical computing development under embedded Linux faster and simpler. Using Arduino-like functions, BoneScript exploits the vast developer base of JavaScript.
Typically, your intention in using Node.js and BoneScript on BBB—just as it is with Python in the next section—is to gain access to the header pins, the General Purpose In/Out (GPIO) pins. Although we will discuss more about GPIOs in a later chapter, for now our plan is to briefly explore some fundamental methods to control the hardware.
Toggle LED
In this section, let's do a quick and easy recipe with BoneScript, one that turns on and off the on board LEDs, also known as USR LEDs. We will tackle more complex recipes with BoneScript in the next chapter.
How to do it...
In order to do this, perform the following steps:
- Remove all cables and power from your BBB.
- Power up your board via the mini USB using your desktop USB port.
- On the
BEAGLEBONE_BLACK
device that appears on your desktop, browse to and open theSTART.htm
file (some versions of the OS may have a slightly different file name, such asBASIC_START.htm
).Note
Note that on Debian 8 (Jessie), your board will be labelled
BEAGLEBONE
on the desktop and notBEAGLEBONE_BLACK
. - Scroll down the page to
BoneScript interactive guide
, where you'll see an embedded script that you can run to interact with BBB. - Click on Run.
- All the LEDs should stay on for two seconds. Let them return to blinking.
- Now change USR0 from
b.HIGH
tob.LOW
. - Change the timing from
2000
to12000
. - You should now see two differences from the default script that you just ran. Firstly, the LEDs now stay on for longer (12 seconds), and the USR0 LED—the LED closest to the Reset button—now remains off.
Voila! You're talking to the hardware using JavaScript and BoneScript.!
See also
If you run into any errors while running your BoneScript recipes, such as Cannot find module 'bonescript', you may need to do two things:
- Check the version of BoneScript that you are running on your board using the following code:
$ node -pe "require('bonescript').getPlatform().bonescript"
- Install the latest version of BoneScript; to do this, you need to be the root user first. Then, you can execute the following command:
$ sudo -i # TERM=none npm install -g bonescript
How to do it...
In order to do this, perform the following steps:
- Remove all cables and power from your BBB.
- Power up your board via the mini USB using your desktop USB port.
- On the
BEAGLEBONE_BLACK
device that appears on your desktop, browse to and open theSTART.htm
file (some versions of the OS may have a slightly different file name, such asBASIC_START.htm
).Note
Note that on Debian 8 (Jessie), your board will be labelled
BEAGLEBONE
on the desktop and notBEAGLEBONE_BLACK
. - Scroll down the page to
BoneScript interactive guide
, where you'll see an embedded script that you can run to interact with BBB. - Click on Run.
- All the LEDs should stay on for two seconds. Let them return to blinking.
- Now change USR0 from
b.HIGH
tob.LOW
. - Change the timing from
2000
to12000
. - You should now see two differences from the default script that you just ran. Firstly, the LEDs now stay on for longer (12 seconds), and the USR0 LED—the LED closest to the Reset button—now remains off.
Voila! You're talking to the hardware using JavaScript and BoneScript.!
See also
If you run into any errors while running your BoneScript recipes, such as Cannot find module 'bonescript', you may need to do two things:
- Check the version of BoneScript that you are running on your board using the following code:
$ node -pe "require('bonescript').getPlatform().bonescript"
- Install the latest version of BoneScript; to do this, you need to be the root user first. Then, you can execute the following command:
$ sudo -i # TERM=none npm install -g bonescript
See also
If you run into any errors while running your BoneScript recipes, such as Cannot find module 'bonescript', you may need to do two things:
- Check the version of BoneScript that you are running on your board using the following code:
$ node -pe "require('bonescript').getPlatform().bonescript"
- Install the latest version of BoneScript; to do this, you need to be the root user first. Then, you can execute the following command:
$ sudo -i # TERM=none npm install -g bonescript
Using the Cloud9 IDE
As the name implies, Cloud9 is a cloud-hosted toolkit. For BBB, it provides an integrated, open source development environment to build BoneScript-powered (JavaScript) code. Its strengths are JavaScript and Node.js (which it actually uses on the backend; we'll discuss this in the next section), though it is also very flexible with other programming languages such as PHP, Ruby, and Python.
The IDE comes preloaded and ready to use immediately on the BBB firmware with no setup necessary. With your board still connected via USB, let's do a snappy recipe.
How to do it…
- To load the IDE, open a browser window to the following URL:
http://192.168.7.2:3000/ide.html
. The IDE will open to a window like this: - Next, change the color settings to improve readability in the UI. The default black scheme is funereal; let's change it to Cloud9 Bright Theme instead.
Note
Not all UI screens change to the new color scheme; there's a temporary bug in this beta release of Cloud9's IDE.
- One handy feature in the lower portion of the screen is a command shell window. This gives the user an integrated command-line control within the IDE proper without the need to pop open another window for a shell application.
- Unless you want to customize the UI or listen to the audio tutorials, close the Welcome tab.
- Create a new file by clicking on the + sign.
- Copy and paste the following code in the new window:
var b = require('bonescript'); var ledPin = "USR0"; b.pinMode(ledPin, b.OUTPUT); var state = b.LOW; b.digitalWrite(ledPin, state); setInterval(toggle, 1000); function toggle() { if(state == b.LOW) state = b.HIGH; else state = b.LOW; b.digitalWrite(ledPin, state); }
For you Arduino users, the code feels kind of familiar, right? For those of you who are brand new to physical computing and hardware, let's break down some of the lines before executing the script.
At the outset of the code, we needed to establish certain ground rules, namely that we will be using the functionality of BoneScript. So, we had to include the BoneScript library with all its functionalities and coding shortcuts with the following script:
var b = require('bonescript');
Next, we needed to establish which pin or pins we intended to use (USR0
) and then create a variable of it so as to not have to write the pin name repeatedly throughout the script. The following code helped us do this:
var ledPin = "USR0";
Once we had an anointed pin to play with, we needed to set its mode—in other words, initialize it—so that we could interact with it and declare whether it will be an input or output pin. If we were controlling a button, the pin would need to be recognized as an input; however, in our case we had an LED, which needed to be in the output mode. Note also b.
, which is used in the notation. This was used to tell the code interpreter—Node.js—that the subsequent function will be found in the BoneScript library. For this, we used the following code:
b.pinMode(ledPin, b.OUTPUT);
With the pin initialized, we declared whether the pin began in a state of being on (HIGH
) or off (LOW
). At this point, we also needed to tell the interpreter that we would actually be writing to the pin, as opposed to collecting data from it or reading it, with the following script:
var state = b.LOW; b.digitalWrite(ledPin, state);
Our task moved on to telling the interpreter how often we will be doing a particular thing. In our case, we toggled the light on and off in 1000-millisecond intervals by executing the following script:
setInterval(toggle, 1000);
It was great that we knew the frequency of our toggle event, but as we did not yet tell the interpreter what the toggle
term actually does, we had to explain its meaning. We described it as a function that alternates between the states of HIGH
and LOW
, which was applied to the pin that we declared at the beginning of our script with the following lines of code:
function toggle() { if(state == b.LOW) state = b.HIGH; else state = b.LOW; b.digitalWrite(ledPin, state); }
Okay! For the moment, that's enough of a script breakdown. If you have not already jumped ahead, let's continue with the recipe's steps and take a look at how these lines actually affect the LED.
Now, perform the following steps:
- Create a new directory called
projects
and save the file in it, naming the filemajor_tom_blinks.js
. - Now, run the file in the terminal window at the bottom of the IDE. First, ensure that you navigate to the proper directory using the following lines of code:
$ cd projects $ node major_tom_blinks.js
- The USR0 LED (which is the on board LED closest to the reset button) should now have changed its constant "heartbeat"-patterned blink to slower, steadier 1-second blink intervals.
- Now, press Ctrl + z or click on the Stop button in the terminal pane window at the bottom of the IDE. Don't forget to do this; otherwise, you're likely to run into some errors or confusion in the upcoming recipes.
- Finally, it's a good idea to reset the LEDs so that you end up where you started. For now, the easiest way to do this is by running the restore script at http://beagleboard.org/Support/BoneScript/demo_blinkled/.
See also
You can find more information at http://beagleboard.org/Support/BoneScript.
How to do it…
- To load the IDE, open a browser window to the following URL:
http://192.168.7.2:3000/ide.html
. The IDE will open to a window like this: - Next, change the color settings to improve readability in the UI. The default black scheme is funereal; let's change it to Cloud9 Bright Theme instead.
Note
Not all UI screens change to the new color scheme; there's a temporary bug in this beta release of Cloud9's IDE.
- One handy feature in the lower portion of the screen is a command shell window. This gives the user an integrated command-line control within the IDE proper without the need to pop open another window for a shell application.
- Unless you want to customize the UI or listen to the audio tutorials, close the Welcome tab.
- Create a new file by clicking on the + sign.
- Copy and paste the following code in the new window:
var b = require('bonescript'); var ledPin = "USR0"; b.pinMode(ledPin, b.OUTPUT); var state = b.LOW; b.digitalWrite(ledPin, state); setInterval(toggle, 1000); function toggle() { if(state == b.LOW) state = b.HIGH; else state = b.LOW; b.digitalWrite(ledPin, state); }
For you Arduino users, the code feels kind of familiar, right? For those of you who are brand new to physical computing and hardware, let's break down some of the lines before executing the script.
At the outset of the code, we needed to establish certain ground rules, namely that we will be using the functionality of BoneScript. So, we had to include the BoneScript library with all its functionalities and coding shortcuts with the following script:
var b = require('bonescript');
Next, we needed to establish which pin or pins we intended to use (USR0
) and then create a variable of it so as to not have to write the pin name repeatedly throughout the script. The following code helped us do this:
var ledPin = "USR0";
Once we had an anointed pin to play with, we needed to set its mode—in other words, initialize it—so that we could interact with it and declare whether it will be an input or output pin. If we were controlling a button, the pin would need to be recognized as an input; however, in our case we had an LED, which needed to be in the output mode. Note also b.
, which is used in the notation. This was used to tell the code interpreter—Node.js—that the subsequent function will be found in the BoneScript library. For this, we used the following code:
b.pinMode(ledPin, b.OUTPUT);
With the pin initialized, we declared whether the pin began in a state of being on (HIGH
) or off (LOW
). At this point, we also needed to tell the interpreter that we would actually be writing to the pin, as opposed to collecting data from it or reading it, with the following script:
var state = b.LOW; b.digitalWrite(ledPin, state);
Our task moved on to telling the interpreter how often we will be doing a particular thing. In our case, we toggled the light on and off in 1000-millisecond intervals by executing the following script:
setInterval(toggle, 1000);
It was great that we knew the frequency of our toggle event, but as we did not yet tell the interpreter what the toggle
term actually does, we had to explain its meaning. We described it as a function that alternates between the states of HIGH
and LOW
, which was applied to the pin that we declared at the beginning of our script with the following lines of code:
function toggle() { if(state == b.LOW) state = b.HIGH; else state = b.LOW; b.digitalWrite(ledPin, state); }
Okay! For the moment, that's enough of a script breakdown. If you have not already jumped ahead, let's continue with the recipe's steps and take a look at how these lines actually affect the LED.
Now, perform the following steps:
- Create a new directory called
projects
and save the file in it, naming the filemajor_tom_blinks.js
. - Now, run the file in the terminal window at the bottom of the IDE. First, ensure that you navigate to the proper directory using the following lines of code:
$ cd projects $ node major_tom_blinks.js
- The USR0 LED (which is the on board LED closest to the reset button) should now have changed its constant "heartbeat"-patterned blink to slower, steadier 1-second blink intervals.
- Now, press Ctrl + z or click on the Stop button in the terminal pane window at the bottom of the IDE. Don't forget to do this; otherwise, you're likely to run into some errors or confusion in the upcoming recipes.
- Finally, it's a good idea to reset the LEDs so that you end up where you started. For now, the easiest way to do this is by running the restore script at http://beagleboard.org/Support/BoneScript/demo_blinkled/.
See also
You can find more information at http://beagleboard.org/Support/BoneScript.
See also
You can find more information at http://beagleboard.org/Support/BoneScript.
Node.js basic recipes
JavaScript on the server; let that sink in for a moment….
What is Node.js? The quick and dirty answer is that it's a unique and very fast server environment to handle requests from client applications and apps that are authored in Javascript. It's Javascript on the server. More specifically, it's an I/O framework that:
- Is event-driven
- Is nonblocking
- Runs on the V8 JavaScript engine
- Executes JavaScript code on the server side
- Is rich in robust developer libraries and modules
Node's speed makes it particularly useful in physical computing scenarios as it can handle requests in real time. After all, when a gust of sudden wind blows and your BBB-powered drone starts teetering midair, you don't want to rely on a poky LAMP stack and keep those gyros compensating.
The good news about Node.js—and we'll often just call it node—is that you don't have to install it because it comes preloaded on the BBB firmware. The bad news about Node.js is that it can be a bit confusing to understand for beginners; its sheer simplicity is daunting! However, once you review some recipes, you'll likely find yourself a new fangirl/fanboy of node.
Adding a new module to Node.js
Here is a recipe to add a new module into Node.js. In this case, we'll use Nodemailer, a powerful and highly customizable API e-mail engine. We chose this module because we wanted to actually have the script do something interesting and not just spit out another onscreen print command. At the end of this recipe, you will be able to run a script that sends an e-mail to your inbox.
Getting ready
Open up LXTerminal. Alternatively, open up the Cloud9 IDE in the manner described in the previous section.
How to do it...
Create a directory for your projects using the following command:
$ mkdir projects
Perform the following steps after creating a directory for your project:
- Browse to this new directory and make another
emailer
directory using the following command:$ cd projects $ mkdir emailer
- Now, go to the new directory with the following command:
$ cd emailer
- Although it's not mandatory, the following command is the proper first step to setting up your node environment:
$ npm init
You will see a series of prompts that you can fill out; you can skip them by hitting the return (Enter) key on your keyboard.
What you will do with these prompts and inputs is create the metadata to populate a file called
package.json
. This file's purpose is to give information tonpm
, which allows it to identify the project as well as handle the project's dependencies. - Next, we will use the following command to install the star of the current show: a node package called
nodemailer
:$ sudo npm install nodemailer --save
- Navigate to the new directory created by the installation and open up a
nano
window with a new filename, as described here:$ cd node_modules/nodemailer $ sudo nano nodemailer-test.js
- Copy and paste this code in the
nano
window://This code has been modified from the nodemailer github example. var nodemailer = require('nodemailer'); var transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: 'gmail.user@gmail.com', pass: 'user_password' } }); // setup e-mail data with unicode symbols var mailOptions = { // sender address from: 'Ground Control <your_name@gmail.com>', // list of receivers to: 'sender_name1@some_domain.com, another_address@anotherdomain.com', // Subject line subject: 'This is Ground Control to Major Tom', // plaintext body text: 'Can you hear me, Major Tom?', // html body html: '<b>Can you hear me Major Tom?</b>' }; // send mail with defined transport object transporter.sendMail(mailOptions, function(error, info){ if(error){ return console.log(error); } console.log('Message sent: ' + info.response); });
Note
The preceding code is a modification of nodemailer's GitHub example. Also note: if you run into problems copying and pasting the code, you can download the code from https://github.com/HudsonWerks/Nodemailer/blob/master/examples/nodemailer-test.js.
Finally, if you use Gmail for your account in this example and run into login errors, there are numerous troublehooting tips here: https://github.com/andris9/nodemailer-wellknown/issues/3.
- Save the new file using the keyboard command, Ctrl + x with
nano
, and then typeY
for "yes".Then, press the return (Enter) key.
- Now, run the following command:
$ node nodemailer-test.js
- Ta-da! If all went well, you should receive an e-mail from Ground Control in your inbox.
There's more…
- 6 things you should know about Node.js: This is perhaps the best (and most succinct) article on why Node.js has become a freight train for rapid, robust development, and can be found at http://www.javaworld.com/article/2079190/scripting-jvm-languages/6-things-you-should-know-about-node-js.html.
- The Node Beginner Book: The author of this book provides the first 21 pages for free and charges for the rest of the book, which is definitely worth the $20.00. You can find it athttp://www.nodebeginner.org/.
- Mixu's Node book: Although it was originally written several years ago, it remains an excellent in-depth introduction to Node.js. This can be easily found at http://book.mixu.net/node/.
- From Java to Node.js: You can find this at https://n0tw0rthy.wordpress.com/2012/01/08/from-java-to-node-js/.
- For further ideas on which modules are out there, explore the extensive list of node modules found at https://github.com/nodejs/node/wiki.
See also
To explore this particular module, including nodemailer's wide variety of features and customization options, check out https://github.com/andris9/Nodemailer.
Getting ready
Open up LXTerminal. Alternatively, open up the Cloud9 IDE in the manner described in the previous section.
How to do it...
Create a directory for your projects using the following command:
$ mkdir projects
Perform the following steps after creating a directory for your project:
- Browse to this new directory and make another
emailer
directory using the following command:$ cd projects $ mkdir emailer
- Now, go to the new directory with the following command:
$ cd emailer
- Although it's not mandatory, the following command is the proper first step to setting up your node environment:
$ npm init
You will see a series of prompts that you can fill out; you can skip them by hitting the return (Enter) key on your keyboard.
What you will do with these prompts and inputs is create the metadata to populate a file called
package.json
. This file's purpose is to give information tonpm
, which allows it to identify the project as well as handle the project's dependencies. - Next, we will use the following command to install the star of the current show: a node package called
nodemailer
:$ sudo npm install nodemailer --save
- Navigate to the new directory created by the installation and open up a
nano
window with a new filename, as described here:$ cd node_modules/nodemailer $ sudo nano nodemailer-test.js
- Copy and paste this code in the
nano
window://This code has been modified from the nodemailer github example. var nodemailer = require('nodemailer'); var transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: 'gmail.user@gmail.com', pass: 'user_password' } }); // setup e-mail data with unicode symbols var mailOptions = { // sender address from: 'Ground Control <your_name@gmail.com>', // list of receivers to: 'sender_name1@some_domain.com, another_address@anotherdomain.com', // Subject line subject: 'This is Ground Control to Major Tom', // plaintext body text: 'Can you hear me, Major Tom?', // html body html: '<b>Can you hear me Major Tom?</b>' }; // send mail with defined transport object transporter.sendMail(mailOptions, function(error, info){ if(error){ return console.log(error); } console.log('Message sent: ' + info.response); });
Note
The preceding code is a modification of nodemailer's GitHub example. Also note: if you run into problems copying and pasting the code, you can download the code from https://github.com/HudsonWerks/Nodemailer/blob/master/examples/nodemailer-test.js.
Finally, if you use Gmail for your account in this example and run into login errors, there are numerous troublehooting tips here: https://github.com/andris9/nodemailer-wellknown/issues/3.
- Save the new file using the keyboard command, Ctrl + x with
nano
, and then typeY
for "yes".Then, press the return (Enter) key.
- Now, run the following command:
$ node nodemailer-test.js
- Ta-da! If all went well, you should receive an e-mail from Ground Control in your inbox.
There's more…
- 6 things you should know about Node.js: This is perhaps the best (and most succinct) article on why Node.js has become a freight train for rapid, robust development, and can be found at http://www.javaworld.com/article/2079190/scripting-jvm-languages/6-things-you-should-know-about-node-js.html.
- The Node Beginner Book: The author of this book provides the first 21 pages for free and charges for the rest of the book, which is definitely worth the $20.00. You can find it athttp://www.nodebeginner.org/.
- Mixu's Node book: Although it was originally written several years ago, it remains an excellent in-depth introduction to Node.js. This can be easily found at http://book.mixu.net/node/.
- From Java to Node.js: You can find this at https://n0tw0rthy.wordpress.com/2012/01/08/from-java-to-node-js/.
- For further ideas on which modules are out there, explore the extensive list of node modules found at https://github.com/nodejs/node/wiki.
See also
To explore this particular module, including nodemailer's wide variety of features and customization options, check out https://github.com/andris9/Nodemailer.
How to do it...
Create a directory for your projects using the following command:
$ mkdir projects
Perform the following steps after creating a directory for your project:
- Browse to this new directory and make another
emailer
directory using the following command:$ cd projects $ mkdir emailer
- Now, go to the new directory with the following command:
$ cd emailer
- Although it's not mandatory, the following command is the proper first step to setting up your node environment:
$ npm init
You will see a series of prompts that you can fill out; you can skip them by hitting the return (Enter) key on your keyboard.
What you will do with these prompts and inputs is create the metadata to populate a file called
package.json
. This file's purpose is to give information tonpm
, which allows it to identify the project as well as handle the project's dependencies. - Next, we will use the following command to install the star of the current show: a node package called
nodemailer
:$ sudo npm install nodemailer --save
- Navigate to the new directory created by the installation and open up a
nano
window with a new filename, as described here:$ cd node_modules/nodemailer $ sudo nano nodemailer-test.js
- Copy and paste this code in the
nano
window://This code has been modified from the nodemailer github example. var nodemailer = require('nodemailer'); var transporter = nodemailer.createTransport({ service: 'Gmail', auth: { user: 'gmail.user@gmail.com', pass: 'user_password' } }); // setup e-mail data with unicode symbols var mailOptions = { // sender address from: 'Ground Control <your_name@gmail.com>', // list of receivers to: 'sender_name1@some_domain.com, another_address@anotherdomain.com', // Subject line subject: 'This is Ground Control to Major Tom', // plaintext body text: 'Can you hear me, Major Tom?', // html body html: '<b>Can you hear me Major Tom?</b>' }; // send mail with defined transport object transporter.sendMail(mailOptions, function(error, info){ if(error){ return console.log(error); } console.log('Message sent: ' + info.response); });
Note
The preceding code is a modification of nodemailer's GitHub example. Also note: if you run into problems copying and pasting the code, you can download the code from https://github.com/HudsonWerks/Nodemailer/blob/master/examples/nodemailer-test.js.
Finally, if you use Gmail for your account in this example and run into login errors, there are numerous troublehooting tips here: https://github.com/andris9/nodemailer-wellknown/issues/3.
- Save the new file using the keyboard command, Ctrl + x with
nano
, and then typeY
for "yes".Then, press the return (Enter) key.
- Now, run the following command:
$ node nodemailer-test.js
- Ta-da! If all went well, you should receive an e-mail from Ground Control in your inbox.
There's more…
- 6 things you should know about Node.js: This is perhaps the best (and most succinct) article on why Node.js has become a freight train for rapid, robust development, and can be found at http://www.javaworld.com/article/2079190/scripting-jvm-languages/6-things-you-should-know-about-node-js.html.
- The Node Beginner Book: The author of this book provides the first 21 pages for free and charges for the rest of the book, which is definitely worth the $20.00. You can find it athttp://www.nodebeginner.org/.
- Mixu's Node book: Although it was originally written several years ago, it remains an excellent in-depth introduction to Node.js. This can be easily found at http://book.mixu.net/node/.
- From Java to Node.js: You can find this at https://n0tw0rthy.wordpress.com/2012/01/08/from-java-to-node-js/.
- For further ideas on which modules are out there, explore the extensive list of node modules found at https://github.com/nodejs/node/wiki.
See also
To explore this particular module, including nodemailer's wide variety of features and customization options, check out https://github.com/andris9/Nodemailer.
There's more…
- 6 things you should know about Node.js: This is perhaps the best (and most succinct) article on why Node.js has become a freight train for rapid, robust development, and can be found at http://www.javaworld.com/article/2079190/scripting-jvm-languages/6-things-you-should-know-about-node-js.html.
- The Node Beginner Book: The author of this book provides the first 21 pages for free and charges for the rest of the book, which is definitely worth the $20.00. You can find it athttp://www.nodebeginner.org/.
- Mixu's Node book: Although it was originally written several years ago, it remains an excellent in-depth introduction to Node.js. This can be easily found at http://book.mixu.net/node/.
- From Java to Node.js: You can find this at https://n0tw0rthy.wordpress.com/2012/01/08/from-java-to-node-js/.
- For further ideas on which modules are out there, explore the extensive list of node modules found at https://github.com/nodejs/node/wiki.
See also
To explore this particular module, including nodemailer's wide variety of features and customization options, check out https://github.com/andris9/Nodemailer.
See also
To explore this particular module, including nodemailer's wide variety of features and customization options, check out https://github.com/andris9/Nodemailer.
Using Node.js with Johnny-Five
In this section, we will cover a recipe for Johnny-Five, a unique library built in JavaScript/Node.js that is increasingly getting the attention of the open source software world. Although positioned as a robotics library, Johnny-Five is a great tool set to scratch the itch that many JS developers have for hardware now.
One of its principal advantages is that it greatly simplifies the process of managing pins and allows a programmer to use more obvious naming conventions in their code, such as LEDs, buttons, sensors, and servos, rather than high pins, low pins, and so on. Although it does not yet have out-of-the-box ease that BoneScript has for BBB, you should consider it a viable and, in some ways, more robust alternative. It is also a more modular library than BoneScript as the code can be easily ported to a variety of platforms. Finally, if you are an Arduino aficionado, you will appreciate its familiarity as it is based on the Arduino Firmata protocol.
How to do it…
Perform the following steps to use Node.js with Johnny-Five:
- As usual, good practice before installing a new package is to update your repositories. You can use the following command line for this:
$ sudo apt-get update
- Next, we will install Johnny-Five as root user using
npm
(node package manager) and notapt-get
, as follows:$ sudo -i # npm install johnny-five
- Then, we will add a BeagleBone-specific plugin with the following command. This will make our board's I/O pins easily accessible:
$ npm install beaglebone-io
- In a terminal window, open up the
nano
editor with a new filename using this command:$ sudo nano johnny5_led1.js
- Copy and paste this code in the
nano
window:var five = require('johnny-five'); var BeagleBone = require('beaglebone-io'); var board = new five.Board({ io: new BeagleBone() }); board.on('ready', function() { var led = new five.Led(); // turn the LED off and on in 1000ms increments led.blink(1000); this.repl.inject({ led: led }); });
Note
If you run into problems copying and pasting the code, you can download the code from https://github.com/HudsonWerks/Johnny-Five/blob/master/johnny5_led1.js
- Save the new file using the following keyboard command with
nano
, Ctrl + x; when prompted typey
for yes and then press return (Enter) key: - Now, run the following script:
$ sudo node johnny5_led1.js
The onboard LED (USR3) should begin blinking at 1-second (1000ms) intervals.
We will not break down every part of the script here; you can further investigate Johnny-Five in the There's More... section. However, one thing we will point out is a feature of the code that expresses Johnny-Five's modularity over BoneScript, specifically the following line:
var board = new five.Board({ io: new BeagleBone()
With Johnny-Five, this code snippet is all you need to change if you want to run the same script on the Raspberry Pi, Arduino, or UDOO board or a huge range of other SOCs. "Write once, run anywhere" is getting closer….
There's more…
For more insight into Johnny-Five, it's best to start by exploring their wiki, which is full of examples and documentation, at http://johnny-five.io/. In addition to the BeagleBone Black, you will notice that the library supports a host of SOCs and microcontrollers.
Learn more about the Johnny-Five beaglebone-io
plugin and the specific pin mapping for the board at https://github.com/julianduque/beaglebone-io#beaglebone-io.
How to do it…
Perform the following steps to use Node.js with Johnny-Five:
- As usual, good practice before installing a new package is to update your repositories. You can use the following command line for this:
$ sudo apt-get update
- Next, we will install Johnny-Five as root user using
npm
(node package manager) and notapt-get
, as follows:$ sudo -i # npm install johnny-five
- Then, we will add a BeagleBone-specific plugin with the following command. This will make our board's I/O pins easily accessible:
$ npm install beaglebone-io
- In a terminal window, open up the
nano
editor with a new filename using this command:$ sudo nano johnny5_led1.js
- Copy and paste this code in the
nano
window:var five = require('johnny-five'); var BeagleBone = require('beaglebone-io'); var board = new five.Board({ io: new BeagleBone() }); board.on('ready', function() { var led = new five.Led(); // turn the LED off and on in 1000ms increments led.blink(1000); this.repl.inject({ led: led }); });
Note
If you run into problems copying and pasting the code, you can download the code from https://github.com/HudsonWerks/Johnny-Five/blob/master/johnny5_led1.js
- Save the new file using the following keyboard command with
nano
, Ctrl + x; when prompted typey
for yes and then press return (Enter) key: - Now, run the following script:
$ sudo node johnny5_led1.js
The onboard LED (USR3) should begin blinking at 1-second (1000ms) intervals.
We will not break down every part of the script here; you can further investigate Johnny-Five in the There's More... section. However, one thing we will point out is a feature of the code that expresses Johnny-Five's modularity over BoneScript, specifically the following line:
var board = new five.Board({ io: new BeagleBone()
With Johnny-Five, this code snippet is all you need to change if you want to run the same script on the Raspberry Pi, Arduino, or UDOO board or a huge range of other SOCs. "Write once, run anywhere" is getting closer….
There's more…
For more insight into Johnny-Five, it's best to start by exploring their wiki, which is full of examples and documentation, at http://johnny-five.io/. In addition to the BeagleBone Black, you will notice that the library supports a host of SOCs and microcontrollers.
Learn more about the Johnny-Five beaglebone-io
plugin and the specific pin mapping for the board at https://github.com/julianduque/beaglebone-io#beaglebone-io.
There's more…
For more insight into Johnny-Five, it's best to start by exploring their wiki, which is full of examples and documentation, at http://johnny-five.io/. In addition to the BeagleBone Black, you will notice that the library supports a host of SOCs and microcontrollers.
Learn more about the Johnny-Five beaglebone-io
plugin and the specific pin mapping for the board at https://github.com/julianduque/beaglebone-io#beaglebone-io.
Python basic recipes
In addition to your JavaScript chops, some of you reading this most likely have some Python skills. We'll take a look at a similar recipe to activate the onboard LEDs; this time, however, we will do this from a Python perspective.
Getting ready
Let's confirm that you have Python installed and working properly along with its IDE. After this, perform the following steps:
- Open a terminal window and type the following:
$ python
- At the
>>>
prompt, type:>>> print "This is Ground Control"
- Now, you should see this:
This is Ground Control
- To quit, press Ctrl + z.
Getting ready
Let's confirm that you have Python installed and working properly along with its IDE. After this, perform the following steps:
- Open a terminal window and type the following:
$ python
- At the
>>>
prompt, type:>>> print "This is Ground Control"
- Now, you should see this:
This is Ground Control
- To quit, press Ctrl + z.
Adding libraries
The current Debian distribution includes the Adafruit_BBIO and PyBBIO libraries, both of which are extremely useful and commonly used on BBB to control the pins of your board with Python. We will work with these libraries in the next section.
If you're using the current Debian 7 Wheezy distribution or Debian 8 Jessie, you can skip to the next section. However, if you have some other version of an OS, here are the steps to install the two libraries.
How to do it…
Part One: Installing Adafruit _BBIO library. Perform the following steps:
- Log in as the root user with this command:
$ sudo -i
- Using the following command, ensure that you update your package list:
# apt-get update
- Now, install the library's dependencies through the following command:
# apt-get install build-essential python-dev python-setuptools python-pip python-smbus -y
Note
For instructions on installing a software patch to make extra pins accessible with the library (the SPI and UART pins, in particular), refer to the further chapters.
- Now, we can install the library itself with the following command:
# pip install Adafruit_BBIO
- Test your package installation by typing out this command:
# python -c "import Adafruit_BBIO.GPIO as GPIO; print GPIO"
Your output should look similar to this:
<module 'Adafruit_BBIO.GPIO' from '/usr/local/lib/python2.7/dist-packages/Adafruit_BBIO/GPIO.so'>
Part Two: Installing PyBBIO library. Perform the following steps:
- Log in as the root user with the following command line:
$ sudo -i
- Ensure that you've updated your package list using the following command:
# apt-get update
- Now, install the library's dependencies with this command:
# apt-get install python-serial python-setuptools python-dev python-smbus python-pip
- Now, we can install the library itself. Use the following command for this:
# pip install --upgrade PyBBIO
- Test your package installation via the following command line:
# python -c "import bbio as GPIO; print GPIO"
If all went as hoped with the installation, your output should look similar to this:
PyBBIO initialized<module 'bbio' from '/usr/local/lib/python2.7/dist-packages/PyBBIO-0.9.4-py2.7-linux-armv7l.egg/bbio/__init__.pyc'>Finished PyBBIO cleanup
How to do it…
Part One: Installing Adafruit _BBIO library. Perform the following steps:
- Log in as the root user with this command:
$ sudo -i
- Using the following command, ensure that you update your package list:
# apt-get update
- Now, install the library's dependencies through the following command:
# apt-get install build-essential python-dev python-setuptools python-pip python-smbus -y
Note
For instructions on installing a software patch to make extra pins accessible with the library (the SPI and UART pins, in particular), refer to the further chapters.
- Now, we can install the library itself with the following command:
# pip install Adafruit_BBIO
- Test your package installation by typing out this command:
# python -c "import Adafruit_BBIO.GPIO as GPIO; print GPIO"
Your output should look similar to this:
<module 'Adafruit_BBIO.GPIO' from '/usr/local/lib/python2.7/dist-packages/Adafruit_BBIO/GPIO.so'>
Part Two: Installing PyBBIO library. Perform the following steps:
- Log in as the root user with the following command line:
$ sudo -i
- Ensure that you've updated your package list using the following command:
# apt-get update
- Now, install the library's dependencies with this command:
# apt-get install python-serial python-setuptools python-dev python-smbus python-pip
- Now, we can install the library itself. Use the following command for this:
# pip install --upgrade PyBBIO
- Test your package installation via the following command line:
# python -c "import bbio as GPIO; print GPIO"
If all went as hoped with the installation, your output should look similar to this:
PyBBIO initialized<module 'bbio' from '/usr/local/lib/python2.7/dist-packages/PyBBIO-0.9.4-py2.7-linux-armv7l.egg/bbio/__init__.pyc'>Finished PyBBIO cleanup
Running a Python script to control the LEDs
In the next chapter, we'll look at more robust ways to begin using the GPIO pin library. In the meantime, let's wrap up by doing an on board LED blink similar to the recipe we did earlier in the chapter.
However, instead of BoneScript, we'll do a variation of the recipe in Python and specifically pull on the PyBBIO library's functionality. This recipe will work on both Debian Wheezy and Jessie.
How to do it…
Perform the following steps to run Python scripts to control LEDs:
- Open up LXTerminal.
- Create a python project directory within the
bbb_recipe_book
directory and navigate to it as follows:mkdir python cd bbb_recipe_book/projects/python
- Create a new Python file using the following code (note the
.py
file format):sudo nano major_tom_blinks.py
- Copy and paste the following code into the window:
#!/usr/bin/python # Blinks one of the Beaglebone Black's on-board LEDs until CTRL-C is pressed. These LEDs include USR0, USR1, USR2, USR3 # Import PyBBIO library from bbio import * #import the time module which allows us to set the timing for a loop event import time #Create variable called ledPin which refers to one of the designated onboard USR LEDs. You can change the number to any of the USR LEDs listed above. ledPin = "USR3" # Create a setup function def setup(): # Set one of the USR LEDs as output pinMode(ledPin, OUTPUT) # Set up a loop and the blink timing to two second intervals while True: # Start the pin state at LOW = off digitalWrite(ledPin, LOW) # Hold this state for 2 seconds time.sleep(2) # Change the pin state to HIGH = on digitalWrite(ledPin, HIGH) time.sleep(2)
Note
If you run into problems copying and pasting the code, you can download the code from https://github.com/HudsonWerks/Python-examples/blob/master/major_tom_blinks.py
- Run this script:
$ sudo python major_tom_blinks.py
- The on board USR3 LED should now be blinking at regular 2-second intervals.
- To quit the script, press Ctrl + z on your keyboard.
There's more…
Python is a big subject, and the web is jammed with great resources to learn it more deeply. Here is a small, select sample of starting points to teach yourself Python:
- MIT's online course is on demand, free, and taught by one of their computer science department's favorite teachers, Prof. John Guttag. You can find it at https://www.edx.org/course/introduction-computer-science-mitx-6-00-1x-5.
- Coursera has several strong online courses. Most of their courses are not available on demand but for specific schedules throughout the year. Here are two excellent Python courses offered:
- University of MICHIGAN offers Python in their Programming for Everybody series. You can find it at https://www.coursera.org/specializations/python.
- Rice Unversity's 8-week course is another excellent introductory dive to be found at https://class.coursera.org/interactivepython1-003.
- Python.org is an excellent place to get started with its tons of links on the beginners' page at the link, https://wiki.python.org/moin/BeginnersGuide/Programmers.
How to do it…
Perform the following steps to run Python scripts to control LEDs:
- Open up LXTerminal.
- Create a python project directory within the
bbb_recipe_book
directory and navigate to it as follows:mkdir python cd bbb_recipe_book/projects/python
- Create a new Python file using the following code (note the
.py
file format):sudo nano major_tom_blinks.py
- Copy and paste the following code into the window:
#!/usr/bin/python # Blinks one of the Beaglebone Black's on-board LEDs until CTRL-C is pressed. These LEDs include USR0, USR1, USR2, USR3 # Import PyBBIO library from bbio import * #import the time module which allows us to set the timing for a loop event import time #Create variable called ledPin which refers to one of the designated onboard USR LEDs. You can change the number to any of the USR LEDs listed above. ledPin = "USR3" # Create a setup function def setup(): # Set one of the USR LEDs as output pinMode(ledPin, OUTPUT) # Set up a loop and the blink timing to two second intervals while True: # Start the pin state at LOW = off digitalWrite(ledPin, LOW) # Hold this state for 2 seconds time.sleep(2) # Change the pin state to HIGH = on digitalWrite(ledPin, HIGH) time.sleep(2)
Note
If you run into problems copying and pasting the code, you can download the code from https://github.com/HudsonWerks/Python-examples/blob/master/major_tom_blinks.py
- Run this script:
$ sudo python major_tom_blinks.py
- The on board USR3 LED should now be blinking at regular 2-second intervals.
- To quit the script, press Ctrl + z on your keyboard.
There's more…
Python is a big subject, and the web is jammed with great resources to learn it more deeply. Here is a small, select sample of starting points to teach yourself Python:
- MIT's online course is on demand, free, and taught by one of their computer science department's favorite teachers, Prof. John Guttag. You can find it at https://www.edx.org/course/introduction-computer-science-mitx-6-00-1x-5.
- Coursera has several strong online courses. Most of their courses are not available on demand but for specific schedules throughout the year. Here are two excellent Python courses offered:
- University of MICHIGAN offers Python in their Programming for Everybody series. You can find it at https://www.coursera.org/specializations/python.
- Rice Unversity's 8-week course is another excellent introductory dive to be found at https://class.coursera.org/interactivepython1-003.
- Python.org is an excellent place to get started with its tons of links on the beginners' page at the link, https://wiki.python.org/moin/BeginnersGuide/Programmers.
There's more…
Python is a big subject, and the web is jammed with great resources to learn it more deeply. Here is a small, select sample of starting points to teach yourself Python:
- MIT's online course is on demand, free, and taught by one of their computer science department's favorite teachers, Prof. John Guttag. You can find it at https://www.edx.org/course/introduction-computer-science-mitx-6-00-1x-5.
- Coursera has several strong online courses. Most of their courses are not available on demand but for specific schedules throughout the year. Here are two excellent Python courses offered:
- University of MICHIGAN offers Python in their Programming for Everybody series. You can find it at https://www.coursera.org/specializations/python.
- Rice Unversity's 8-week course is another excellent introductory dive to be found at https://class.coursera.org/interactivepython1-003.
- Python.org is an excellent place to get started with its tons of links on the beginners' page at the link, https://wiki.python.org/moin/BeginnersGuide/Programmers.