Programming The BeagleBone - Sample Chapter
Programming The BeagleBone - Sample Chapter
ee
P U B L I S H I N G
C o m m u n i t y
$ 29.99 US
19.99 UK
pl
Yogesh Chavan
Programming the
BeagleBone
Sa
m
D i s t i l l e d
Programming the
BeagleBone
Harness the power of BeagleBone from blinking LEDs to Internet
of Things applications
E x p e r i e n c e
Yogesh Chavan
India. He has now been teaching operating systems, device drivers, and embedded
systems in colleges and institutes for more than three years. These include the
computer science department of Pune University, Symbiosis Institute of Computer
Studies and Research (SICSR) college, and the Centre for Development of Advanced
Computing (C-DAC) institute. He has about six years of experience in the software
industry. His previous industrial role was of a software maintenance engineer at Red
Hat Software Services.
Yogesh has overseen many engineering projects under GEEP (http://www.
geeksofpune.in). He has given many talks at the annual open source event,
GNUnify (http://gnunify.in).
Yogesh enjoys cutting edge technologies. He is a hardware hobbyist who likes
playing with smartphones, tablets, routers, and Arduino. He is big fan of Android
and various Linux distributions. He has compiled and modified kernel and
firmwares for many phones and routers. He wishes to be a humble contributor
to the open source world.
Preface
The whole world is moving from desktop/computers to smartphones/embedded
systems. We are at the door to Internet of Things (IoT). The number of Internet
connected users crossed 3.2 billion in 2015, which is almost half of the total
population. The number of connected devices has exceeded the number of humans
already. IoT is going to bring a combination of solutions, mixing physical world and
digital world. We will interact with the digital world in newer ways than keyboard
and mouse. Everyday objects will have logic in them to do their work in a better
way. Multiple things will work collectively in order to achieve better results. IoT will
bring lot many possibilities and opportunities along.
IoT implementation needs power-efficient embedded system solutions. There has
been an exponential rise in the demand of the embedded systems in the last few
years. Therefore, there is a demand for embedded programming as well. Embedded
development boards such as BeagleBone play a key role here. These boards provide
opportunities to new programmers to get their hands on ARM-based embedded
systems. BeagleBone comes as an ultra-small, cost-effective solution with a powerful
hardware that runs Debian Linux. This book tries to explore the hardware and
software capabilities of BeagleBone to create real-life electronics and IoT
applications quickly.
Preface
Being an open source hardware board, BeagleBone is the perfect choice to study
embedded systems. Board design files and in-depth datasheets are open for being
studied. It comes with an Ethernet port that allows deploying the IoT projects
without making any addition to the board. It provides plenty of GPIO, ADC, UART,
I2C, and SPI pins that make it the right choice for electronic projects. One can install
Debian, Ubuntu, Android, and many other Liunx distributions. By default, it comes
with a full-fledged Debian Linux OS running on it. This gives you all the benefits
of Linux kernel such as multitasking, multiuser, and extensive device drivers
support. It also allows you to do programming in many languages, including C,
C++, JavaScript, Python, Ruby, Perl, and so on. This book uses BeagleBone as a tool
to write useful applications on the embedded systems. Starting with the basics to set
up BeagleBone and Cloud9 IDE, this book covers interfacing with various electronic
components via simple programs. The electronics theory related to these components
is explained in detail before using them in a program. Then, the book covers some
real-life IoT applications.
This book is divided in two parts: the first part is covers programs in JavaScript and
the second part of this book provides electronics projects and IoT applications in
Python. Most of the physicial computing theories and concepts are covered in the
JavaScript part. Programs are explained in the explanation section, immediately after
it's source code. Troubleshooting steps are given wherever needed. Some programs
have an execution section, which explains how a program works internally.
Programming language conventions and error handling are loosely followed to make
programs short and easy to understand. The language that is to be covered first is a
tough choice. I choose JavaScript as it is energy-efficient, event-driven architecture.
It is more suited as an IoT solution. Only sending the important information reduces
the processing that is to be done on the Thing connected to the Internet. Javascript is
a natural language of web. It comes preinstalled in the BeagleBone along with Node
and Cloud9. You can start Javascript programming immediately after connecting
BeagleBone. Let's start the journey of programming the BeagleBone.
Preface
Chapter 3, Blinking External LEDs, explains the General Purpose Input/Output (GPIO)
theory and how to attach the external LEDs to the GPIO pins. Then, it covers blinking
LED and display pattern programs.
Chapter 4, Controlling LED Using a Push Button, teaches how to read from input
components using polling. The interrupt method programs for each of these
methods are covered.
Chapter 5, Reading from Analog Sensors, covers the theory about Analog I/O and how
BeagleBone supports it. Then, it has programs to read from the TMP36 temperature
sensor and light sensor.
Chapter 6, PWM Writing Analog Information, explains how the Pulse Width
Modulation (PWM) technique is used to write the analog information and how
BeagleBone supports it. It has a program to fade-in LED and control the servo
motor using PWM.
Chapter 7, Internet of Things with BeagleBone, explains how to implement IoT in
JavaScript using BeagleBone. It covers important information about IoT. Then,
there are three real-life examples. Two of them are programs to remotely control
LED and servo motor. Another program is to shoot an e-mail alert when
overtemperature is detected.
Chapter 8, Physical Computing in Python, explains rewriting all the programs that are
covered from Chapter 3 to Chapter 6 in the Python language.
Chapter 9, UART, I2C, SPI Programming, covers popular buses in the embedded
systemsUART, I2C, and SPI. All these protocols are explained here in detail. This
chapter covers programs that communicate over each of these buses.
Chapter 10, Internet of Things Using Python, teaches IoT programs in Python. It
has programs that were similar to the programs covered in Chapter 7. It has an
additional program that uploads the temperature data over the Cloud website and
we will receive the temperature graph over time for analysis.
Appendix A, GPIO Control in Bash, teaches how to set the direction and turn GPIO
on/off directly by writing sysfs files.
Appendix B, BeagleBone Capes, provides information about BeagleBone add-on boards
called capes.
Appendix C, Pinmux and the Device Tree, gives details about the new hardware
description files that help the kernel to initialize BeagleBone. They are called device
tree. It covers how to use the device tree filestoselecttheroleoftheBeagleBone
pin among other possibilities.
This book does not cover BeagleBone Programmable Realtime Units (PRUs) and
building/customising installable image.
Cloud9 IDE
BeagleBoard foundation has created a few low power ARM-based open hardware
boards. The most successful board among them was BeagleBone Black. Actually, it
is a series of boards that match physical size with the same processor and slightly
different hardware. There are three variants in this seriesBeagleBone White,
BeagleBone Black and BeagleBone Green. This book is about programming boards
in this BeagleBone series. We will see details about BeagleBone hardware as the first
topic of this chapter. Then we will learn how to connect and set up BeagleBone for
our work. All BeagleBones come with a programming interface called BoneScript.
It is a faster and easier way to deal with components of BeagleBone. We are going
to use BoneScript for programming in the first part of this book. At the end of this
chapter, we will learn about IDE (Integrated Development Environment), which
helps us to do programming in BoneScriptCloud9.
Here are the topics that will be covered in this chapter:
BeagleBone hardware
Setting up BeagleBone
bone101 page
Cloud9
[1]
Cloud9 IDE
BeagleBone hardware
The BeagleBoard foundation is a non-profit corporation promoting open source
hardware and software. It has been releasing low power, hacker-friendly embedded
boards since 2008. They have created a few powerful and educational single board
computers. These boards are sold to the public under the Creative Commons
share-alike license that encourages sharing. These boards are collectively called
BeagleBoards. They have a GitHub page at https://github.com/beagleboard.
Here you can find hardware information files and software related to released
boards. Support for these boards comes from a very active developer community. The
BeagleBoard group on Google has more than 10,000 members. You can view posts
and join the group here: http://beagleboard.org/Community/Forums. Their IRC
(Internet Relay Chat) channel #beagle on freenode is active. You can join the channel
and ask questions at http://beagleboard.org/chat. There are more than 500
different projects registered with BeagleBoard at http://beagleboard.org/project.
There are two different series of released boards by beagleboard.org. First
is the BeagleBoard series. This series has candidatesoriginal BeagleBoard,
BeagleBoard-xM and BeagleBoard-X15. These are comparatively big, square-sized
boards. Their processors are slightly better in terms of performance and have an
additional DSP (Digital Signal Processor) that can do better audio/video processing.
These boards have many peripherals available onboard. They are more powerful and
comparatively costly. These boards are perfect in scenarios where major audio/video
processing is involved or performance is important.
Another series is called the BeagleBone series. This series has candidates
BeagleBone White, BeagleBone Black, BeagleBone Green. These boards are compact,
lightweight and share the same physical size (3.4 inch 2.1 inch). They all have the
same Texas Instruments AM335x sitara ARM Cortex-A8 processor. These boards
lack DSP and lag behind in scenarios with major audio/video processing. But these
processors are fine in other scenarios. They come with fewer peripherals on board.
You can attach many peripherals externally. They are far cheaper than boards in
the BeagleBoard series. They provide many expansion i/o pins of type GPIO/I2C/
SPI/PWM/UART/CAN/ADC. So you can connect lots of sensors, modules, electronic
components, displays, and so on. to these boards. All these boards share the same
expansion pins layout. This means if you study expansion of one board in the series,
the knowledge applies to other boards in the series too. There are small differences
in these boards. Please refer to the following table to learn the differences. All these
characteristics make BeagleBone a popular choice among hardware hackers. Besides
hardware, they can all boot up from the same firmware image. So all software
stack is the same for them. These boards can be programmed using the same
programming interface. All these boards come with preinstalled Cloud9 IDE, which
allows you to write and deploy applications on that board in many programming
languages remotely via web browser.
[2]
Chapter 1
BeagleBone Black
BeagleBone Green
Processor
720MHzARM
CortexA8
1GHz ARMCortex-A8
1GHz ARMCortex-A8
RAM
256MB DDR2
512MB DDR3
512MB DDR3
Storage
2/4GB emmc,
microSD slot
Display/
Audio
onboard micoHDMI
Power
connector
via MiniUSB or
5.5mm DC jack(5V)
Boot
debugging
Other
connector
Expansion
2x 46pin i/o
expansion header
http://beagleboard.org/bone
http://elinux.org/Beagleboard:BeagleBone
[3]
Cloud9 IDE
http://beagleboard.org/black
http://www.elinux.org/Beagleboard:BeagleBoneBlack
[4]
Chapter 1
http://www.beagleboard.org/green
http://www.seeedstudio.com/wiki/Beaglebone_green
It is important to note that throughout this book we will use the
word BeagleBone to represent any board (BBW or BBB or BBG)
in the BeagleBone series. So BeagleBone setup steps in the book
should work for BeagleBone White as well as BeagleBone Black as
well as BeagleBone Green.
Cloud9 IDE
When you connect the BeagleBone to PC using a USB-to-MiniUSB cable (Micro USB
for BeagleBone Green), it gets detected as flash drive providing you with a local copy
of the documentation and drivers. When it autoruns, you see the browser opened
with the page Getting Started. If it does not run automatically, you can manually
open the file START.htm or the README.htm file inside the BeagleBone flash drive.
This HTML page has a link to "update to latest software" on the left. It provides you
with a step-by-step procedure with screenshots to install the latest prebuilt Debian
image on the SD card. An online version of this webpage is available at: http://
beagleboard.org/getting-started#update.
Here are the important steps to install the latest Debian image on the BeagleBone:
1. Latest supported images of all BeagleBoards are available at http://
beagleboard.org/latest-images. Download a Debian image for BeagleBone
on your PC. The same image works on BeagleBone White, Black and Green.
2. These images come compressed. On a Linux system you can extract it by
right-clicking to that file in File Manager and choosing Extract Here. On a
Windows system, you can extract it using decompression software 7zip
available at http://www.7-zip.org/download.html.You will get an .img
file. This is an actual image file.
3. Now, attach a USB SD card reader to your PC. On a Linux system, you can
dump an .img file on a SD card using the following command. You need to
find the name of the SD card file. You can get that in dmesg command output
after you connect the SD card. Put that in place of sdx in command.
sudo dd
4. Push this SD card in the BeagleBone SD card holder. Give power supply to
the board and you should see user LEDs blinking, which is sign of life. In
case you want to make sure you are booting from the SD card and not emmc,
get shell access (covered in the next topic) and edit files /etc/issue and /
etc/issue.net on the SD card to print that it is booted from the SD card.
The next the shell access login will show that message.
[6]
Chapter 1
Setting up BeagleBone
Embedded boards lack rich programming environment like x86 Desktop PC. Often
they are connected to x86 Desktop for programming. Before starting programming,
we need to connect BeagleBone to PC and set up the working environment. Let us
see different ways to connect to BeagleBone and how to start Cloud9 programming
IDE and the useful bone101 page. If you connect the BeagleBone via any one the
following ways successfully, you can skip others. You will need a little Linux
commands knowledge here. If any of these connection steps do not work, try the
steps given in Troubleshooting section. The most common problem is the power
supply. USB 2.0 is designed to supply max 500mA current, which is fine if you
are not attaching peripherals to BeagleBone. But if you are connecting Ethernet,
HDMI or USB devices, you should use a 5V 2A power adapter with 5.5mm DC
barrel jack to power up BeagleBone. You can get it at https://www.sparkfun.com/
products/12889. On BeagleBone Green, you will have to use a 5V 2A Micro USB
power adapter. You can get it at: https://www.sparkfun.com/products/12890.
By default, you can login as username debian and password temppwd on default
Debian images for BeagleBone. This user has sudo access to all the commands in the
current Debian image. The board has to be secured before starting to use it. Once
logged in, you should change the password of debian user using the command
passwd. You can also login as root with no password when asked. You should login
as a root user and change the root password too using the same command.
[7]
Cloud9 IDE
Troubleshooting
Refer to the table at end of this topic to learn different ways you can get shell
access. After getting shell access to BeagleBone, you can use utilities like
ifconfig, ping and dmesg to debug further.
If you were not able to install the RNDIS driver from the BeagleBone flash
storage, you can install drivers from http://beagleboard.org/static/
Drivers.
[8]
Chapter 1
Troubleshooting
[9]
Cloud9 IDE
VNC
You can also connect via VNC (Virtual Network Computing). It is a remote
desktop connection. You need to connect via the Ethernet over USB or Ethernet or
USB-Wi-Fi method first to do a VNC connection. Debian for BeagleBone comes with
tightvncserver preinstalled. To set up VNC get shell access to BeagleBone and run
the command vncserver on it as a Debian user. Download VNC client software
on PC and connect to server beaglebone:1. You will get a similar GUI like you get
on an HDMI connection. You will be able to get shell access via the lxterminal
terminal emulator, browse the bone101 page at http://beaglebone.local and
browse cloud9 IDE at http://beaglebone.local:3000. As BeagleBone White
and BeagleBone Green do not have an HDMI port, this option is useful if you want
GUI access.
Troubleshooting
The vncserver display does not always run on :1. Command vncserver
prints the name of the display it is running on. Note it down and use it when
connecting from the VNC viewer.
The VNC session might not use the lxde window manager. Currently
Debian uses openbox window manager for the VNC session of the debian
user. It shows the desktop with no icon or panel. You get shell and browser
access by right-clicking on the desktop.
Serial Connection
Serial connection gives you a booting log and then a SSH-like command line
interface. Please note that you cannot access Cloud9 or bone101 page or GUI using
serial connection. BeagleBone provides two types of serial access. One is using a
pseudo USB-serial driver on a USB port. You get a SSH-like shell access by this
method. As a USB-serial driver starts working after kernel booting, you do not get
boot logs by this method. BeagleBone Black on MiniUSB port and BeagleBone Green
on Micro USB port provide this type of serial access. When you connect by these
methods, BeagleBone appears as serial device on the connected PC. On Windows,
it appears as serial COM port in the device manager. Note down the COM port
number in the device manager and connect to that port via putty or hyperterminal
specifying baud rate 115200.
[ 10 ]
Chapter 1
On the Linux system, check kernel messages of the PC using the command dmesg to
find out the name of the device it got detected as. It gets detected as /dev/ttyUSB0
by default. You can use this command to connect it serially:
sudo screen /dev/ttyUSB0 115200
When you are done, press Ctrl + A then K to exit the screen.
Another type of serial connection possible on BeagleBone is via using a hardware
chip that is responsible for making a serial connection. As an external chip is doing
the work, this method gives boot time logs as well as shell access when booting
is done. This connection is the only way to get logs when BeagleBone is failing to
boot properly. It is useful to configure Ethernet, and debug problems. BeagleBone
White has FTDI USB-to-serial conversion chip onboard. It gives serial access over a
MiniUSB port. For BeagleBone Black and BeagleBone Green, the onboard USB-serial
chip is absent. But there are serial header pins available onboard. You need a special
USB-serial TTL cable to attach to these header pins. Any FTDI or PL2303 or cp210x
chip based USB TTL cable can be used here. The FTDI cable from Adafruit is popular
which can be found at https://www.adafruit.com/products/70. You will have
to install drivers corresponding to the chip used in the cable. Drivers for these chips
come preinstalled in most of the Linux systems and the serial port gets detected as
/dev/ttUSB0 by default. You can connect using the screen command we covered in
previous paragraph. Windows drivers for FTDI or PL2303 of CP210x are available on
vendor websites. Once you install the driver, you will be able to locate the COM port
in the device manager and connect via the hyperterminal or putty:
Physical ports
GUI
Shell
bone101
Cloud9
Internet
Direct monitor
and keyboard
connection
HDMI &
regular USB
port
Yes
Yes
Yes
Yes
Possible via
Ethernet or
USB-Wi-Fi
Ethernet over
USB
Mini/Micro
USB
via
VNC
via
SSH
Yes
Yes
Possible via
Ethernet or
USB-Wi-Fi
Ethernet or USBWi-Fi
Ethernet or
regular USB
port
via
VNC
via
SSH
Yes
Yes
Yes if
connected to
router with
the Internet
VNC
Mini/Micro
USB or
Ethernet
Yes
Yes
Yes
Yes
Possible via
Ethernet or
USB-Wi-Fi
Serial
connection
Mini/Micro
USB or serialheader
___
Yes
___
___
Possible via
Ethernet or
USB-Wi-Fi
[ 11 ]
Cloud9 IDE
Besides all these options, Cloud9 IDE has one tab inside it, which gives you a
root shell. So, if you have Cloud9 access, there is no need to connect via terminal
emulator or SSH to get BeagleBone shell access. Here is a helpful link on BeagleBone
wiki about connecting BeagleBone http://elinux.org/Beagleboard:Terminal_
Shells.
[ 12 ]
Chapter 1
The top-most green frame tells you that the board is connected. If your board is not
connected, this frame will be of orange color and it will ask you to enter the IP address
of the board. The left side pane has links to supported BoneScript and JavaScript
functions. The remaining page gives miscellaneous information including available
OS, upgrading OS, Cloud9 quickstart information, and expansion I/O pin details.
You can always get help about BoneScript library functions from the left frame on the
bone101 page. These function help information have example code snippets. These
code snippets come with a run and restore button. If your board is showing a green
frame indicating that you are connected, then you can run these examples directly
from the bone101 page. You can modify the code on the webpage and run new code
by pressing the run button. If you want to go back to the unmodified original example
code, press the restore button. You can even open this page from a smartphone
browser with the correct BeagleBone IP address and run code from there.
If you are connected to BeagleBone via Ethernet over USB, you get connected to the
topmost green frame automatically. If you are connected to the Ethernet port, you
will see an orange frame asking for the IP address. You can get the IP address of
the Ethernet port from your router weblogin or by getting shell access and running
ifconfig. You can enter that IP and you will get green frame saying You are
connected. Then you can explore online help and execute the example code.
A later part in the webpage gives a step-by-step procedure with screenshots to start
Cloud9 IDE and run the first BoneScript program. The last part of this page gives
details about BeagleBone Black hardware. It has links to the online hardware design
files and wiki page. This section gives pin details of expansion headers like which
pins have GPIO, analog input, PWM, UART, I2C and SPI capabilities. We will need this
information throughout the book. To get updated help information and examples
of BoneScript, visit http://beagleboard.org/Support/BoneScript/. This page
allows us to connect BeagleBone and run BoneScript example code on BeagleBone
similar to the bone101 page.
[ 13 ]
Cloud9 IDE
Cloud9 IDE
Cloud9 IDE runs on port number 3000 on BeagleBone. The Setting up BeagleBone
section covered many ways to connect to BeagleBone and open Cloud9 IDE. After
connecting to BeagleBone and opening Cloud9 via any one of these ways, we are
ready to explore BeagleBone's default programming IDE.
Cloud9 is a web-based IDE to develop primarily JavaScript and Node.js applications.
It also supports many other programming languages including PHP, Java, Python
and Ruby. Cloud9 runs on the web which means it works inside a browser. There
is no difference if you are using Windows, Linux or MAC OS on your PC or even
from your smartphone. If you are using a supported Firefox or Chrome browser on
a remote PC/smartphone, you can run Cloud9 and do programming on BeagleBone.
Cloud9 allows many developers to code simultaneously on single project through
the web. It supports instant deployment to many well-known cloud platforms like
Microsoft Azure, Google App Engine and OpenShift. It is open source software and
maintained by a company called Cloud9 IDE, Inc. You can get the source code here:
https://github.com/c9/core:
[ 14 ]
Chapter 1
Cloud9 is made up of multiple child windows inside. In the leftmost windows you
can select a project related window among Workspace or Navigate or Commands.
The Workspace window has a tree view that expands and collapses project files. You
can add new, rename and delete project files from this window. At the bottom, there
is a console window to display program output, compilation errors, and console.
log() messages. When you run any program, you get output printed in this window.
You can add a new JavaScript immediate tab in this window. It is useful to evaluate
expressions, execute statements and print variables values. You can also add a bash
shell in this window tab. You can run commands directly on BeagleBone from here.
At the right, there is a place for toolbars. Debugger and Outline toolbars take place
in this area. Expand the debugger toolbar when you want to debug a program line
by line. The middle empty part is the code editor area. Here actual code gets written.
It has very small pane area at the left side. It shows line numbers and breakpoints,
errors, and warning signs corresponding to that line. Cloud9 supports multiple tabs
to edit many files simultaneously. It provides code completion features for snippets
and identifiers. It has rich debugging features like setting breakpoints and step
into/step over. It provides dragging and dropping of files from computer to code
area. This way, you can add new ready-made code to your project. There are many
customization options available with a menu bar at the uppermost side.
We are going to use Cloud9 for all BoneScript programs. There are some
ready-made files with code in the demo directory. But they need some hardware
setup. So, we will skip them. The best way to get help is to visit the bone101 page
or http://beagleboard.org/Support/BoneScript/.
Cloud9 IDE
3. Go to the File menu again and save as hello.js. Now, you should see the
tab title is changed from Untitled1 to hello.js. Now Cloud9 knows this is
JavaScript program. It will highlight the program with different colors.
4. Click on the run button at the top of screen. You will see the Debugger
toolbar from right side is expanded to the Debug pane. Click on the Resume
button on expanded pane or press the F8 key. You should see the Hello
World text in the output view at the bottom.
Explanation
In this tiny code, the first line is the comment. JavaScript supports C and C++ style
commenting. So the pattern /* ... */ is used in multi-line commenting and
the pattern// is used for single line commenting. The second line is calling the
log() method on the object console. We have given the string Hello World as
a parameter to the log() method. A semicolon ; denotes a terminated statement.
Here, the console object provides access to the browser's debugging console.
console.log() is a method to print string. It prints Hello World in the console.
As we are using a built-in JavaScript object, we have not loaded a JavaScript
module/library. You can try more methods provided by the console object. You can
get a detailed document about JavaScript at: http://www.w3schools.com/js/ and
https://developer.mozilla.org/en-US/docs/Web/JavaScript.
Summary
This chapter covered all the prerequisites to get programming IDE access on
BeagleBone with the latest software. In this chapter we learned about different
boards available in the BeagleBone series and their hardware differences. Then we
learned how to install the latest Debian image on BeagleBone and various ways to
connect to BeagleBone with troubleshooting steps. Once connected, we can visit
the bone101 HTML page, which has lots of information about BeagleBone. It also
provides help pages for JavaScript and BoneScript functions. Then we started using
Cloud9 IDE. It is a web-based IDE that runs on port number 3000 on BeagleBone. In
the end, we created our first JavaScript program that prints Hello World.
Now, we are ready with IDE and we know how to compile and run a program on
BeagleBone. In the next chapters, we will write programs that interact with the
physical environment.
[ 16 ]
www.PacktPub.com
Stay Connected: