CHAPTER 2
The BeagleBone Black Software

In this chapter, you are introduced to the Linux operating system and software tools that can be used with the BeagleBone. This chapter aims to ensure that you can connect to your BeagleBone and control it. By the end of this chapter you should be able to “blink” a system LED having followed a step‐by‐step guide that demonstrates how you can use Linux shell commands in a Linux terminal window. In this chapter, you are also introduced to a library of BeagleBone functions, called BoneScript, which can be used with Node.js and the Cloud9 integrated development environment to build code that flashes the same system LED.

Equipment Required for This Chapter:

  • BeagleBone Black board
  • Supplied USB cable (USB A male to mini‐USB A male)
  • Micro‐SD card (4 GB or greater; Class 10+) (optional)
  • Network infrastructure and cabling (optional)

Further details on this chapter are available at www.exploringbeaglebone.com/chapter2/

Linux on the BeagleBone

A Linux distribution is a publicly available version of Linux that is packaged with a set of software programs and tools. There are many different Linux distributions, which are typically focused on different applications. For example, high‐end server owners might install Red Hat Enterprise, Debian, or OpenSUSE; desktop users might install Ubuntu, Debian, Fedora, or Linux Mint. The list is endless, but at the core of all distributions is a common Linux kernel, which was conceived and created by Linus Torvalds in 1991.

In deciding on a Linux distribution to use for your embedded system platform, it would be sensible to choose one for which the following apply:

  • The distribution is stable and well supported.
  • There is a good package manager.
  • The distribution is lean and suited to a low storage footprint.
  • There is good community support for your particular device.
  • There is device driver support for any peripherals you wish to attach.

Linux Distributions

There are many different distributions of Linux for embedded system platforms, including expensive proprietary versions for real‐time programming. At their heart, they all use the mainline Linux kernel, but each distribution contains different tools and configurations that result in quite different user experiences. The main open‐source distributions used by the community on the BBB board include Debian, Ångström, Ubuntu, and Arch Linux.

Debian (contraction of Debbie and Ian!) is a community‐driven Linux distribution that has an emphasis on open‐source development. There is no commercial organization involved in the development of Debian; in fact, there is a formal social contract (tiny.cc/ebb201) that states that Debian will remain entirely free (as in software freedom). The Debian distribution is used for many of the practical steps in this book and is recommended as the distribution of choice for the BBB, as it is currently distributed with new BBB boards. In addition, Debian is used throughout this book as the distribution for the Linux desktop computer, as it provides excellent support for cross‐platform development through the Embedded Debian (Emdebian) project (see www.debian.org).

Ångström is a stable and lean Linux distribution that is widely used on embedded systems. The team of developers behind Ångström is experienced in customizing Linux distributions for embedded devices such as set‐top boxes, mobile devices, and networking devices. Impressively, Ångström can scale down to devices with only megabytes of flash storage. Ångström makes extensive use of BusyBox, a multicall binary (a single executable that can do the job of many) used to create a compact version of command‐line utilities that are found on Linux systems. Many of my YouTube videos use Ångström, as it was the primary distribution for the BeagleBone for quite some time.

Ubuntu is very closely related to Debian; in fact, it is described on the Ubuntu website (www.ubuntu.com) as follows: “Debian is the rock upon which Ubuntu is built.” Ubuntu is one of the most popular desktop Linux distributions, mainly because of its focus on making Linux more accessible to new users. It is easy to install and has excellent desktop driver support, and there are binary distributions available for the BBB.

Arch Linux is a lightweight and flexible Linux distribution that aims to “keep it simple,” targeting competent Linux users in particular by giving them complete control and responsibility over the system configuration. There are pre‐built versions of the Arch Linux distribution available for the BBB; however, compared to the other distributions, it currently has less support for new Linux users with the BBB platform (see www.archlinux.org).

Communicating with the BBB

When you are ready to try out your BBB, the first thing you should do is connect it to your desktop computer using the supplied USB lead. After you apply power, the BBB will connect to the desktop in USB client mode. Once connected and discovered, your file manager, such as Windows Explorer, will display the contents of the BBB’s FAT partition, as shown in Figure 2-1. The BeagleBoard.org team has put together a really excellent HTML guide on getting started with the BBB. You should double‐click the START.htm file to display the guide, which is illustrated in Figure 2-1, within a web browser.

images

Figure 2-1 The BBB START.htm guide to setting up your BBB

Installing Drivers

Follow the steps in the guide displayed in Figure 2-1, which mainly involve browsing to the Drivers folder and installing the correct version. Under Windows you may receive Windows driver certification warnings on multiple occasions. Continue with the process and do not click Cancel. Under Windows 8, you may have to restart the computer in a troubleshooting mode in order to disable “driver signature enforcement”—please see the chapter web page. Once this process is complete, several new devices are available on your desktop computer. For example, you will now have the following devices:

  • Access to the FAT partition of the BBB (like a USB memory key).
  • Serial access to the BBB using a new Gadget Serial driver.
  • A Linux USB Ethernet/RNDIS Gadget (for Internet‐over‐USB). RNDIS stands for Remote Network Driver Interface Specification.

The Windows Device Manager displays these new devices. Similar steps for Linux and Macintosh desktop computers are available in the startup guide. These new devices can be used to connect to the BBB.

Network Connections

There are three main ways to connect to and communicate with the BBB over the network, each with its own advantages and disadvantages. The first way is to use Internet‐over‐USB, which creates a “private” virtual LAN using a single USB cable. The second way is to use regular Ethernet, and the third is to use an Ethernet crossover cable. Connecting to the BBB over a network can be a stumbling block for beginners. It is usually straightforward if you are working at home with control of your own network; however, complex networks, such as those in universities, can have multiple subnets for wired and wireless communication. In such complex networks, routing restrictions may make it difficult, if not impossible, to connect to the BBB over regular Ethernet. All three methods are suitable for connecting your BBB to Windows, Macintosh, and Linux desktop machines.

Internet‐over‐USB

