Introducing BoneScript - Programming with BoneScript - BeagleBone For Dummies (2015)

BeagleBone For Dummies (2015)

Part III

Programming with BoneScript

Visit www.dummies.com/extras/beaglebone to read an article about using keyboard shortcuts with the Cloud9 IDE.

In this part …

· Launching the Cloud9 integrated development environment (IDE) for the first time

· Experimenting with BoneScript and writing your first script

· Understanding general programming concepts, such as variables, if statements, and while loops

· Playing around with a three-color LED, some buttons, and a motion sensor

Chapter 7

Introducing BoneScript

In This Chapter

Getting familiar with JavaScript, Node.js, and BoneScript

Launching and exploring Cloud9 IDE

Writing your first script from scratch with BoneScript

Wiring an LED and a resistor and blinking more LEDs

One of the coolest things that the BeagleBone enables you to do is watch the code you write become projects that interact with the real world. Chapter 6 gives you a glimpse of that world, but it really merely scratches the surface.

This chapter introduces BoneScript, a library containing functions specially created for the BeagleBone. This library greatly simplifies the process of configuring the pins of your BeagleBone; tasks such as blinking a light-emitting diode (LED), reading a button, controlling a servomotor, and reading a sensor are quite easy with BoneScript.

You get into programming just as you get the hang of riding a bike — by practicing — and that’s exactly what this chapter helps you do. This chapter introduces new concepts with examples whose results you can promptly watch in the real world. We greatly encourage you to try them yourself and, after you feel confident, add a twist of your own.

Introducing JavaScript, Node.js, and BoneScript

JavaScript is a programming language that is most commonly used on websites. If you’ve ever visited a website with really cool things, such as interactive buttons, slideshow animations, alert messages, or pop-up windows, some sort of JavaScript certainly was working on the back end. JavaScript is used in web browsers, and it allows interactions with the clients without talking to the server.

JavaScript communication is done asynchronously. This means that data isn’t transmitted at regular intervals, which makes it different than several communication protocols.

Node.js is a framework that allows applications written in JavaScript to run applications outside the web browser and interact directly with the server. BoneScript is a Node.js library that makes reading and controlling the GPIOs (general purpose inputs/outputs; see Chapter 6) of your BeagleBone a no-brainer.

One thing that makes JavaScript really powerful is the fact that unlike in other programming languages, your code won’t wait to run each line sequentially. Some lines are skipped and then wait for an event such as a button press. For this reason, people often say that this language is much faster than usual. This language contrasts with Python, the other GPIO-controlling language covered in this book, in which all lines of code run one after another, each line waiting for the previous one to complete before doing its task.

Introducing Cloud9 IDE

The Cloud9 integrated development environment (IDE) is an open-source web-based programming platform that supports several programming languages. This great piece of software comes installed on your BeagleBone by default. Its greatest advantage is that the code you write on your desktop computer is immediately passed to your BeagleBone through the SSH (Secure Shell).

Cloud9 also comes with some features that make every programmer’s life a little bit easier:

· Code completion: After you start typing a command, if you hover your mouse over what you’ve typed, you see suggestions for autocompleting your command.

· Functions: The code editor comes with search, a goto file, themes, and much more.

· Drag-and-drop functionality: It’s easy to move folders and files within your workspace.

· Programming: Cloud9 supports several programming languages, such as JavaScript, Python, HTML, Ruby, and C.

· SSH and FTP: You can access your own server with SSH (the process is similar to the one described in Chapter 3, but done in a browser) and connect to your FTP server to edit your projects.

· Collaborative: Cloud9 enables you to work with other developers to edit the same code and chat in real time.

Visit the official Cloud9 IDE website at https://c9.io to find out more about this software.

Launching the Cloud9 IDE

Grab your BeagleBone and connect it to your computer through a Mini USB cable. After the board boots up, open your web browser, and type 192.168.7.2:3000 in the address bar. You see something similar to Figure 7-1 when the page loads.

