GNU-Linux Rapid Embedded Programming
上QQ阅读APP看书,第一时间看更新

Preface

Embedded computers have become very complex in the last few years and developers need to easily manage them by focusing on how to solve a problem without wasting time in finding good peripherals or learning how to manage them. The main challenge with experienced embedded programmers and engineers is really how long it takes to turn an idea into reality, and we show you exactly how to do it.

This book shows how to interact with external environments through specific peripherals used in the industry. We will use the latest Linux kernel release 4.x and Debian/Ubuntu distributions (with embedded distributions of OpenWrt and Yocto).

The book will present popular boards based on widely used and easily available CPUs on the components market and widely available from different professional boards makers. After a brief introduction of each boards, the book will show how to set up them in order to run a complete GNU/Linux distribution and then getting access to the system console. After that the book will present how to install a complete developing system on each board in order to be able to add developer's programs.

Readers will be able to take their first steps in programming the embedded platforms, using C, Bash and Python/PHP languages in order to get access to the external peripherals. More about using and programming device driver and accessing the peripherals will be covered to lay a strong foundation. The readers will learn how to read/write data from/to the external environment by using both C programs and a scripting language (Bash/Python) and how to configure a device driver for a specific hardware.

The hardware devices used in the book has been chosen in order to cover all possible connection type we can encounter working with an embedded board so you can find I2C, SPI, USB, 1-Wire, serial, digital and analog devices, etc.

The programming languages used in the book has been chosen according to the rule to find the quickest and easiest solution to solve the current problem, in particular you can find example codes in Bash, C, PHP, Python.

In such chapters were will need to use a daemon, a kernel module or to recompile the whole kernel I've added a short description about what the reader should do and where he/she can get more information regarding the used tools, however some basic skills in managing a GNU/Linux system or the kernel's modules or the kernel itself are required.

What this book covers

This book can be pided into two major parts: the first one, which is introductory to the second one, where you will see how to install the developing systems and the host system and how to get access to the serial console. You'll take a look at some basic bootloader's commands as far as to the C compiler and the cross-compiler and then I'll introduce kernel modules, device drivers and some filesystem internals with a note on the Network File System. Also the machine emulator usage will be presented in order to execute a complete target machine's Debian distribution on a host PC, you'll see the system daemons and script programming in Bash, PHP and Python and then you'll take a look at the flash memories and Linux's Memory Technology Device (MTD) where I'll introduce the JFFS2 and the UBIFS filesystem and two of the most famous embedded distribution used in these days, Yocto and OpenWrt.

Below is a brief introduction of each chapters related to this first part:

Chapter 1 , Installing the Developing System, will present three of the most used development kits for industrial applications: the BeagleBone Black, the SAMA5D3 Xplained and the WandBoard. After a brief introduction of each boards, we'll see how we can set up them in order to run a complete GNU/Linux distribution. We'll see how to install a complete developing system on each board as far as the host system (even on a virtual machine).

Chapter 2 , Managing the System Console, will show to setup our developer kits and (in part) the host PC, then we'll go further in exploring the serial console and the shell running in it. In the end a special section will introduce the bootloader commands.

Chapter 3 , C Compiler, Device Drivers, and Useful Developing Techniques, will focus the readers' attention to the C compiler (with its counter part: the cross-compiler). Then we'll take a look at kernel modules, device drivers and some filesystem internals with a note on the Network File System. In the end we'll see how developers can use an emulator in order to execute a complete target machine's Debian distribution on a host PC.

Chapter 4 , Quick Programming with scripts and system daemons, will take a look at system daemons (what they are and how to use the most famous and useful ones). Then we'll take a look at script programming by using Bash, PHP and Python languages.

Chapter 5 , Setting up an embedded OS, will start taking a look at flash memories and the software used to manage them, then we'll present the Linux's Memory Technology Device (MTD) and the two major filesystems that can run over them, that is the JFFS2 and the UBIFS. The we'll present two of the most famous embedded distribution used in these days, Yocto and OpenWrt, and how an embedded developer can write an his/her own application and how he/she can add it to them.