The standard BBB distributions provide support for Internet‐over‐USB using the Linux USB Ethernet/RNDIS Gadget device. For new users, and for users within complex network infrastructures, this is probably the best way to get started with the BBB. For this setup you only need the BBB board, the supplied USB cable, and access to a desktop computer, ideally with administrator access levels. Table 2-1 describes the advantages and disadvantages of Internet‐over‐USB for connecting to the BBB.

Table 2-1 Advantages and Disadvantages of BBB Internet‐over‐USB

ADVANTAGES DISADVANTAGES
Provides a good stable network setup for beginners. Without significant effort, you are limited to a single BBB per desktop.
When you do not have access to, or control of, network infrastructure hardware you can still connect the BBB to the Internet. Network sharing configuration can be difficult, especially on Macintosh desktop computers. Additional configuration must also be performed on the BBB.
Power is supplied by your desktop machine over USB. Your desktop machine must be running in order to transfer data to/from the Internet.

For example, if you fully installed the BBB drivers under Windows, you should now have a new network connection (Start ➢ type view Network Connections). Figure 2-2 captures a typical Network Connections window under Windows. In this case, “Local Area Connection 9” is the Linux USB Ethernet/RNDIS Gadget. The desktop computer remains connected to your regular LAN, which provides access to the Internet, and to a new “private” LAN that contains only your desktop computer (192.168.7.1) and your BBB (192.168.7.2). You can open a web browser and connect to the BBB’s web server by typing 192.168.7.2 in the address bar, as illustrated in Figure 2-2.

images

Figure 2-2 Windows Network Connections with Internet‐over‐USB connection LAN 9, and a web browser connection

At this point you can connect to the BBB’s web server using a web browser, so you have a fully functional private network; however, you may also want the BBB to have full direct access to the Internet so that you can download files and update Linux software directly on the BBB. To do this, you need to share your main network adapter, so that traffic from the BBB can be routed through your desktop machine to the Internet. For example, under Windows use the following steps:

  1. Choose your desktop/laptop network adapter that provides you with Internet access. Right‐click it and choose Properties.
  2. In the dialog that appears, as shown on the left‐hand side of Figure 2-3, click the Sharing tab at the top and enable the option Allow other network users  .  .  .
  3. In the drop‐down list, choose your BBB private LAN (e.g., referring back to Figure 2-2, this is “Local Area Connection 9”). Click OK.
  4. Right‐click the BBB private LAN (e.g., LAN 9) and select Properties.
  5. Double‐click Internet Protocol Version 4. In this dialog, select Obtain an IP address automatically and enable Obtain DNS server address automatically (see Figure 2-3 on the right‐hand side).
  6. Click OK and then OK again to save the configurations.
images

Figure 2-3 Configuring the Network Connection Sharing Properties under Windows

If all goes well, you will not have noticed any difference at this point and you should be able to reload the web page that is shown in Figure 2-2. The impact of the last two steps can only be appreciated when you open a terminal connection to the BBB. A link to a video guide for configuring network sharing for Mac OS X is available at tiny.cc/ebb202.

Regular Ethernet

By “regular” Ethernet, I mean connecting the BBB to a network in the same way that you would connect your desktop computer using a wired connection. For the home user and power user, regular Ethernet is probably the best solution for networking and connecting to the BBB. Table 2-2 lists the advantages and disadvantages of using this type of connection. The main issue is the complexity of the network—if you understand your network configuration and have access to the router settings, then this is by far the best configuration. If your network router is distant from your desktop computer, you can use a small network switch, which can be purchased for as little as $10–$20. Alternatively, you could purchase a wireless access point with integrated multiport router, for $25–$35. This is useful for wireless BBB applications and also for extending the range of your wireless network.

Table 2-2 Regular BBB Ethernet Advantages and Disadvantages

ADVANTAGES DISADVANTAGES
You have full control over IP address settings and dynamic/static IP settings. You might need administrative control or knowledge of the network infrastructure.
You can connect and interconnect many BBBs to a single network (including wireless devices). The BBB needs a source of power (which can be a mains‐powered adapter).
The BBB can connect to the Internet without a desktop computer being powered on. The setup is more complex for beginners if the network structure is complex.

The first challenge with this configuration is finding your BBB on the network. By default, the BBB is configured to request a Dynamic Host Configuration Protocol (DHCP) IP address. In a home network environment this service is usually provided by a DHCP server that is running on the integrated Modem‐Firewall‐Router‐LAN (or some similar configuration) that connects the home to an Internet Service Provider (ISP).

DHCP servers issue IP addresses dynamically from a pool of addresses for a fixed time interval, called the lease time, which is specified in your DHCP configuration. When this lease expires, your BBB is allocated a different IP address the next time it connects to your network. This can be frustrating, as you may have to search for your BBB on the network again. It is possible to set the IP address of your BBB to be static, so that it is fixed at the same address each time the board connects. Wireless connections and static IP connections are discussed in Chapter 10.

There are a few different ways to find your BBB’s dynamic IP address:

  • Use a web browser to access your home router (often address 192.168.1.1, 192.168.0.1, or 10.0.0.1). Log in and look under a menu such as “Status” for the “DHCP Table.” You should see an entry that details the allocated IP address, the physical MAC address, and the lease time remaining for a device with host name “beaglebone,” for example:

    Leased Table
    IP Address	MAC Address Client	Host Name	Register Information
    192.168.1.116	c8:a0:30:c0:6b:48	beaglebone	Remains 23:59:51
  • Use a port‐scanning tool like nmap under Linux or the Zenmap GUI version that is available for Windows (see tiny.cc/ebb203). The command nmap ‐T4 ‐F 192.168.1.* will scan for devices on a subnet. You are searching for an entry that has three or four open ports (e.g., 22 for SSH, 80 for the BBB guide, 8080 for the Apache web server, and 3000 for the Cloud 9 IDE). It may also identify itself with Texas Instruments.
  • You could use a Serial‐over‐USB connection to connect to the BBB and type ifconfig to find the IP address. The address is the “inet addr” associated with the eth0 adapter. This is discussed shortly.