You can also access the Cloud 9 IDE via Ethernet. Power up your BeagleBone, and connect an Ethernet cable from your BeagleBone to your router. Open your web browser, and type beaglebone:3000. You see a page that looks like the one shown in Figure 7-1.

If you’ve changed your hostname as discussed in Chapter 4, in your web browser’s address bar, type <yourhostname>:3000.

Figure 7-1: Cloud9 IDE running on a BeagleBone Black.

Exploring the Cloud9 IDE

When you open the Cloud9 IDE for the first time, you may feel intimidated. There are so many menus, submenus, options, and tabs!

To get started with your first project, you need to know about only a few of the windows of the Cloud9 IDE. The following sections give you a closer look at the six main areas of the Cloud9 IDE.

Menus tab

If you’ve ever used any computer application, you’ll find that the menus in the Cloud9 IDE are organized in a very familiar way:

· File menu commands create, open, save, and close files.

· Edit menu commands give you the option to undo or redo a task, as well as cut, copy, paste, and edit your files. You can use the typical Ctrl or Cmd key shortcuts with these tools.

· Find menu commands make it easy to find or replace words in your code.

· View menu commands allow you to change the look and feel of your editor window.

· Goto menu commands provide fast ways to access the right file.

· Run menu commands are used to run and build your scripts.

· Tools menu commands are used to format your code, rename variables, and play macros.

· Window menu commands enable you to select the windows you want to open or close.

Workspace

You can access all your folders and files with the workspace window (see Figure 7-2). Just like in your computer’s file system, everything is organized in a hierarchy. You can drag and drop to move files, and creating folders and files is quite easy.

Editor

The first time you open the Cloud9 IDE, the Preferences tab is open in the editor window (refer to Figure 7-1 earlier in this chapter). You can close that tab because by default, Cloud9 is preconfigured.

As soon as you open one of your scripts, the editor window looks like the one shown in “Creating a folder and .js file” later in this chapter. This window is where you write all your code. The editor highlights the functions according to the syntax of the programming of the file you have open, which is decided by its file extension.

Figure 7-2: Exploring the Cloud9 IDE.

Console

When you run a script, the console prints the output of your application (refer to Figure 7-2 earlier in this chapter). If you’re running a web server, for example, the console tells you the URL of the page that is being served. You can also print messages — using the JavaScript function console.log('<Your message>'). Those messages are commonly used to debug your code.

Debugger

The debugger is the perfect way to see exactly what is happening when you run your scripts (refer to Figure 7-2 earlier in this chapter). You can create a breakpoint so that your code runs only to a certain line that you define. You can also see which functions your code is calling and which values are stored in your variables.

Terminal

Terminal allows you to run commands as described in Chapter 4 and Chapter 7. You can control your BeagleBone directly from the web browser, meaning that you can update or install new software, move files, and perform other commands. By default, you’re logged in as root, so you have full access to all commands that can be performed on your board.

Be careful when you are logged in as root! As the administrator — or, as the Linux community usually calls it, superuser — you have the permissions to execute commands that would actually mess up the BeagleBone. Refer to Chapter 4 for more on the root user.

Creating a folder and .js file

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.

A new folder is created inside the cloud9 folder.

2. Name the new folder Projects.

The new folder is named Projects because that’s where all projects in future chapters will be stored. Naturally, you can name yours whatever you want.

3. Right-click the Projects folder and choose New File from the shortcut menu.

This step creates a new file inside your Projects folder.

4. Name your file blink.js.

Your file must end with the extension .js (JavaScript) because it will run a JavaScript script.

The result should be similar to Figure 7-3.

Figure 7-3: Projects folder and a new file called blink.js.

Blinking an Onboard LED with BoneScript

This section shows you how to write your first script from scratch to blink an onboard LED. There’s a popular saying in the digital electronics world: If you can blink an LED, you can do anything. It’s true. The difference between controlling an LED to controlling, say, the outlet that controls your toaster is almost nonexistent. Don’t underestimate this project just because it’s a simple one.

