Hands-On Robotics with JavaScript

5 (1 reviews total)
By Kassandra Perch
  • Instant online access to over 8,000+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Setting Up Your Development Environment

About this book

There has been a rapid increase in the use of JavaScript in hardware and embedded device programming. JavaScript has an effective set of frameworks and libraries that support the robotics ecosystem.

Hands-On Robotics with JavaScript starts with setting up an environment to program robots in JavaScript. Then, you will dive into building basic-level projects such as a line-following robot. You will walk through a series of projects that will teach you about the Johnny-Five library, and develop your skills with each project. As you make your way through the chapters, you’ll work on creating a blinking LED, before moving on to sensors and other more advanced concepts. You will then progress to building an advanced-level AI-enabled robot, connect their NodeBots to the internet, create a NodeBots Swarm, and explore MQTT.

By the end of this book, you will have gained hands-on experience in building robots using JavaScript

Publication date:
August 2018
Publisher
Packt
Pages
214
ISBN
9781789342055

 

Chapter 1. Setting Up Your Development Environment

Welcome! This book is designed to get you started with writing robotics code in JavaScript using the Raspberry Pi, Node.js, and the Johnny-Five framework. This chapter will fill in the details of what the Raspberry Pi is and how we're going to use it, and will also help you get your development environment ready. 

The following topics will be covered in this chapter:

  • What is the Raspberry Pi
  • How we will use the Raspberry Pi
  • Installing the operating system
  • Setting up SSH and hardware interfaces
  • Installing Node.js
  • Installing Johnny-Five and Raspi-IO
 

Technical requirements