The second part then starts in going deeper in presenting all of such peripheral devices that you, as embedded developer, may encounter into your professional life. For each peripheral I'll present where it is available on each embedded kit supported by this book and then how you can get access and use it. For each device kind I'll show to you how you can easily manage it with practical examples.

Below is a brief introduction of each chapters related to the second part:

Chapter 6 , General Purposes Input Output signals - GPIO, will introduce GPIO lines with a short description and then we'll see where they are physically located in our embedded machines. Then we're going to see in detail how we can get access to these lines in a very simple (but poor efficient) manner and then in a smarter (but a bit more complex) way. In the end we'll cover a rapid introduction of the GPIOs management inside the kernel with IRQ management and LED devices support.

Chapter 7 , Serial Ports and TTY Devices - TTY, will introduce serial ports, that is one of the most important peripherals class a computer can have (at least a computer used in the control automation industry). After a brief description about what a serial port or a serial device is, we'll see how we can manage them into a GNU/Linux system in order to use a real serial device. Then we'll take a look at a kernel trick useful to communicate between two embedded systems by using a serial line as they were connected by an Ethernet cable.

Chapter 8 , Universal Serial Bus - USB, will introduce the USB bus, that is a versatile bus, widely used in modern PCs, that allow people to connect an electronic device to a computer: for instance an hard disk, a keyboard or a serial device can be all connected to a computer through the same USB port.

Chapter 9 , Inter-Integrated Circuits - I2C, will introduce the I2C bus which is typically used to connect on-board devices, that is the main computer with devices whose are all placed on the same board. Several devices use the I2C bus to communicate with the CPU and in this chapter will give to you a panoramic as wide as possible of them: we'll see several kinds of different devices with different configurations in order to cover as much as possible the combinations offered by this bus.

Chapter 10 , Serial Peripheral Interface - SPI, will introduce the SPI bus which is another bus kind typically used to connect on-board devices as I2C does. However, and opposed to the I2C bus, this bus can transfer data at higher rates than I2C and, since it's full-duplex, data transfer can take place bidirectionally at the same time. Due these features the SPI bus is normally used to implement an efficient data stream for multimedia applications or digital signal processing and/or telecommunications devices and SD cards.

Chapter 11, 1-Wire - W1, will introduce Ethernet devices whose add the possibility to any equipped device to communicate with other devices even on very long distances. The GNU/Linux based systems offer a really good support of Ethernet devices and their relative networking protocols that's why most of networking devices around the world are based on this technology.

Chapter 12, Ethernet network device - ETH, will introduce the one wire bus which is interesting because it permits to communicate with a remote device using only one wire even if at slower rates. This allows to simplify connections between the CPU and its peripherals giving the designer the possibility to have the most economical and simply way to add electronic devices for identification, authentication and delivery of calibration data or manufacturing information to a computer board.

Chapter 13 , Wireless Network Device - WLAN, will introduce Wireless network devices whose allow the communication between several computers but doing it without using wires. What is really interesting in using these networking interfaces is that a large part of communication protocols used on Ethernet interfaces can be used with these devices too!

Chapter 14 , Controller Area Network - CAN, will introduce the CAN bus that has been specifically designed to allow microcontrollers, computers and devices to communicate with each other in applications without a host computer by having a message-based protocol. The CAN bus is not so famous as Ethernet or WiFi but in the embedded world it is used and is not rare finding SoCs which support it by default.

Chapter 15 , Sound devices - SND, will introduce sound devices with some possible usages of them till to show to the reader how they can use them in order to generate audio how to implement a simple and low cost oscilloscope.

Chapter 16 , Video devices - V4L, will introduce common video acquisition devices with some possible usages of them till to show to the reader how they can turn our embedded kits into a surveillance camera or a remote image recorder.