Once you have the IP address, you can test that it is valid by entering it in the address bar of your web browser—192.168.1.116 in the example above. Your browser should display the page that is shown in Figure 2-2.

Ethernet Crossover Cable

An Ethernet crossover cable is a cable that has been modified to enable two Ethernet devices to be connected directly together, without the need for an Ethernet switch. It can be purchased as a cable or as a plug‐in adapter. If you have an RJ-45 crimping tool, you could even make one by swapping the transmit pair (green, white/green) with the receive pair (orange, white/orange) on one end of a 10Base‐T or 100Base‐TX Ethernet cable (the Gigabit Ethernet cable is different). Many desktop machines have an automatic crossover detection function (Auto‐MDIX) that enables a regular Ethernet cable to be used. Similar to the Internet‐over‐USB network configuration, this connection type can be used when you do not have access to network infrastructure and/or where the Internet‐over‐USB network configuration is not working correctly. Table 2-3 describes the advantages and disadvantages of this connection type.

Table 2-3 Crossover Cable Network Advantages and Disadvantages

ADVANTAGES DISADVANTAGES
When you do not have access to network infrastructure hardware you can still connect to the BBB. If your desktop machine has only one network adapter then you will lose access to the Internet. It is best used with a device that has multiple adapters.
BBB may have Internet access if the desktop has two network adapters. BBB still needs a source of power (can be a mains‐powered adapter).
Provides a reasonably stable network setup. Requires a specialized Ethernet crossover cable or adapter, unless your desktop has Auto‐MDIX.

Communicating with the BBB

Once you have networked the BBB, the next thing you might want to do is communicate with the BBB. You can connect to the BBB using either a serial connection over USB, USB‐to‐TTL, or a network connection, such as that just discussed. The network connection should be your main focus, as that type of connection provides your BBB with full Internet access. The serial connection is generally used as a fallback connection when problems arise with the network connection. As such, you may skip the next section, but the information is here as a reference for when problems arise.

Serial Connection over USB

If you installed the device drivers for the BBB in the previous section, the Gadget Serial device will allow you to connect to the BBB directly using a terminal emulator program. Serial connections are particularly useful when the BBB is close to your desktop computer and connected via the USB cable. It is often a fallback communications method when something goes wrong with the network configuration or software services on the BBB.

To connect to the BBB via the serial connection, you need a terminal program. Several third‐party applications are available for Windows, such as RealTerm (tiny.cc/ebb204) and PuTTY (www.putty.org). PuTTY is also used in the next section. Most distributions of desktop Linux include a terminal program (try Ctrl+Alt+T or use Alt+F2 and type gnome‐terminal under Debian). A terminal emulator is included by default under Mac OS X (e.g., use screen /dev/tty.usbmodemfa133 115200).

To connect to the BBB over the USB serial connection you need to know some information:

  • Port number: You can find this by opening the Windows Device Manager and searching under the Ports section. Figure 2-4 captures an example Device Manager, where the Gadget Serial device is listed as COM20. This will be different on different machines.
  • Speed of the connection: By default you need to enter 115,200 baud to connect to the BBB.
  • Other information you may need for other terminal applications: Data bits = 8; Stop bits = 1; Parity = none; and, Flow control = XON/XOFF.
images

Figure 2-4 Windows Device Manager and opening a PuTTY serial connection to the BBB

Save the configuration with a session name so that it is available each time you wish to connect. After you click Open, it is important that you press Enter when the window appears. When connecting to Debian, you should see the following output:

   Debian GNU/Linux 7 beaglebone ttyGS0
   default username:password is [debian:temppwd]
   The IP Address for usb0 is: 192.168.7.2
   beaglebone login:

which allows you to log in with username root. There is no password by default (just press Enter).

On a Linux desktop computer you can install the screen program and connect to the serial‐over‐USB device with the commands:

   molloyd@debian:~$ sudo apt‐get install screen
   molloyd@debian:~$ screen /dev/ttyUSB0/ 115200

Serial Connection with the USB‐to‐TTL 3.3 V Cable

For this serial connection type you need the specialized cable that is described in Chapter 1. Find the COM port from Windows Device Manager that is associated with a device called “USB Serial Port.” Plug in the cable to the 6‐pin connector beside the P9 header (black lead to the white dot/J1). You can then open a serial connection using PuTTY (115,200 baud) and you will see the same BBB login prompt as above. However, when you reboot the board you will also see the full console output as the BBB boots, which begins with:

   U-Boot	2013.10-00016-ga0e6bc6 (Feb 25 2014 - 10:27:54)
   I2C:	ready
   DRAM:	512 MiB . . .

This is the ultimate fallback connection, as it allows you to see what is happening during the boot process, which is described in the next chapter.

Connecting through Secure Shell (SSH)

Secure Shell (SSH) is a very useful network protocol for secure encrypted communication between network devices. You can use an SSH terminal client to connect to the SSH server that is running on port 22 of the BBB, which allows you to do the following:

  • Log in remotely to the BBB and execute commands.
  • Transfer files to and from the BBB using the SSH File Transfer Protocol (SFTP).
  • Forward X11 connections, which allows you to perform virtual network computing (covered in Chapter 11).

By default, the BBB Linux distributions run an SSH server (sshd on Debian and Dropbear on Ångström) that is bound to port 22. There are a few advantages in having an SSH server available as the default method by which you log in remotely to the BBB. In particular, you can open port 22 of the BBB to the Internet using the port forwarding functionality of your router. Please ensure that you set a password on the root user account before doing this. You can then remotely log in to your BBB from anywhere in the world if you know the BBB’s IP address. A service called dynamic DNS that is supported on most routers allows your router to register its latest address with an online service. The online service then maps a domain name of your choice to the latest IP address that your ISP has given you. The dynamic DNS service usually has an annual cost, for which it will provide you with an address of the form dereksBBB.servicename.com.

Secure Shell Connections using PuTTY