In order to get started, you'll need the following:

  • A Raspberry Pi 3: Either the original or model B is fine. 
  • A power supply: Plugging the Raspberry Pi into a USB port on your computer can cause serious issues because it cannot supply enough power to allow the Raspberry Pi to function properly, so you'll need a proper wall wart power supply.
  • MicroSD card: This needs to have at least 8 GB to hold the Raspbian OS and the code we're going to write. You'll also need a way to write to the SD card from your computer—either a full SD card adapter or a USB card reader.
  • A PC9685 GPIO expansion board: There are expansion boards that require assembly on Adafruit (https://www.adafruit.com/product/815), but if you're not confident in your soldering, then there are plenty of preassembled ones available on Amazon if you search for PC9685.
  • Text editor: Your code editor will be fine; we just need to edit a few files on the SD card once we've burned the OS image onto it.

If this is your first foray into a hardware project, I suggest getting a kit that contains at least the following items, as it will help you finish many of the projects in this book, and will provide you with the parts to create your own designs:

  • Pi Cobbler
  • Resistors
  • LEDs
  • A servo
  • A motor
  • Buttons
  • Other sensors and peripherals

The following are some good examples of these items (at the time of writing):

 

What is the Raspberry Pi?


So, now you've got this green, credit-card-sized object with a bunch of ports that you recognize, and a bunch of pins, as shown in the following diagram. You can see some chips, and some parts you might not recognize. Before we talk about the power contained in this rather inconspicuous board, we need to clear up some vocabulary that we'll be using throughout the book:

 

Microcontrollers

Microcontroller is a term that encapsulates a bunch of devices. It's a term used to describe a device that contains a processor, memory, and input/output peripherals (or ways to interact with those peripherals) that is meant for a particular type of task. One extremely common microcontroller is the Arduino Uno, and the Raspberry Pi technically falls into this category as well.

 

General-Purpose Input/Output (GPIO) pins

Microcontrollers interface with devices such as sensors, LEDs, and buttons using electrical signals that are sent and received through pins designed for input and/or output signals. These pins can be broken into multiple subcategories, as we'll find out in subsequent chapters, but you can address them as GPIO pins as a whole. We'll use that abbreviation throughout the book.

Debian and Raspbian

Debian is a distribution of Linux that is considered extremely user friendly for those new to using Linux. It contains many utilities that are commonly used while working with Linux preinstalled, and is compatible with a lot of the peripherals that you would use with a computer, such as Wi-Fi cards and USB devices.

Raspbian is a modified version of Debian specifically designed to run on Raspberry Pi devices. There are drivers for the GPIO pins, USB Wi-Fi devices, and expansion slots on the Pi that allow you to attach a specific display and camera. 

There are two flavors of Raspbian—Raspbian Full and Raspbian Lite. Full has a graphical desktop with programs aimed at educational programming and development. Lite (which we will be using for the projects in this book) only has a command-line interface, but still has full functionality when it comes to Raspberry Pi peripherals. As of the time of writing, the current version of Raspbian is 4.14, nicknamed Stretch.

Johnny-Five and Raspi-IO

Back in 2012, Rick Waldron wrote a node-serialport program to operate an Arduino Uno with Node.js, and formed a library around it called Johnny-Five. Since then, the Johnny-Five library has grown to over 100 contributors, and can control over 40 platforms, including the Raspberry Pi! It can also control many kinds of sensors and peripherals that you can use to create the robotics project you've been dreaming of in Node.js!

One of the ways the Johnny-Five library has grown to support so many platforms is by creating what are called IO plugins. You create an IO plugin for each type of board you wish to control. For example, we will be installing and using the Raspi-IO plugin to use Johnny-Five with the Raspberry Pi.

 

What is great about this system is that the code you write in this book can be used on any other platform that Johnny-Five supports (you just need to change PIN numbers)! Writing code for Node.js botnets is much easier when you're using the same APIs for any devices you might use.

So, the Pi is technically a microcontroller...

Let's get back to the question of what the Raspberry Pi is. In short, it is a microcontroller. It has dozens of GPIO pins and can be used to interface with many physical peripherals in order to achieve specialized tasks. The low cost and small size allows the Raspberry Pi to be a versatile device, but the power involved allows you to use it for tasks that other microcontrollers may not pack the punch for.

...but it is also a computer!

An interesting fact about the Raspberry Pi is that, while it is a microcontroller, it can also be used as a fully fledged computer! While it certainly isn't the most powerful hardware, with full Raspbian installed, a Raspberry Pi attached to a monitor, keyboard, and mouse creates a great machine for kids and adults to learn programming on! The original intent of the Raspberry Pi was to create a low-cost educational machine to teach programming, and it exceeded every expectation in that regard. The fact that it's also a great microcontroller for the world of makers is a great bonus!

 

How we will use the Raspberry Pi


So, we've established that the Raspberry Pi is a very versatile and powerful machine for its size, but with so many options, it can be hard to figure out where to get started. Luckily, we have a plan that will walk you through your first Raspberry Pi and Johnny-Five projects so that you can keep up, but which will also empower you to build your way into advanced robotics projects.

 

Taking advantage of all that the Raspberry Pi has to offer!

The projects we will build will take advantage of the fact that the Raspberry Pi is both a microcontroller and a computer. We'll use the Linux operating system, via the Raspbian distribution, and leverage it to run our projects in Node.js. We'll also use Johnny-Five and Raspi-IO to leverage the GPIO of the Raspberry Pi in order to create robotics projects in a way that makes the code easy to understand and portable to many different hardware platforms.

Johnny-Five – letting us code hardware in Node.js

In the past, when you thought of robotics projects, it meant writing in C or C++, usually through the Arduino IDE and APIs. However, as microcontrollers have gotten more powerful, they are capable of running other programming languages, even scripting languages, such as subsets of Python and JavaScript.

And, of course, with computer/microcontroller hybrids, such as the Raspberry Pi, you're able to run stock Node.js, allowing you to create even advanced robotics projects without having to deal with any low-level languages. There are quite a few benefits to being able to code robotics projects in Node.js:

  • Event-based systems: In the Arduino and C/C++ level of robotics programming, you will need to check the state of everything through each iteration of a loop, and act accordingly. This can create monolithic functions and code paths. With Node.js and Johnny-Five, we can use event emitters and systems, which fit in surprisingly well as they can read sensors and interact with peripherals in the real world, where things take time. This will help you to organize code in a way that reflects the asynchronous way the world works.
  • Garbage collection/automatic memory management: While Arduino and C++ handle most memory management for you, programming in microcontrollers that use C requires strict memory management. While you may need to bear the resource constraints of the Raspberry Pi in mind from time to time, it is much easier than the days of 20K SRAM.
  • Using a language you already know: Instead of trying to remember the way things work in a new language, it will accelerate your learning in the field of electronics and robotics if you focus on learning fewer things at once. Using Node.js can help you focus on learning the wide and varied world of electronics, instead of adding on the extra work of remembering whether it's uint8_t or uint16_t.
 

Installing the operating system


In order to get started with Johnny-Five and the Raspberry Pi, we will need to set up the Raspbian operating system by burning it to a microSD card. Then, we'll need to edit some files on the SD card in order for the Raspberry Pi to boot with Wi-Fi and the ability to SSH in. Lastly, we'll need to boot up the Raspberry Pi and get some settings in place before finally installing Node.js, Johnny-Five, and Raspi-IO.

Downloading Raspbian Lite

The following steps will show you how to download Raspbian Lite:

  1. The first step is downloading the Raspbian Lite image so we can burn it to our microSD card. The best place to get the image from is https://www.raspberrypi.org/downloads/raspbian/, as shown in the following screenshot:

A screenshot of the Raspbian download page, with both Full and Lite download links

  1. Select RASPBIAN STRETCH LITE (or whichever version is the current one), which will replace the word STRETCH. Give yourself some time for this step to complete; although Raspbian Lite is much smaller than Raspbian Full, it is still several hundred megabytes, and can take time to download!

Note

If you're preparing to run a class, hackathon, or some other event using the Raspberry Pi and Raspbian, it's best to predownload it and place it on a flash drive to hand around, as conference and event Wi-Fi can be a bit slower than normal, or even drop in and out, so be prepared!

Burning the image to an SD card

Luckily, the tools for burning OS images to SD cards have evolved arcane command-line tools that can overwrite your computer's hard drive as easily as it can the SD card. My current favorite is called Etcher, and it can be downloaded for any platform at https://etcher.io/, as shown in the following steps:

  1. The free version is more than enough for our needs, so download and install it as you download Raspbian Lite.
  2. Once they are both downloaded, you'll want to place the micro SD card in your computer, either by placing it into a full-sized SD adapter and then into a slot on your computer, or by using a USB-to-micro-SD adapter. Whichever you use, make sure your computer can see the volume as a drive before continuing. Then, boot up Etcher. The following screenshot shows Etcher running on a Mac:

A screenshot of the Etcher program running on a Mac

  1. Once you see a window similar to the preceding screenshot, you'll need to select the Raspbian Lite image you just downloaded. You don't even need to unzip the .zip file—Etcher can handle that outright! Once you've selected the image, Etcher should select your micro SD card drive, so long as your machine can see it! Once you've ensured that the image and micro SD card drive are properly selected, hit Flash! to begin the process.

Note

Sometimes, with larger micro SD cards, you'll get a warning from Etcher about the drive being very large (this happens to me when I use 64 GB cards). This is to prevent you from overwriting your computer's hard drive. You can bypass the warning by going through a confirmation window—just be absolutely sure that your micro SD card drive is selected first!

A few minutes will pass as Etcher burns the image to your micro SD card, then verifies that it is present on the card. Once this is done, remove and reinsert the micro SD card so that your computer recognizes it as a drive again; the drive should be namedboot. We're not quite done editing the image files yet, so Etcher's polite attempt to eject the micro SD card drive needs to be ignored.

Editing files on the SD card

We need to edit and create some files on our Raspberry Pi's image in order to be able to access it with SSH when we turn on the Raspberry Pi. First, we'll set up the Wi-Fi using the following steps:

Note

If you're using an Ethernet cable and port to connect the Raspberry Pi to the internet, you can skip this step. If this doesn't get the Wi-Fi to work, you'll want to look at the information box under the section Booting up the Pi for troubleshooting steps and an alternative (if clunkier) way to set this up.

  1. In order to set up the Wi-Fi, you'll want to create a file in the root of the micro SD card drive called wpa_supplicant.conf that contains the following text:
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
    ssid="yourNetworkSSID"
    psk="yourNetworkPasswd"
}

 

 

  1. Replace yourNetworkSSID with the SSID of the Wi-Fi network you wish to connect to, and then replace yourNetworkPasswd with that Wi-Fi's network password.