Chapter 17 , Analog-to-Digital Converters - ADC, will introduce ADCs that can be used to get analogical signals from the environment. The chapter will show how to use them and how to use special software and hardware triggers in order to start conversions at specific timing or when some events occur.

Chapter 18 , Pulse-Width Modulation - PWM, will introduce PWMs that are able to encode a message into a pulsing signal (usually a square waveform) to generate an analog signal by using a digital source, then these messages can be used to control the power supplied to electrical motors or other electronics devices or, as we're going to show into this chapter, to control the position of a servo motor.

Chapter 19 , Miscellaneous devices, will introduce peripherals that can fit in one of the above chapters but that has not reported there for better readability. In this last chapter we're going to present a list of additional peripherals we can encounter into a monitoring or controlling system such as RFID and smart card readers, some digital and analog sensors, GSM/GPRS modem, Z-Wave, etc.

What you need for this book

Following are the requisites for efficient learning.

Software prerequisite

Regarding the software you should have a little knowledge of a non graphical text editor as vi, emacs or nano. Even if you can connect an LCD display, a keyboard and a mouse directly to embedded kits and then use the graphical interface, in this book we assume that you is able to do little modifications to text files by using a text only editor.

The host computer, that is the computer you will use to cross-compile the code and/or to manage your embedded systems, is assumed running a GNU/Linux based distribution. My host PC is running an Ubuntu 15.10 but you can use also a newer Ubuntu Long Term Support (LTS) or a Debian based system too with little modifications or you may use another GNU/Linux distribution but with a little effort from you mainly regarding the cross-compiling tools installation, libraries dependencies and packages management. Foreign systems such as Windows, MacOS or similar are not covered by this book due the fact you should not use low technology systems to develop code for high technology system!

Knowing how a C compiler works and how to manage a Makefile is required.

This book will present some kernel programming techniques but these must cannot be taken as a kernel programming course. You need a proper book for such topic! However each example is well documented and you will find several suggested resources. Regarding the kernel I'd like to state that the version used into this book is 4.4.x.

As a final note I suppose that you known how to connect a GNU/Linux based board on the Internet in order to download a package or a generic file.

Hardware prerequisite

In this book all code is developed for BeagleBone Black board revision C, for SAMA5D3 Xplained revision A or for the WandBoard revision C1 (depending on the board used) but you can use an older revision without any issues, in fact the code is portable and it should work on other systems too (but the DTS files whose must be considered apart)!

Regarding the computer peripherals used in this book I reported in each chapter where I got the hardware and where you can buy it but, of course, you can decide to surf the Internet in order to find a better and cheaper offer. A note where to find the datasheet is also present.

You should not have any difficulties in order to connect the hardware presented in this book with the embedded kits since the connections are very simple and well documented. They don't require any particular hardware skills to be performed from you (apart knowing how to use a solder), however having a minor knowledge in electronics may help.

Who this book is for

If you want to learn how to use embedded machine learning capabilities and get access to a GNU/Linux device driver to collect data from a peripheral or to control a device, this book is for you.

If you are interested in knowing how to easily and quickly get access to different computer peripherals in order to realize a functional control or monitor system based on GNU/Linux for industrial applications, this book is for you.

If you have some hardware or electrical engineering experience and know the basics of C, Bash, and Python and PHP programming in a UNIX environment and want using them into an embedded system, this book is for you.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Codes and command lines

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs and user input are shown as follows: "To get the preceding kernel messages, we can use both the dmesg and tail -f /var/log/kern.log commands."

A block of code is set as follows:

#include <stdio.h> 
 
int main(int argc, char *argv[]) 
{ 
    printf("Hello World!\n"); 
 
    return 0; 
} 

You should note that most code in this book has 4 spaces indentation while the example code you can find into the files provided with this book on Github or Packt site, has 8 spaces indentation. So the above code will look like as follow:

#include <stdio.h> 
 
int main(int argc, char *argv[]) 
{ 
        printf("Hello World!\n"); 
 
        return 0; 
}