PuTTY (www.putty.org) was mentioned earlier as a way of connecting to the BBB using serial‐over‐USB. PuTTY is a free, open‐source terminal emulator, serial console, and SSH client that you can also use to connect to the BBB over the network. PuTTY has a few very useful features:

  • It supports serial and SSH connections.
  • It installs an application called psftp that enables you to transfer files to and from the BBB over the network from your desktop computer.
  • It supports SSH X11 forwarding, which is required in Chapter 11.

Figure 2-5 captures the PuTTY Configuration settings: Choose SSH as the connection type; enter the IP address for your BBB (192.168.7.2 if you are using Internet‐over‐USB); accept Port 22 (the default); and then save the session with a useful name for future use. Click Open and log in using your username and password. You may get a security alert that warns about man‐in‐the‐middle attacks, which may be a concern on insecure networks. Accept the fingerprint and continue. Mac OS X users can run the Terminal application with very similar settings (e.g., ssh ‐X [email protected]).

images

Figure 2-5 PuTTY SSH Configuration settings beside an open SSH terminal connection

You will see the basic commands that can be issued to the BBB later in this chapter, but first it is necessary to examine how you can transfer files to and from the BBB.

Chrome Apps: Secure Shell Client

The Chrome web browser has support for Chrome Apps—applications that behave like locally installed (or native) applications but are written in HTML5, JavaScript, and CSS. Many of these applications use Google’s Native Client (NaCl, or Salt!), which is a sandbox for running compiled C/C++ applications directly in the web browser, regardless of the OS. The benefit of NaCl is that applications can achieve near‐native performance levels, as they can contain code that uses low‐level instructions.

There is a very useful “terminal emulator and SSH client” Chrome App available. Open a new tab on the Chrome browser and click the Apps icon. Go to the Chrome Web Store and search the store for “Secure Shell.” Once it is installed, it will appear as the Secure Shell App when you click the Apps icon again. When you start up the Secure Shell App, you will have to set the connection settings as in Figure 2-5, and the application will appear as in Figure 2-6.

images

Figure 2-6 The SSH Chrome App

Transferring Files Using PuTTY/psftp over SSH

The PuTTY installation also includes file transfer protocol (ftp) support that enables you to transfer files to and from the BBB over your network connection. You can start up the psftp (PuTTY secure file transfer protocol) application by typing psftp in the Windows Start command text field.

At the psftp> prompt you can connect to the BBB by typing open [email protected] (e.g., the BBB address for Internet‐over‐USB). Your desktop machine is now referred to as the local machine and the BBB is referred to as the remote machine. When you issue a command, you are typically issuing it on the remote machine. After connecting you are placed in the home directory of the user account that you used. Therefore, under the BBB Debian distribution, if you connect as root you are placed in the /root directory.

To transfer a single file c: emp est.txt from the local desktop computer to the BBB you can use the following steps:

   psftp: no hostname specified; use "open host.name" to connect
   psftp> open [email protected]
   Using username "root". Debian GNU/Linux 7
   Remote working directory is /root
   psftp> lcd c:	emp
   New local directory is c:	emp
   psftp> mkdir test
   mkdir /root/test: OK
   psftp> put test.txt
   local:test.txt => remote:/root/test.txt
   psftp> dir test.*
   Listing directory /root
   -rw-r--r-- 1 root root 6 May 15 04:17 test.txt

Commands that are prefixed with an l refer to commands issued for the local machine, e.g., lcd (local change directory) or lpwd (local print working directory). To transfer a single file, the put command is issued, which transfers the file from the local machine to the remote machine. The get command can be used to transfer a file in reverse. To “put” or “get” multiple files you can use the mput or mget commands. Use help if you have forgotten a command.

If you are using a Linux client machine, you can use the command sftp instead of psftp. Almost everything else remains the same. The sftp client application is also installed on the BBB distribution by default, so you can reverse the order of communication, that is having the BBB act as the client and another machine as the server.

Here are some useful hints and tips with the psftp/sftp commands:

  • mget ‐r * will perform a recursive get of a directory. This is very useful if you wish to transfer a folder that has several subfolders. The ‐r option can also be used on get, put, and mput commands.
  • dir *.txt will apply a filter to display only the .txt files in the current directory.
  • mv can be used to move a file/directory on the remote machine to a new location on the remote machine.
  • reget can be used to resume a download that was interrupted. The partially downloaded file must exist on the local machine.
  • The psftp command can be issued as a single line or a local script at the command prompt. You could create a file test.scr that contains a set of psftp commands to be issued. You can then execute psftp from the command prompt, passing the password using ‐pw and the script file using ‐b (or ‐be to continue on error, or ‐bc to display commands as they are run), as follows:

    c:	emp>more test.scr
    lcd c:	empdown
    cd /tmp/down
    mget *
    quit
    c:	emp>psftp [email protected] ‐pw mypassword ‐b test.scr
    Using username "root".
    Remote working directory is /home/root . . .

Controlling the BeagleBone

At this point you should be able to communicate with the BBB using an SSH client application, so this section investigates the commands that you can issue to interact with the BBB.

Basic Linux Commands

When you first connect to the BBB with SSH you are prompted to log in. You can log in with username root, which does not require a password:

   login as: root
   Debian GNU/Linux 7
   BeagleBoard.org BeagleBone Debian Image 2014-10-08
   Support/FAQ: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian
   root@beaglebone:~#

You are now connected to the BBB, and the Linux terminal is ready for your command. The # prompt means that you are logged in to a superuser account (discussed in Chapter 3). For a new Linux user this step can be quite daunting, as it is not clear what arsenal of commands is at your disposal. This section provides you with sufficient Linux skills to get by. It is written as a reference with examples, so that you can come back to it when you need help.

First Steps

The first thing you might do is determine which version of Linux you are running. This can be useful when you are asking a question on a forum:

   root@beaglebone:~# uname ‐a
   Linux beaglebone 3.8.13-bone67 #1 SMP Wed Sep 24 21:30:03 UTC 2014 armv7l GNU/Linux