Note

The Raspberry Pi's Wi-Fi chip can only connect to 2.4 GHz networks at the time of writing, so you need to make sure that you input a network that operates on that bandwidth or your Raspberry Pi will not be able to connect!

  1. After you've set up the Wi-Fi network, you'll want to tell the Raspberry Pi to allow you to SSH into it. To do this, you'll want to create a file called ssh in the same rootfolder as the wpa_supplicant.conf file. Make sure that the ssh file is empty and has no extension. When you're all done, the rootdirectory of the micro SD card drive will look similar to the following screenshot:

A list of files on the micro SD drive, once I've made my edits

Once this is all done, fully eject the microSD drive, take the microSD card and insert it into the Raspberry Pi. We're now ready to boot up the Raspberry Pi and start installing software.

Booting up the Pi

Once the micro SD card is inserted, plug your power source into your Raspberry Pi. A red and green LED should light up. The red LED should be solid—this is the power indicator. The green light will flicker on and off—this is the LED that indicates activity. The Raspberry Pi should take a maximum of a minute or so to boot up once you've plugged it in. Next, we'll SSH in. 

 

SSHing from a Linux or Mac

If you're on a Mac or Linux machine, you'll open up a Terminal and type the following:

ssh [email protected]

If you're successful, you'll see a question appear, asking about the authenticity of the host. Respond by typing yes and hitting Enter. You'll then be asked for a password, which is raspberry, as shown in the following screenshot: 