Obviously they are perfectly equivalent!

Any command line input or output given on one of the embedded kits used in this book is written as follows:

 root@bbb:~# make CFLAGS="-Wall -O2" helloworld 
 cc -Wall -O2 helloworld.c -o helloworld 

Then by looking into the prompt string we can deduce which board we're currently using. I use the string bbb for the BeagleBone Black, a5d3 for the SAMA5D3 Xplained and wb for the WandBoard. However I use the generic string arm when I'm referring a generic embedded kit.

Note also that due space reasons into the book you may read very long commands lines as follows:

$ make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf- 
 sama5d3_xplained_nandflash_defconfig

Otherwise I have had to break the command line. However in some special cases you can find broken output lines (specially on kernel messages) as follow:

cdc_ether 2-1.1:1.0 usb0: register 'cdc_ether' at usb-0000:00:1d.0-1.1 , CDC Ethernet Device, 62:1e:f6:88:9b:42

Unluckily these lines cannot be easily reported into a printed book so you should consider them as a single line.

Any command line input or output given on my host computer as a non- privileged user is written as follows:

$ tail -f /var/log/kern.log

When I need to give a command as a privileged user (root) on my host computer the command line input or output is then written as follows:

# /etc/init.d/apache2 restart

You should notice that all privileged commands can be executed by a normal user too by using the sudo command with the form:

$ sudo <command>

So the preceding command can be executed by a normal user as:

$ sudo /etc/init.d/apache2 restart

Kernel and logging messages

On several GNU/Linux distribution a kernel message has the usual form:

Oct 27 10:41:56 hulk kernel: [46692.664196] usb 2-1.1: new high-speed USB device number 12 using ehci-pci

Which is a quite long line for this book, that's why the characters from the start of the lines till the point where the real information begin are dropped. So, in the preceding example, the lines output will be reported as follow:

usb 2-1.1: new high-speed USB device number 12 using ehci-pci

However, as just said above, if the line is still too long it will be broken anyway.

Long outputs, repeated or less important lines in a terminal are dropped by replacing them with three dots ... shown as follows:

output begin
output line 1
output line 2
...
output line 10
output end

When the three dots are at the end they mean that the output continues but I decided cut it for space reasons.

File modifications

When you should modify a text file, I'm going to use the unified context diff format since this is a very efficient and compact way to represent a text modification. This format can be obtained by using the diff command with the -u option argument.

As a simple example, let's consider the following text into file1.old:

This is first line 
This is the second line 
This is the third line 
... 
... 
This is the last line 

Suppose we have to modify the third line as highlighted in the following snippet:

This is first line 
This is the second line 
This is the new third line modified by me 
... 
... 
This is the last line 

You can easily understand that reporting each time the whole file for a simple modification it's quite obscure and space consuming, however by using the unified context diff format the preceding modification can be written as follow:

$ diff -u file1.old file1.new 
--- file1.old 2015-03-23 14:49:04.354377460 +0100 
+++ file1.new 2015-03-23 14:51:57.450373836 +0100 
@@ -1,6 +1,6 @@ 
 This is first line 
 This is the second line 
-This is the third line 
+This is the new third line modified by me 
 ... 
 ... 
 This is the last line 

Now the modification is very clear and written in a compact form! It starts with a two-line header where the original file is preceded by --- and the new file is preceded by +++, then follows one or more change hunks that contain the line differences in the file. The preceding example has just one hunk where the unchanged lines are preceded by a space character, while the lines to be added are preceded by a + character and the lines to be removed are preceded by a - character.

Still for space reasons, most patches reported into this book has reduced indentation in order to fit printed pages width, however they are still perfectly readable in a correct form. For the real patch you should refer to the provided files on Github or Packt site.

Serial & network connections

In this book I'm going to mainly use two different kind of connections to interact with the the embedded boards: the serial console, an SSH terminal and an Ethernet connection.