In this case, Linux 3.8.13 is being used, which was built for the ARMv.7 architecture on the date that is listed.

The Linux kernel version is described by numbers in the form X.Y.Z. The X number changes only very rarely (version 2.0 was released in 1996 and 3.0 in 2011). The Y value changes rarely, every two years or so (3.8 was released in February 2013 and 3.13 in January 2014). The Z value changes regularly.

Next, you could use the passwd command to set a superuser account password:

   root@beaglebone:~# passwd
   Enter new UNIX password:
   Retype new UNIX password:
   passwd: password updated successfully

Table 2-4 lists other useful first step commands.

Table 2-4 Useful First Commands in Linux

COMMAND DESCRIPTION
more /etc/issue Returns the Linux distribution you are using
ps ‐p $$ Returns the shell you are currently using (e.g., bash)
whoami Returns who you are currently logged in as
uptime Returns how long the system has been running
top Lists all of the processes and programs executing. Press Ctrl+C to close the view

Basic File System Commands

This section describes the basic commands that you will need in order to move around on, and manipulate, a Linux file system. When using Debian and Ubuntu user accounts, you often must prefix the word sudo at the start of certain commands. That is because sudo is a program that allows users to run programs with the security privileges of the superuser. User accounts are discussed in the next chapter. For the moment, the basic file system commands that you need are listed in Table 2-5.

Table 2-5 Basic File System Commands

NAME COMMAND OPTIONS AND FURTHER INFORMATION EXAMPLE(S)
List files ls ‐a shows all (including hidden files)
‐l displays long format
‐R gives a recursive listing
‐r gives a reverse listing
‐t sorts last modified
‐S sorts by file size
‐h gives human readable file sizes
ls ‐al
Current directory pwd Print the working directory
‐P prints the physical location
pwd ‐P
Change directory cd Change directory
cd then Enter or cd ~/ takes you to the home directory
cd / takes you to the file system root
cd .. takes you up a level
cd /home/root
cd /
Make a directory mkdir Make a directory mkdir test
Delete a file or directory rm Delete a file
‐r recursive delete (use for directories)
‐d remove empty directories
rm bad.txt
rm ‐r test
Copy a file or directory cp ‐r recursive copy
‐u copy only if the source is newer than the destination or the destination is missing
‐v verbose copy (i.e., show output)
cp a.txt b.txt

cp ‐r test testa
Move a file or directory mv ‐i prompts before overwriteNo ‐r for directory. Moving to the same directory performs a renaming. mv a.txt c.txt
mv test testb
Create an empty file touch Create an empty file or update the modification date of an existing file. touch d.txt
View content of a file more View the contents of a file. Use the Space key for the next page. more d.txt
Get the calendar cal Display a text‐based calendar. cal 01 2015

That covers the basics but there is so much more!—the next chapter describes file ownership, permissions, searching, I/O redirection, and more. The aim of this section is to get you up and running. Table 2-6 describes a few shortcuts that make life easier when working with most Linux shells.

Table 2-6 Some Time‐Saving Terminal Keyboard Shortcuts

SHORTCUT DESCRIPTION
Up arrow (repeat) Gives you the last command you typed, and then the previous commands on repeated presses
Tab key Auto‐completes the file name, the directory name, or even the executable command name. For example, to change to the Linux /tmp directory you can type cd /t and then press Tab, which will auto‐complete the command to cd /tmp/. If there are many options, press the Tab key again to see all of the options as a list
Ctrl+A Brings you back to the start of the line you are typing
Ctrl+E Brings you to the end of the line you are typing
Ctrl+U Clears to the start of the line. Ctrl+E and then Ctrl+U clears the line
Ctrl+L Clears the screen
Ctrl+C Kills whatever process is currently running
Ctrl+Z Puts the current process into the background. Typing bg then leaves it running in the background, and fg then brings it back to the foreground. This is discussed under Linux Processes in the next chapter

Here is an example that uses several of the commands in Table 2-5 to create a directory called test in which an empty text file hello.txt is created. The entire test directory is then copied to the /tmp directory, which is off the root directory:

   root@beaglebone:~# cd ~/
   root@beaglebone:~# pwd
   /root
   root@beaglebone:~# mkdir test
   root@beaglebone:~# cd test
   root@beaglebone:~/test# touch hello.txt
   root@beaglebone:~/test# ls
   hello.txt
   root@beaglebone:~/test# cd ..
   root@beaglebone:~# cp ‐r test /tmp
   root@beaglebone:~# cd /tmp/test/
   root@beaglebone:/tmp/test# ls
   hello.txt

Environment Variables

Environment variables are named values that describe the configuration of your Linux environment, such as the location of the executable files or your default editor. To get an idea of the environment variables that are set on the BBB, issue an env call, which provides you with a list of the environment variables on your account. Here, env is called on the Debian BBB image:

   root@beaglebone:~# env
   TERM=xterm
   SHELL=/bin/bash
   SSH_CLIENT=192.168.7.1 18533 22
   SSH_TTY=/dev/pts/3
   USER=root
   PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin . . .

You can view and modify environment variables according to the following example, which adds the /root directory to the PATH environment variable:

   root@beaglebone:~# echo $PATH
   /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
   root@beaglebone:~# export PATH=$PATH:/root
   root@beaglebone:~# echo $PATH
   /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root

This change will be lost on reboot. Permanently setting environment variables requires modifications to your .profile file when using sh, ksh, or bash shells, and to your .login file when using csh or tcsh shells. To do this, you need to be able to perform file editing in a Linux terminal window.

Basic File Editing

A variety of editors are available, but perhaps one of the easiest to use for new users is also one of the most powerful—the GNU nano editor. You can start up the editor by typing nano followed by the name of an existing or new filename; for example, typing nano hello.txt will display the view captured in Figure 2-7 (after the text has been entered!). Typing nano ‐c hello.txt will also display line numbers, which is very useful when debugging program code. You can move freely around the file in the window using the arrow keys and edit or write text at the cursor location. You can see some of the nano shortcut keys listed on the bottom bar of the editor window, but there are many more, some of which are presented in Table 2-7.