Successful SSH into a Raspberry Pi from a Mac Terminal

Once you've entered the password, you should see the following:

Successful login to a Raspberry Pi via SSH from a Mac

SSHing from Windows

In order to SSH from a Windows machine, you'll need to use a program called PuTTY. You can get it on https://putty.org/. But first, you'll want your Raspberry Pi's IP address. You'll need a monitor, an HDMI cable, and a USB keyboard. Once you have these, go through the following steps:

  1. Plug the monitor, HDMI cable, and USB keyboard into the Raspberry Pi before booting it up. Then plug in the power supply.
  2. When it prompts you for a username, type pi. When it asks for a password, enter raspberry. Once you are logged in, type ifconfig. You should see a lot of information appear.
  3. Look for the wlan0 section and the inet address under that heading. For the following output, the IP is 192.168.1.106, as shown in the following screenshot. Write this IP down. Then, you can unplug the display and the keyboard—you won't need them again:

Getting the IP address from the Terminal

  1. Once you have the IP address for your Raspberry Pi, you can boot up PuTTY. The window that opens is the configuration window, as shown in the following screenshot: 

The PuTTY configuration window

  1. Type the IP address that you obtained into the field labeled Host Name (or IP address) and click the Open button. You'll be asked about the authenticity of the host (only the first time you connect). Select Yes. Then enter Pi as the username and raspberry as the password when prompted. Once that's done, you should see the following:

Successful login to the Raspberry Pi with PuTTY

Now that everyone's logged in, let's set up our Raspberry Pi for our projects!

 

Setting up your password and hardware interfaces


Now that we have our Raspberry Pi connected to the Wi-Fi and we're SSHed in, we need to make a few changes before we install Node.js and get started with our coding.

First things first – change your password!

When you log in, your Raspberry Pi will warn you that having SSH enabled with the default username and password isn't very secure, and it's absolutely right! The first step is to change our password.

 

In order to do so, in your SSH window, type in passwd and hit Enter. You'll be prompted for your current password (raspberry) and a new password. Type in whatever you like (just don't forget it)! You'll be asked to confirm it, and voila! The new password is set, as shown in the following screenshot. Your Raspberry Pi will be much more secure:

Changing your Pi password

Updating the Raspberry Pi

Next, you'll make sure that the Raspberry Pi is updated and ready to go by running the following command:

sudo apt-get update && sudo apt-get upgrade

This will take a while, but it's worth it to make sure everything is properly updated.

Turning on the hardware interfaces

Next, we'll set up the Raspberry Pi so that our hardware code can run. Run the following command:

sudo raspi-config

You'll be greeted with a graphical menu with lots of different options, as shown in the following screenshot:

The raspi-config menu

You'll want to use the arrow keys to select Interfacing Options, and then select I2C and Yes to turn it on. Repeat for SPI, then use Tab to close the menu. When it prompts you to reboot, say Yes, then SSH back in, because you're ready to install Node.js, Johnny-Five, and Raspi-IO!

 

Installing Node.js, Johnny-Five, and Raspi-IO


So, now that our Raspbian OS is installed and set up, it's time to install Node.js (which comes bundled with npm), Johnny-Five, and Raspi-IO!

Installing Node.js and npm