If you followed the instructions in the preceding sections, at this moment you have your first folder and a .js file created.

When you get done with writing the program in this section, it will look like this:

/*
Blink
Turns an onboard LED on and off continuously,
with intervals of 1 second.
*/
// Load BoneScript module
var b = require('bonescript');
// Create a variable called led, which refers to the onboard USR3 LED
var led = "USR3";
// Initialize the led as an OUTPUT
b.pinMode(led, b.OUTPUT);
// Create a variable called state, which stores the current state of the LED.
var state = b.LOW;
// Set the LED as LOW (off)
b.digitalWrite(led, state);
// Execute the toggle function every one second (1000 milliseconds)
setInterval(toggle, 1000);
// Function that turns the LED either HIGH (on) or LOW (off)
// depending on the parameter state.
function toggle() {
if(state == b.LOW) state = b.HIGH; // if the LED is LOW (off), change the state to HIGH (on)
else state = b.LOW; // otherwise, if the LED is HIGH (on), change the state to LOW (off)
b.digitalWrite(led, state); // write the new state value to the led pin, turning the led on or off
}

This script has only a few lines of code, which you can divide, like so:

· Commenting

· Loading the BoneScript module

· Creating variables

· Configuring pins

· Setting the default pin state

· Setting an interval

· Creating a function

The following sections describe these groups of code in more detail. Follow along and write the snippets of code to your blink.js file.

Commenting

The script starts as follows:

/*
Blink
Turns an onboard LED on and off continuously,
with intervals of 1 second.
*/
// Load BoneScript module

This group of code is a series of comments. Comments are plain English — or some other language — that explains how the code works. Anything designated as a comment is ignored and won’t interfere with your code.

It’s important that you use comments frequently so that other people who read your code understand what you’re trying to do. Comments are also helpful for reminding yourself what your code did when you open the file a few months later. They’re easily the leading tools for organization.

There are two types of comments:

· Single-line: The // symbol indicates that anything that follows in that line should be ignored.

· Multiple-line: Any text between the /* and */ symbols is a comment written across multiple lines. It’s a good practice to start a script with multiple-line comments that include the script name, a brief explanation of what the code does, and some information about the author.

Loading the BoneScript module

Following is the first line of code that runs:

var b = require('bonescript');

You need to type this line every time you work with BoneScript because it loads the BoneScript module into your script in an object — called b in this case. An object is a combination of properties, and a property is an association between a name and a value. You control your BeagleBone by changing the values of the object you created.

Creating variables

The next line creates another variable:

// Create a variable called led, which refers to the onboard USR3 LED
var led = "USR3";

This line creates a variable called led to store the string "USR3" that refers to your onboard USR3 LED. A string is a collection of characters, words, and phrases, written between quotation marks.

JavaScript is case-sensitive. If you define led as your variable, you always need to type led, because LeD, LED, and Led are different.

Configuring pins

You need to initialize the LED as an output:

// Initialize the led as an OUTPUT
b.pinMode(led, b.OUTPUT);

To configure a pin to act as an output or input, you use the function pinMode(), which takes two parameters:

pinMode(<GPIO>, <mode>)

The two parameters are

· GPIO: The string of the pin you want to define — in this case, USR3, which is defined as led.

· mode: This argument sets the GPIO as an OUTPUT or as an INPUT. An LED is always an OUTPUT.

This function can take four more parameters — mux, pullup, slew, and callback — but they’re optional, and we don’t use them in the following examples.

Setting the default pin state

Create a variable called state, and set the default state to your LED:

// Create a variable called state, which stores the current state of the LED.
var state = b.LOW;
// Set the LED as LOW (off)
b.digitalWrite(led, state);
// Execute the toggle function every one second (1000 milliseconds)