images

Figure 2-7 The GNU nano editor being used to edit an example file in a PuTTY Linux terminal window

Table 2-7 Nano Shortcut Keys—A Quick Reference

KEYS COMMAND KEYS COMMAND
Ctrl+G Help Ctrl+Y Previous page
Ctrl+C Cancel Ctrl+_ or Ctrl+/ Go to line number
Ctrl+X Exit (prompts save) Alt+/ Go to end of file
Ctrl+L Enable long line wrapping Ctrl+6 Start marking text (then move with arrows to highlight)
Ctrl+O Save Ctrl+K or Alt+6 Cut marked text
Arrows Move around Ctrl+U Paste text
Ctrl+A Go to start of line Ctrl+R Insert content of another file (prompts for location of file)
Ctrl+E Go to end of line Ctrl+W Search for a string
Ctrl+Space Next word Alt+W Find next
Alt+Space Previous word Ctrl+D Delete character under cursor
Ctrl+V Next page Ctrl+K Delete entire line

What Time Is It?

A simple question like this causes more difficulty than you can imagine. If you type date at the shell prompt, you may get the following:

   root@beaglebone:~# date
   Thu May 15 06:55:54 UTC 2014

which is many months out of date in this case, where the BBB connected to the desktop PC using an Internet‐over‐USB connection. However, it is likely that the date and time are correct if you are connected via “regular” Ethernet.

If it is wrong, why did the BBB team not set the clock time on your board? The answer is that they could not. Unlike a desktop PC, there is no battery backup on the BBB to ensure that the BIOS settings are retained—in fact, there is no BIOS! That topic will be examined in detail in the next chapter, but for the moment you need a way to set the time, and for that you can use the NTP (Network Time Protocol). The NTP is a networking protocol for synchronizing clocks between computers. If your BBB has the correct time, that is only because your BBB is obtaining it from your network.

One way to set the date and time is to find your closest NTP server pool by going to www.pool.ntp.org (the closest server to me is ie.pool.ntp.org for Ireland) and entering the following commands:

   root@beaglebone:/etc/network# date
   Thu May 15 07:28:21 UTC 2014
   root@beaglebone:/etc/network# /usr/sbin/ntpdate ‐b ‐s ‐u ie.pool.ntp.org
   root@beaglebone:/etc/network# date
   Sun Oct 12 19:07:37 UTC 2014

The time is now correct, but that is only the case until you reboot. If this command failed (e.g., you received the message “Error resolving  .  .  .”), then see the following feature on the “BeagleBone Internet‐over‐USB Settings.”

After you set the time, you can set your time zone. Use the following command, which provides a text‐based user interface that allows you to choose your location. The BBB is set for Irish Standard Time (IST) in this example:

   root@beaglebone:~# dpkg‐reconfigure tzdata
   root@beaglebone:~# date
   Mon Oct 13 00:16:47 IST 2014

Package Management

At the beginning of this chapter, a good package manager was listed as a key feature of a suitable Linux distribution. A package manager is a set of software tools that automate the process of installing, configuring, upgrading, and removing software packages from the Linux operating system. Different Linux distributions use different package managers: Ångström uses OPKG, Ubuntu and Debian use APT (Advanced Packaging Tool) over DPKG (Debian Package Management System), and Arch Linux uses Pacman. Each has its own usage syntax, but their operation is largely similar. For example, the first row in Table 2-8 lists the command for installing a package using different managers. The table also lists other package management commands that can be used.

Table 2-8 Common Package Management Commands (Using Nano as an Example Package)

COMMAND ÅNGSTRÖM DEBIAN/UBUNTU
Install a package. opkg install nano sudo apt‐get install nano
Update the package index. opkg update sudo apt‐get update
Upgrade the packages on your system.* opkg upgrade sudo apt‐get upgrade
Is nano installed? opkg list‐installed |grep nano dpkg‐query ‐l |grep nano
Is a package containing the string nano available? opkg list|grep nano apt‐cache search nano
Get more information about a package. opkg info nano apt‐cache show nano apt‐cache policy nano
Get help. opkg apt‐get help
Download a package to the current directory. opkg download nano sudo apt‐get download nano
Remove a package. opkg remove nano sudo apt‐get remove nano
Clean up old packages. Nontrivial. Search for “opkg‐clean script” sudo apt‐get clean

*It is not recommended that you do this. It can take quite some time to run (often several hours), and serious issues can arise if the BBB runs out of space during the upgrade.

Wavemon is a useful tool that you can use in configuring Wi‐Fi connections (see Chapter 10). If you execute the command you will see that the package is not installed:

   root@beaglebone:~# wavemon
   -bash: wavemon: command not found

The platform-specific (Debian in this case) package manager can be used to install the package, once you determine the package name:

   root@beaglebone:~# apt‐cache search wavemon
   wavemon - Wireless Device Monitoring Application
   root@beaglebone:~# apt‐get install wavemon
   Reading package lists . . . Done . . .
   Setting up wavemon (0.7.5-3) . . .

The wavemon command now executes, but unfortunately it will not do anything until you configure a wireless adapter (see Chapter 10):

   root@beaglebone:~# wavemon
   wavemon: no supported wireless interfaces found

Interacting with the BBB On‐board LEDs

In this section you are going to examine how you can change the behavior of the BBB on‐board user LEDs—the four blue LEDs in the top corner of the board. Each LED provides information about the BBB’s state:

  • USR0 flashes in a heartbeat sequence, indicating the BBB is alive.
  • USR1 flashes during micro‐SD card activity.
  • USR2 flashes depending on the level of CPU activity.
  • USR3 flashes during eMMC activity.

You can change the behavior of these LEDs to suit your own needs, but you will temporarily lose this useful activity information.

Sysfs is a virtual file system that is available under recent Linux kernels. It provides you with access to devices and drivers that would otherwise only be accessible within a restricted kernel space. This topic is discussed in detail in Chapter 6; however, at this point it would be useful to briefly explore the mechanics of how sysfs can be used to alter the behavior of the user LEDs.