In days past, you would have to compile the Node.js source on your Pi, to varying degrees of success because of the nonexistence of binaries for the ARM processor that Raspberry Pi uses. Luckily now, because of a rousing amount of third-party support in the past few years, you can easily download the binary from the https://nodejs.org/en/ website! But how are we going to do this from the command line of our Raspberry Pi? 

 

Detecting your version of ARM processor

If you're using the Raspberry Pi 3 Model B recommended by this book, you're most likely on ARM v8 (the Raspberry Pi 3 original is ARMv7, which is fine too!). But you should always double-check (doubly so if you're using a different Raspberry Pi, such as the Pi Zero or Pi 2/1 series). To check the ARM version on your Raspberry Pi, run the following in your SSH Terminal:

uname -m

You'll see a return message that looks like armv#, where # is a number (possibly followed by a letter). That number is what is important, because that number tells us which Node.js binary we will need. Once you have your ARM version, go through the following steps:

  1. Head to the Node.js download page at https://nodejs.org/en/download/, as shown in the following screenshot:

A snapshot of the Node.js binary download page

  1. Right-click on the ARM version link you need and copy the URL. Then, run the following in your Raspberry Pi's SSH Terminal:
wget <binary-download-url>

 

 

 

 

Replace <binary-download-url> (carats, too!) with the URL you copied from the Node.js download website. Once it's downloaded, we need to extract the archive using the following code:

tar -xvf node-v****-linux-armv**.tar.xz
  1. The asterisks will differ depending on the current LTS version of Node.js and your ARM version. The Raspberry Pi will spit out a lot of filenames to the console, then give you back your shell prompt. This means that the binaries have been extracted into your home folder. We need to place them into the /usr/local folder. To do that, run the following:
cd node-v****-linux-armv** 
sudo mv ./lib/* /usr/local/lib
sudo mv ./share/* /usr/local/share
  1. This will move all of the precompiled binaries to their new homes on your Raspberry Pi. Once this is done, run the following:
node -v
npm -v

You should see something like the following:

Successful Node.js installation results

  1. If that's all well and good, you now have Node.js and npm installed! Let's wrap this up with Johnny-Five and Raspi-IO! Note that you can absolutely clean up the binary downloads by running the following:
cd ~
rm -rf node-v**-linux-armv**
rm -rf node-v****-linux-armv**.tar.xz

 

 

 

 

 

 

Note

Some of you with more Debian experience may be asking, well, why can't we just useapt-get? The short answer is that the package with the name node was taken a very long time ago, and because that is the case, and because sudo apt-get install nodejs is outdated (at the time of writing, using this command will install v4 when we needv8+, if it installs Node.js at all), we need to download the binaries and move them ourselves.

Installing Johnny-Five and Raspi-IO

To install Johnny-Five, once you've made sure Node.js and npm are installed, run the following command:

npm i -g johnny-five raspi-io

This installs the libraries globally; you won't have to reinstall it every new project. And that's it! You're ready to start developing Node.js robotics projects on the Raspberry Pi with Johnny-Five!

 

Summary


It feels like a lot, but you've now completed everything you need to have a fully-fledged development environment for the projects in this book, and you've taken your first steps toward building robots with JavaScript. You've learned more about what the Raspberry Pi is and why we're using it, and how to get the operating system image ready to go!

 

Questions


  1. What is the common operating system for the Raspberry Pi that we'll be using in the projects in this book, and what Linux distribution is it based on?
  2. What does GPIO stand for?
  3. Who originally started the Johnny-Five project, and what did they use it to control?

 

  1. What command do you run on the Raspberry Pi to find out what ARM architecture it uses?
  2. Why is changing the default Raspberry Pi password important?
  3. What are two benefits of using JavaScript and Node.js for robotics code?
  4. Why do we have to download the Node.js binaries instead of using Raspbian's package manager?
 

Further reading


You can use the following sources for further reading relating to the topics covered in this chapter:

About the Author

  • Kassandra Perch

    Kassandra Perch is an open web developer and supporter. She began as a frontend developer and moved to server-side with the advent of Node.js and was especially enthralled by the advance of the NodeBots community. She travels the world speaking at conferences about NodeBots and the fantastic community around them.

    Browse publications by this author

Latest Reviews

(1 reviews total)
excelente, o aprendizado é muito grande!

Recommended For You

Book Title
Access this book and the full library for just $5/m.
Access now