The serial console, that is implemented over the same USB connection used to power up the board, is mainly used to manage the system from the command line. It's largely used to monitoring the system especially to take under control the kernel messages.

An SSH terminal is quite similar to the serial console even if is not exactly the same (for example kernel messages do not automatically appear on a terminal) but it can be used in the same manner as a serial console to give commands and to edit files from the command line.

In the next chapters I'm going to use a terminal on the serial console or over an SSH connection indifferently to give the most of the commands and configuration settings needed to implement all the prototypes explained in this book.

To get access to the serial console from your host PC you can use the minicon command as follow:

$ minicom -o -D /dev/ttyACM0

Or the next one according to the board and/or the USB-to-Serial adapter used:

$ minicom -o -D /dev/ttyUSB0

However in Chapter 1 , Installing the Developing System, this aspects are explained and you should not worry about them. Note also that on some system you may needs the root privileges to get access to the /dev/ttyACM0 device. In this case you can fix this issue or by using the sudo command or, better, by properly add you system's user to the right group by using the command below:

$ sudo adduser $LOGNAME dialout

Then log out and log in again and you should access the serial devices without any problem.

To get access to the SSH terminal you can use the emulated Ethernet connection over the same USB cable used for the serial console. In fact, if your host PC is well configured, when you plug in the USB cable, after a while, you should see a new cable connection with a proper IP address (in case of the BeagleBone Black you should get the address 192.168.7.1, for the SAMA5D3 Xplained the address 192.168.8.1, while address 192.168.9.1 for the WandBoard. See Chapter 1 , Installing the Developing System ). Then, for example, I can use this new connection to get access to the BeagleBone Black by using the following command:

$ ssh root@192.168.7.2

The last available communication channel is the Ethernet connection. It is used mainly to download files from the host PC or the Internet and it can be established by connecting an Ethernet cable to the each embedded kit's Ethernet port and then configuring the port accordingly to the reader's LAN settings.

But it's quite important to point out the you can get connected with the Internet by using also the emulated Ethernet connection over USB presented above. In fact, by using the commands below on the host PC (obviously GNU/Linux based), you'll be able to use it as a router allowing your embedded boards to surf the net as it was connected with its real Ethernet port:

# iptables --table nat --append POSTROUTING --out-interface eth1 -j MASQUERADE
# iptables --append FORWARD --in-interface eth4 -j ACCEPT
# echo 1 >> /proc/sys/net/ipv4/ip_forward

Then, for instance, on the BeagleBone Black I should set the gateway through the USB cable using the following command:

root@bbb:~# route add default gw 192.168.7.1

Note that the eth1 device is the preferred Internet connection on my host system, while the eth4 device is the BeagleBone Black's device as viewed on my system.

Other conventions

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Clicking the Next button moves you to the next screen."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail feedback@packtpub.com , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors .

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com . If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.
  2. Hover the mouse pointer on the SUPPORT tab at the top.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box.
  5. Select the book for which you're looking to download the code files.
  6. Choose from the drop-down menu where you purchased this book from.
  7. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows
  • Zipeg / iZip / UnRarX for Mac
  • 7-Zip / PeaZip for Linux

The complete set of code can also be downloaded from the following GitHub repository: https://github.com/PacktPublishing/GNU-Linux-Rapid-Embedded-Programming/. We also have other code bundles from our rich catalog of books and videos available at: https://github.com/PacktPublishing/. Check them out!

For this book the example code files can also be downloaded from the author's Github repository at URL https://github.com/giometti/gnu_linux_rapid_embedded_programming .

Just use the following command to get it at once:

$ git clone https://github.com/giometti/gnu_linux_rapid_embedded_programming.git

The examples are grouped according to the chapters name so you can easily find the code during the reading of the book.

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/GNULinuxRapidEmbeddedProgramming.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata , selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at copyright@packtpub.com with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at questions@packtpub.com , and we will do our best to address the problem.