Using your SSH client, you can connect to the BBB and browse to the directory /sys/class/leds. The output is as follows:

   root@beaglebone:~# cd /sys/class/leds
   root@beaglebone:/sys/class/leds# ls
   beaglebone:green:usr0 beaglebone:green:usr2
   beaglebone:green:usr1 beaglebone:green:usr3

You can see the four (green!) LED sysfs mappings—usr0, usr1, usr2, and usr3. You can change the directory to alter the properties of one of these LEDs—for example, usr3 (use the Tab key to reduce typing):

   root@beaglebone:/sys/class/leds# cd beaglebone:green:usr3
   root@beaglebone:/sys/class/leds/beaglebone:green:usr3# ls
   brightness device max_brightness power subsystem trigger uevent

Here you see various different file entries that give you further information and access to settings. Please note that this section uses some commands that are explained in detail in the next chapter.

You can determine the current status of an LED by typing:

   root@beaglebone:/sys/class/leds/beaglebone:green:usr3# cat trigger
   none nand-disk mmc0 [mmc1] timer oneshot heartbeat backlight gpio cpu0 . . .

where you can see that the USR3 LED is configured to show activity on the mmc1 device—the eMMC. You can turn this trigger off by typing:

   !root@beaglebone:/sys/class/leds/beaglebone:green:usr3# echo none > trigger

and you will see that the LED stops flashing completely. You can use more trigger to see the new state. Now that the LED trigger is off, you can turn the USR3 LED fully on or off using:

   root@beaglebone:/sys/class/leds/beaglebone:green:usr3# echo 1 > brightness
   root@beaglebone:/sys/class/leds/beaglebone:green:usr3# echo 0 > brightness

You can even set the LED to flash at a time interval of your choosing. If you watch carefully you will notice the dynamic nature of sysfs. If you perform an ls command at this point, the directory will appear as follows, but will shortly change:

   root@beaglebone:/sys/class/leds/beaglebone:green:usr3# ls
   brightness device max_brightness power subsystem trigger uevent

To make the LED flash you need to set the trigger to timer mode by typing echo timer > trigger. You will see the USR3 LED flash at a one‐second interval. Notice that there are new delay _ on and delay _ off file entries in the beaglebone:green:usr3 directory, as follows:

   root@beaglebone:/sys/class/leds/beaglebone:green:usr3# echo timer > trigger
   root@beaglebone:/sys/class/leds/beaglebone:green:usr3# ls
   brightness delay_on max_brightness subsystem uevent
   delay_off device power trigger

The LED flash timer makes use of these new delay _ on time and delay _ off time file entries. You can find out more information about these values by using the concatenate (catenate) command, for example:

   root@beaglebone:/sys/class/leds/beaglebone:green:usr3# cat delay_on
   500

which reports the time delay in milliseconds. To make the USR3 LED flash at 10 Hz (i.e., on for 50 ms and off for 50 ms) you can use:

   root@beaglebone:/sys/class/leds/beaglebone:green:usr3# echo 50 > delay_on
   root@beaglebone:/sys/class/leds/beaglebone:green:usr3# echo 50 > delay_off

Typing echo mmc1 > trigger returns the LED to its default state, which results in the delay _ on and delay _ off file entries disappearing.

Shutdown

One final issue to discuss in this section is the correct shutdown procedure for your BBB, as improper shutdown can potentially corrupt the ext4 file system and/or lead to increased boot times due to file system checks. Here are some important points on shutting down, rebooting, and starting the BBB:

  • Typing shutdown ‐h now shuts down the board correctly. You can delay this by five minutes by typing shutdown ‐h +5.
  • Typing reboot will reset and reboot the board correctly.
  • You can press the power button (see Figure 1‐4) once to “soft” (as in software) shutdown the board correctly.
  • Holding the power button for approximately eight seconds performs a hard system power down. This should be avoided unless the board is frozen and will not soft shutdown.
  • Press the power button to start the board. Try to avoid physically disconnecting and reconnecting the power jack or USB lead.

If your project design is enclosed and you need an external soft power down, it is possible to wire an external button to a BBB GPIO input and write a shell script that runs on startup to poll the GPIO for an input. If that input occurs, then /sbin/shutdown ‐h now can be called directly.

Node.js, Cloud9, and BoneScript

The BBB Linux distribution comes complete with a set of technologies that you can use to quickly get started with developing software and hardware applications on the BBB. These are called Node.js, Cloud9, and BoneScript—Node.js is a programming language, Cloud9 is a software development environment in which you can write Node.js code, and BoneScript is a library of code for Node.js that allows you to interact with BBB hardware.

 

Introduction to Node.js

Node.js is a platform for building network applications that uses the same JavaScript engine as the Google Chrome web browser. JavaScript is the programming language that is often used to create interactive interfaces within web pages. Simply put, Node.js is JavaScript on the server side. Its runtime environment and library of code enables you to run JavaScript code applications, without a browser, directly at the Linux shell prompt.

Node.js uses an event‐driven, nonblocking input/output model. Event‐driven programming is commonplace in user‐interface programming. It essentially means that the program’s flow of execution is driven by user actions or messages that are transferred from other threads or processes. Interestingly, the fact that it uses nonblocking I/O means that it is suitable for interfacing to the input/output pins on your BBB, safely sharing resources with other applications. As with all new languages, you should start with a “Hello World” example. Listing 2‐1 sends the string “Hello World!” to the standard output, which is typically a Linux terminal.

Open an SSH connection to the BBB, create a directory to contain the HelloWorld.js file, and then enter the code from Listing 2‐1 using nano:

   root@beaglebone:~# cd ~/
   root@beaglebone:~# mkdir nodeTest
   root@beaglebone:~# cd nodeTest
   root@beaglebone:~/nodeTest# nano HelloWorld.js