You use the digitalWrite() function to write HIGH or LOW to your GPIO:

digitalWrite(<GPIO>, <value>, [callback])

This function takes three parameters:

· GPIO: Define the string of the pin you want to define. You want to change the led state.

· value: Set as HIGH or LOW. By default, you want the LED turned off.

· callback: Call a function upon completion. This parameter is optional, and even though you don’t need it for this example, you use it frequently when programming in BoneScript.

Setting an interval

The following line is executed every second:

// Execute the toggle function every one second (1000 milliseconds)
setInterval(toggle, 1000);

To toggle the LED on and off every second, you use a function called setInterval():

setInterval(<callback>, <milliseconds>)

The two parameters of this function are:

· callback: Calls a function upon completion. In this example, it executes the toggle() function.

· milliseconds: Sets the length of time between executions in milliseconds. In this case, the length of time is 1000 milliseconds (1 second).

Creating a function

This section is the most important part of your code, because it’s when you create the toggle() function that turns your LED on or off:

function toggle() {
if(state == b.LOW) state = b.HIGH; // if the LED is LOW (off), change the state to HIGH (on)
else state = b.LOW; // otherwise, if the LED is HIGH (on), change the state to LOW (off)
b.digitalWrite(led, state); // write the new state value to the led pin, turning the led on or off
}

Functions are great ways to organize your code. If you want to do something multiple times, instead of repeating your whole code several times, you create a separate function that you can call and execute any time. This is how you create a new function:

function toggle() {
// Your code goes here

}

Inside the curly braces, you can type what you want your code to do. In this example, you want to see whether the state variable is LOW, which means that the LED is off, so you change the state variable to HIGH. If the LED is HIGH, change state to LOW:

if(state == b.LOW) state = b.HIGH; // if the LED is LOW (off), change the state to HIGH (on)
else state = b.LOW; // otherwise, if the LED is HIGH (on), change the state to LOW (off)

When setting the value of a variable, you use a single equal sign, such as state = b.HIGH. When you want to check for the value of a variable, as in an if statement, you use two equal signs, as in if(state == b.LOW).

When you know the next state of your LED, you need to use the function digitalWrite() again to change the pin from LOW to HIGH or vice versa, according to the value stored in the state variable:

b.digitalWrite(led, state); // write the new state value to the led pin, turning the led on or off

Running the script

Before you can run your script, you need to save it. Simply press Ctrl+S or Cmd+S and then click the green Run button at the top of the screen. You should see your USR3 LED blinking every second.

After your script has run for a while, you can stop your program by clicking the Stop button.

If you click the Run button and nothing happens to your board, you’re probably running the script in debugger mode. To turn off debugger mode, click the little bug icon shown in Figure 7-4.

Figure 7-4: Turning off debugger mode.

Blinking More LEDs with BoneScript

In this section, you see how to design a circuit to introduce a physical LED to the blinking on-board LEDs.

Grab your BeagleBone, a Mini USB cable, a computer, a breadboard, an LED, and a 220 Ω or 470 Ω resistor. That’s everything you need for this section.

Wiring the circuit

Before you start wiring your circuit, make sure that your BeagleBone is disconnected from power.

Follow these steps to wire your circuit as shown in Figure 7-5:

1. Connect the BeagleBone’s ground (GND) pin (pins 1 and 2 on both headers) to the breadboard’s negative track.

2. Use a jumper to connect a BeagleBone pin to a vertical row on your breadboard.

This example uses pin 14 on the P9 header.

3. Connect a 220 Ω or 470 Ω resistor to the jumper you pulled from P9_14.

Without a resistor, an LED burns up easily. A 220 Ω or 470 Ω resistor should drop enough voltage without reducing the LED’s brightness. If the LED is too dim, use a 220 Ω resistor rather than a 470 Ω resistor.

4. Connect the LED’s negative leg (the cathode, which is usually the shorter leg) to ground, and the positive leg (the anode) to the resistor.