To execute this code, type node HelloWorld.js in the directory containing the JavaScript file. You should see the following output:

   root@beaglebone:~/nodeTest# ls
   HelloWorld.js
   root@beaglebone:~/nodeTest# node HelloWorld.js
   Hello World!

which should give you an idea of how you can write Node.js programs for the BBB. The call to the node command works because the Node.js runtime environment is preinstalled on the BBB Linux image.

A more complex Node.js example is provided in Listing 2‐2. It creates a web server that runs on the BBB at port 5050 and serves a simple “Hello World” message. Write the program code in the same /nodeTest directory:

The example code in Listing 2‐2 begins by requiring the Node.js http module. It then calls the http.createServer() method, which returns an http.Server object. The server.listen() method is called on the http.Server object, where it causes the server to accept connections on a defined port number (i.e., 5050). This method is asynchronous, meaning it does not have to finish before the console.log() method is called on the next line. In fact, unless you kill the process on the BBB, the server.listen() method will listen forever. When a connection is made to port 5050, the server will call the listening function, function(req,res), to which is passed a copy of the HTTP request and response references. In this case, the function responds with a short plaintext message.

To execute this program you type node SimpleWebServer.js in the directory containing the source code file, and you should get the following:

   root@beaglebone:~/nodeTest# ls
   HelloWorld.js SimpleWebServer.js
   root@beaglebone:~/nodeTest# node SimpleWebServer.js
   BBB Web Server running at http://192.168.7.2:5050/

where the output indicates that the server is running and listening on port 5050. You can then open a web browser and connect to this simple Node.js web server, where you will see the output as shown in Figure 2-8. You can use Ctrl+C to kill the web server in the SSH window.

images

Figure 2-8 Connecting to the Node.js web server

Introduction to the Cloud9 IDE

Wouldn’t it be great if there were a way to integrate the development of Node.js code with the execution environment? That is where the Cloud9 IDE is very useful. The Cloud9 integrated development environment (IDE) is an impressive web‐based coding platform that supports many different programming languages, including JavaScript and Node.js. It enables you to write, run, and debug code directly within your web browser without installing any operating‐system‐specific tools or applications. If that is not impressive enough, the Cloud9 service has a low enough overhead to run directly on the BBB, and it comes preinstalled on the BBB Linux images.

To use the Cloud9 IDE, open Google Chrome or Firefox and connect to your BBB address on port 3000. For example, open 192.168.7.2:3000 using the address bar as shown in Figure 2-9. When you first open Cloud9 it provides an excellent introduction to the user interface and controls.

images

Figure 2-9 The Cloud9 IDE (light theme) running on the BBB, executing the SimpleWebServer.js example

Rather than having to write the code on your desktop machine and transfer it to your BBB, the Cloud9 interface can save files directly on your BBB file system and can even execute them too. In Figure 2-9, a new .js file is created, which contains the code in Listing 2‐2. You must save the file using File ➢ Save. You can click the Run button to execute the application. If the Debugger window appears, click Resume. You can click the hyperlink in the output console and the application output will be visible in the browser window that appears, as in Figure 2-9.

Remember that this SimpleWebServer.js program is running on the BBB itself. In fact, if you SSH into the BBB (or use the Cloud9 bash terminal window) and execute the following command (described in Chapter 3), you can see that the application process is running as follows:

   root@beaglebone:~# ps aux|grep SimpleWebServer
   root 4186 0.3 2.2 . . . node . . . /var/lib/cloud9/EBB/SimpleWebServer.js

Clicking the Stop button in the Cloud9 IDE will kill this process.

Introduction to BoneScript

BoneScript is a library of BBB‐specific functionality that has been written for Node.js by BeagleBoard.org co‐founder Jason Kridner. The BoneScript library provides the type of input/output functionality that would be familiar to Arduino users, but with the advantage that it sits on top of the network capabilities of Node.js running on the BBB. There are detailed descriptions of BoneScript and its functionality at tiny.cc/ebb205.

You can use BoneScript to build a simple application to change the state of one of the system LEDs. The code in Listing 2‐3 flashes the BBB on‐board USR3 LED, once every second, by utilizing the BoneScript library.

This program requires the bonescript module, which is now referred to in the code as b—for example, by using b.someMethod(). Therefore, b.pinMode() uses the string literal “USR3” to identify the pin that is to be set to output mode. A temporary Boolean value isOn is used to retain the state of the LED in the code. The Node.js asynchronous global function setInterval() is set up to call the toggleLED() callback function every 500 ms. Each time the toggleLED() function is called the isOn Boolean variable is inverted using the NOT operator (i.e., !true=false and !false=true); you set the LED pin to high if the value of isOn is true, and low if its value is false; and the state is outputted to the console.

This program can be executed directly within the Cloud9 IDE. However, it is important to remember that you can still run programs that include the BoneScript library calls directly at the Linux console. Therefore, for example, if you transfer the BlinkLED3.js code to the BBB and execute it directly, it will also work perfectly, flashing the USR3 LED once per second:

   root@beaglebone:~/nodeTest# node BlinkLED3.js
   LED On is: true
   LED On is: false . . .

BoneScript is very useful for the rapid prototyping of systems, particularly when those systems involve electronics that are to be connected to the Internet. However, it is not ideal for high‐performance large‐scale applications—alternative languages and approaches are described throughout this book for such applications.

Summary

After completing this chapter, you should be able to do the following:

  • Communicate with the BBB from your desktop computer using network connections such as Internet‐over‐USB and regular Ethernet.
  • Communicate with the BBB using fallback serial connections such as Serial‐over‐USB or by using a custom USB‐to‐TTL 3.3 V cable.
  • Interact with and control the BBB using simple Linux commands.
  • Perform basic file editing using a Linux terminal.
  • Manage Linux packages and set the system time.
  • Use Linux sysfs to affect the state of BBB hardware.
  • Safely shut down and reboot the BBB.
  • Use Node.js, Cloud9, and BoneScript to write basic applications and code that interacts with BBB hardware.

Further Reading

There are many links to websites and documents provided throughout this chapter. The following additional links provide further information on the topics covered:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.173.72