Figure 7-5: Pin P9_14 attached to an LED and a resistor.

Opening the blinked.js demo

In this section, you don’t write code, as there is a built-in demo that does just what you want. Follow these instructions to open the demo:

1. Connect your BeagleBone to your computer with a Mini USB cable.

2. Type 192.168.7.2:3000 in the address bar.

This text loads the Cloud9 IDE.

3. Click the folder demos in the workspace.

4. Double-click the blinked.js file.

The file opens, as shown in Figure 7-6.

This code is similar to the code in the “Blinking an onboard LED with BoneScript” section, but it adds a few more concepts, such as arrays and loops, which are covered in the following sections.

Figure 7-6: Cloud9 IDE with demo file blinked.js open.

Loading a module

When you’re programming with BoneScript, the following is always your first line of code:

var b = require('bonescript');

Creating an array

With an array, you can store multiple values in a single variable:

var leds = ["USR0", "USR1", "USR2", "USR3", "P9_14"];

You could create five variables to store all those strings:

var led0 = "USR0";
var led1 = "USR1";
var led2 = "USR2";
var led3 = "USR3";
var led4 = "P9_14";

An array makes your code look nicer and your variables more accessible. They are also very useful to use in loops, which are covered in the next section. If you want to access the elements of your array, such as the "USR0"string, you need to type leds[0]. Here’s how it works:

leds[<index>]

The first element in an array is indexed as 0, the second element is stored in the index 1, and so on.

Creating a loop

You use a for loop when you have a snippet of code that you want to repeat several times:

for(var i in leds) {
b.pinMode(leds[i], b.OUTPUT);
}

That for loop goes through all the LED pins — the ones stored in the leds array — and set them as outputs. You could take another approach by configuring the LEDs as outputs if you repeat the code five times:

b.pinMode(leds[0], b.OUTPUT);
b.pinMode(leds[1], b.OUTPUT);
b.pinMode(leds[2], b.OUTPUT);
b.pinMode(leds[3], b.OUTPUT);
b.pinMode(leds[4], b.OUTPUT);

As you can see, with a for loop, your code looks more organized and less repetitive. Using for loops may seem to add complexity, but imagine having to set up 30 outputs without using a loop.

Setting the default pin state

In this section, you set all pins to LOW as default. The following line creates a variable that stores the current state:

var state = b.LOW;

Then you use another for loop to go through all your five LEDs and turn them off with the digitalWrite() function:

for(var i in leds) {
b.digitalWrite(leds[i], state);
}

Executing the toggle() function

Using a setInterval() function allows you to call the toggle() function every second:

setInterval(toggle, 1000);

The toggle() function does exactly what it does in the “Creating a function” section: blinks an onboard LED. But now you’re using a for loop to change the state of all five LEDs to HIGH or LOW, according to the value stored in the state variable:

function toggle() {
if(state == b.LOW) state = b.HIGH;
else state = b.LOW;
for(var i in leds) {
b.digitalWrite(leds[i], state);
}
}

Running the script

At this point, if you’ve completed all the preceding sections, you should have your circuit wired and a window with the blinked.js script open.

You don’t need to save your script and delete comma because you haven’t edited your code.

Simply click the Run button, and watch all four USR LEDs and the LED blinking at the same time (see Figure 7-7)!

Figure 7-7: Demo blinked.js running on a BeagleBone Black.

If your USR LEDs are blinking but the physical LED isn’t, you may have wired something wrong. Placing the LED in reverse is quite often the problem. Reread the instructions to confirm that you set things up properly.


More on BoneScript

Chapter 8 covers more BoneScript projects, featuring different electrical components and more BoneScript functions, but if you want to take things even further, check the BoneScript Library page on the official website: http://beagleboard.org/Support/BoneScript. There, you can find more information about BoneScript functions and other project examples. You can also check Chapter 18 to discover more about this powerful programming language for the BeagleBone.