download whole pdf by paying server
There is one primary goal for this book: to teach you how to use the C programming language. The
environment for reaching that goal is the Atmel family of microcontrollers. While C can be used to program
other microcontrollers, our emphasis is on the Atmel controllers. Given that there are probably a bazillion C
programming books available to you, why should you choose this one? Good question, and there’s no single
answer. However, I can give you some facts that might help with making your decision.
First, this book is specifically written for the Arduino family of microcontroller boards using the
Atmel family of microcontroller chips. As such, the book is couched within the framework of an integrated
development environment (IDE) that is available as a free Internet download. An IDE is a single program
that combines all of the functions required to progress from the C language source code you are writing to
an executable program. In essence, an IDE is a text editor, compiler, assembler, and linker all rolled into
one program. Having the free Arduino IDE means you will not have to buy additional programming tools
to learn C.
Second, the implementation of C provided with the IDE is not quite a full American National Standards
Institute (ANSI) implementation of the C programming language. This implementation of the C language,
which I will henceforth call Arduino C, is a robust, and virtually complete, subset of ANSI C. (The most
obvious missing feature is the double data type, although float is supported.) In fact, the underling compiler
you will be using throughout this book is the open source C++ compiler (GCC), which is full-featured. You
will learn more about the language features available to you as we proceed through the book.
Why Choose This Book?
Even in light of the considerations mentioned, there are still probably dozens of books that cover Arduino C.
So, why choose this book over the dozens that remain available to you?
First, this is a programming book and that is where the emphasis is. True, there are some small
hardware projects to exercise your code, but the real purpose of the projects is to test your understanding
of the C programming language—not the hardware. Once you have mastered C, Apress has a family
of books that are centered on the Arduino microcontroller that you may use to extend your hardware
Second, I will take you “under the hood” of the C language, so you gain a much deeper understanding
of what the code is doing and how it is done. This knowledge is especially useful in a programming
environment where you have only a few pico-acres of memory available to you. There are those who say you
really don’t have to understand a language with any real detail to use it. To reinforce their argument, I have
often heard the comment: “You don’t have to know how to build a car to drive one.” True, but if your car
Electronic supplementary material The online version of this chapter (doi:10.1007/978-1-4842-0940-0_1)
contains supplementary material, which is available to authorized users.
CHAPTER 1 ■ INTRODUCTION
breaks down 200 miles north of Yellowknife, NWT, I’ll bet you’d wish you had a better understanding of the
details that make a car tick. The same is true for programming. The better you understanding what is going
on with the language, the quicker you will be able to detect, isolate, and fix program bugs. (A program bug
is an error in the program that prevents it from performing its designed task correctly.) Also, there are often
multiple solutions possible for any given programming problem. A little depth of understanding frequently
yields a more efficient and unbreakable, yet elegant, solution.
Third, since I first began using C in 1977, I have gained a lot of commercial programming experience
with C that just might come in handy. My software company produced C compilers and other development
tools for the early PCs back in the 1980s. Also, I wrote my first C programming book more than 30 years
ago. Still, the biggest advantage that has some worth to you is my teaching experience. Honestly, there are
likely thousands of programmers who can code circles around me. Indeed, one of my employees was such
a person. However, to be a good author, it matters little how good you are as a programmer or an engineer if
you cannot convey that experience to others.
I have more than 30 years of university-level teaching experience, and I know where you are most likely
to stumble in our upcoming journey. The bad news is that you will stumble along the way. The good news
is that there have been thousands before you who have stumbled on exactly the same concepts, and I have
managed to develop effective teaching methods to overcome most (all?) of them. I also think you will find
the book’s style both engaging and informative.
Finally, I genuinely enjoy programming with the C language. Of all the different languages I have
used since I first began programming in the late 1960s, C remains my favorite. It is a concise, yet powerful,
language well suited for microcontroller work. I think you’re going to like it, too.
This chapter details what you need to use this book effectively, including some comments about the
expectations I have about you. You will learn about some of the features that different Arduino-compatible
boards have, their approximate cost, and where they can be purchased. Also, there are many Arduino
Starter Kits available now and they are a wonderful way to get started because they usually contain the
Arduino board plus numerous electronic components with which you can experiment. (Details about some
suppliers can be found in Appendix A.) Suggestions are also made about some additional hardware items
you may wish to purchase. The chapter then tells you where and how to download and install the IDE for
the Arduino IDE. The chapter closes out with a short C program to verify that the IDE installation went as
expected. When you finish reading this chapter, you will have a good understanding of what you need to
use this book effectively.
Assumptions About You
Clearly, I’m targeting this book for a specific reader. In so doing, I have made certain assumptions about
that reader: I assume the reader knows absolutely nothing about C or programming in general. In fact, I
hope you don’t know anything. That way, you can start with a clean slate. Often, someone who knows some
programming aspects brings along a lot of bad habits or ill-conceived practices that need to be “unlearned.”
Starting off with no programming experience is, in this case, a very good thing.
I assume you know nothing about electronics. Indeed, this book is not meant to be an electronics book.
However, there are a few hardware concepts used throughout the book, but you will be taught what you need
to know to make things function properly. If you want to gain a deeper understanding of the electronics, I’d
suggest finishing this text and then buying one of the other Apress books that targets your specific hardware
area of interest.
I assume you will do the programming exercises found at the end of each chapter. Most of the exercises
are software-based, meaning they require little or no additional electronic components to complete
the exercise. Clearly, some hardware is needed to test even a purely software exercise: you must have a
microcontroller board to type in and run the software in the exercise. This means you need to invest in a
microcontroller board and some additional components. I’ve made every attempt to keep these component
costs as low as possible while still demonstrating the point at hand.
CHAPTER 1 ■ INTRODUCTION
Appendix A presents a list of vendors from whom you can buy various components at reasonable cost.
Failing that, almost all of the components can be bought from a local Radio Shack outlet. (Alas, Radio Shack
just filed for bankruptcy.) Appendix B presents a list of the miscellaneous hardware components you will
need to complete all of the projects in this book. Obviously, some of these components can be ignored if
certain projects are not attempted. As mentioned earlier, there are some great Arduino experimenter kits
that not only include an Arduino-compatible board, but also dozens of components and other devices that
can be used to make some really interesting projects. I especially like the MAKER Version Electronic Brick
Starter Set from yourduino.com and the Ultimate Kit from oddWires.com. Both kits contain components to
do all of the exercises in this book, plus many, many more (see Appendix A).
Finally, I assume you don’t have to know C by this weekend. That is, I assume you will do the exercises
and take the time to study and understand the code in the examples before moving on to the next chapter.
Learning C is a building process whereby the concepts learned in the current chapter become a foundation
for subsequent chapters. A crumbly understanding of the concepts of one chapter will likely cause a collapse
of that understanding in later chapters. Take your time, pause and think about what you’re reading, and do
the exercises . It’s easy to read something and say “I understand that.” It’s quite another to start with a blank
page and write a program that uses what you’ve read. Simply stated: Do the exercises. If you try to take
shortcuts and bypass the exercises, then your depth of knowledge will be less than it would be otherwise.
Take your time and enjoy the ride.
What You Need
In addition to this book, there are several things you will need, plus some things you should have but could
live without. Consider the components and factors discussed in the following sections.
An Atmel-Based Microcontroller Card
You will need to have access to an Atmel microcontroller board. (Let’s use “ μ c” for “microcontroller” from
now on.) Atmel produces a wide variety of μ cs and there are literally dozens of clone boards available. You
should consider purchasing an Arduino board based on one of those listed in Table 1-1 . So, how do you
decide which one to purchase? It really depends on what you want to do with the μ c. If all you want to do
is blink an LED or control a toaster, then one of the least expensive boards listed in the table probably will
do just fine. If you are setting up some kind of experiment that must sample several dozen sensors every
second, then you will probably want to use a μ c that has a lot of digital and/or analog I/O pins. If your
application is going to have a lot of program code associated with it, then obviously you should pick one with
more memory. (Note that 2K to 8K of flash memory is eaten up by the bootloader. A bootloader is a small
program that allows your μ c to communicate with the outside world, so plan accordingly.)
The Arduino IDE is run on your PC, so most of the actual program development takes place on your PC.
When you think the program code is in a state that can be tested, you compile and “upload” your code to the
μ c via a USB cable connected between your PC to the μ c.
Most μ c boards are shipped with the required USB (A to B) cable. If your board did not include one, often
you can steal your printer cable and use it until you can find a replacement. Also note that some boards do not
have a USB connector on the board. While these boards are less expensive, they require an external programming
interface, which is less convenient. For the time being, only consider a board that has a USB connector on it.
Again, look online for the USB cables and you should be able to buy one for less than a few dollars.
Types of Memory
With regard to memory, you will want to consider what’s outlined in the following sections.
CHAPTER 1 ■ INTRODUCTION
The programs you develop using this book are written on your PC. When you have the program code to a
point where you think it is ready to test, you upload that program code from your PC to the μ c board via the
USB connection. The program code is stored in the Arduino’s flash memory. Flash memory is nonvolatile,
which means that, even if you disconnect the board from its power source, the contents of the flash memory
remain intact. It is probably obvious that your program must fit within the limits imposed by the amount of
flash memory on your Arduino board.
As mentioned, 2K to 8K of flash memory is used for the software (i.e., the bootloader) that allows your
program to communicate with the outside world, including your PC. Therefore, if your Arduino has 32K
of flash memory, your program code actually must be less than 24K to 30K in size, depending on the size
of your bootloader code. Also, flash memory has a finite life in terms of the number of times that you can
rewrite it reliably before it gets a little flaky. Most set the safe write cycle at 100,000 writes. So, according to
the documentation, if you save the program 10 times a day, you only have 27 years of reliability available
Simply stated, the static random-access memory (SRAM) is where your program variables (data) get stored
during program execution. You should assume that the data stored in SRAM is lost when power is removed
from the controller board.
Because SRAM is used to pass data back and forth between functions, creating temporary variables as
the program executes, SRAM plays an important limiting factor in the amount of data your programs can
use. I will have more to say about this in later chapters, but for now, the more SRAM, the better.
Electrically Erasable Programmable Read-Only Memory (EEPROM) is an area of nonvolatile memory where
one often stores data that needs to be retrievable each time the program is run. Like flash memory, data
values stored in EEPROM survive power removal.
However, EEPROM has two drawbacks when compared to flash memory: it is a little slower to
access than flash memory, and like flash memory, it too has about 100,000 read/write cycles before it
becomes unreliable. Because of these factors, EEPROM memory is often used to store configuration
or other types of information that are needed when the system powers up, but are not often changed.
For example, you might have some sensors that need to have certain values sent to them before they can be
used, or other devices that need to be initialized with specific data. EEPROM would be a likely candidate
for storing such configuration data. Again, I will have more to say about this type of memory later
in the book.
Making the Choice
So, should it be the amount of memory, I/O pin count, processor speed, or something else that dictates
your μ c choice? Again, it depends on what you hope to do with the μ c, but for most readers, the amount of
flash and SRAM memory will likely be the most important limitations. But even those two parameters have
CHAPTER 1 ■ INTRODUCTION
For example, you might want to have a program that generates a sine wave for a function generator.
Because μ cs are not that fast, you decide not to calculate the sine values on the fly, but rather to store
pre-calculated sine wave values in a table stored in memory. When you look at the program, you see that
the program code is pretty small but the amount of memory to store the sine table is large. Therefore,
the limiting factor in your design is the amount of SRAM needed to hold the table, not the flash memory
for the program instructions. (You might also store the table in EEPROM memory.) If you don’t have a
specific program task in mind, buy a board that has the most flash and SRAM memory your pocketbook
Table 1-1 shows some of the compatible boards that you may want to consider for use with this book.
1. The Due has two analog input pins.
2. This is not an Atmel chip, but produced by Diligent and can be programmed using C and an IDE that looks
virtually identical to the Arduino IDE. It is based on the PIC32 (32-bit) microcontroller.
The physical size of the μ c card may also be important to you, depending on your planned application. As you
might expect, larger available memory and more I/O pins dictate a larger footprint for the card. Figure 1-1
shows several popular μ c boards. To get some perspective, the center board is a little smaller than the size of
a deck of cards. The Digispark board (bottom right in Figure 1-1 ) is about the size of a postage stamp. You can
also “roll your own” board using an 8-pin ATTiny85 chip (8K flash, 512 bytes SRAM and EEPROM) creating a
really small board size.
Table 1-1. Atmel Microcontrollers Commonly Used in Arduino Boards
input pins Voltage
Arduino Uno 32K 2K 1K 16Mhz 14 6 5V
Arduino Nano 32K 2K 1K 16Mhz 14 8 5V
Digispark Pro 16K 2K 1K 16Mhz 14 10 5V
RoboRED 32K 2K 1K 16Mhz 14 6 5 or 3.3V
ATmega1280 128K 8K 4K 16Mhz 54 16 5V
ATmega2560 256K 8K 4K 16Mhz 54 16 5V
Arduino Leonardo 32K 2.5K 1K 16Mhz 20 12 5V
Arduino Due 512K 96K – 84Mhz 54 12/2 1
ChipKIT Max32 2
512K 128K – 80Mhz 83 16 3.3
CHAPTER 1 ■ INTRODUCTION
Input/Output (I/O) Pins
As you might expect, a μ c with more memory and I/O pins cost a little more. For example, some ATmega328-
based boards can be purchased for under $5 and those based on the ATmega2560 for under $15. The Due
(pronounced “do-eh”) costs around $25, whereas the Leonardo is about $10. (Table 1-1 is only a partial
feature list. Consult the spec sheets for those boards you are considering.) Appendix A presents a list of
suppliers that you may wish to consider. Note that there are numerous clones available for each member
of the Arduino family. (For a good discussion of clones, compatibles, derivatives, and counterfeit boards,
see http://arduino-info.wikispaces.com/Arduino-YourDuino .) As a general rule, buy the “biggest” you
can comfortably afford that is consistent with the project(s) you have in mind. Hardware projects are often
subject to “feature creep,” where more and more functionality is requested as the project goes forward.
“Buying bigger than you need” is often a good idea if you can afford it.
A breadboard is used to prototype electronic projects. By using jumper wires that plug into the holes on the
breadboard, it is easier to create and modify an electronic circuit. The hardware elements found in this text
are not a central feature. Indeed, I have tried to limit the hardware requirements as much as possible. Still, a
Figure 1-1. Sizes of two different Arduino boards, one based on the Atmega1280 (left) and one based on the
Atmega328 (right) relative to a standard playing card.
CHAPTER 1 ■ INTRODUCTION
breadboard is a useful addition to your tool chest and you should consider investing in one. Figure 1-2 shows
a typical breadboard. I like this type of breadboard because it has two sets of power feeds and four banks of
tie points. (The one shown has 2,800 tie points—the little “holes” where you can insert wires, components,
ICs, and so forth. This is about twice the size you will likely need, but it’s what I had on hand.) You also
need some jumper wires to connect the tie points. I purchased the breadboard shown in the figure with 150
jumper wires for less than $20. There are smaller, less expensive breadboards available.
If your breadboard doesn’t come with jumper wires, then make sure you purchase some—you’ll need
them! Note that jumper wires are sold as male-to-male, male-to-female, and female-to-female and with
different lengths. As to the type to get, I would get a mixture of all three types, although you will likely use the
male-to-male most often. I would lean toward the longer lengths (e.g., 10″). I prefer the Dupont-style jumper
wires, as they tend to be a little more durable.
Figure 1-2. A typical breadboard
CHAPTER 1 ■ INTRODUCTION
Every attempt has been made to minimize the number of electronic parts you need to complete an exercise.
In many cases, we reuse components between exercises. Appendix B presents a list of the parts that you
need to complete all the exercises found in this book. With some judicious shopping on eBay, you can
probably buy all of the components for less than $15 (excluding the breadboard and μ c boards). While you
are at it, you might look for some “rubber feet” that can be stuck to the bottom of your board. That way, if you
slide the board across a table, it won’t scratch it. I won’t even mention what can happen if you slide a naked
board across a table that has a paperclip on it.
I’ve already stated that several experimenter kits are available. If you buy one of these kits, you will have
all of the components necessary to do any of the projects listed in this text. Some even come with a carrying
case that keeps the components organized. I’ve only recently started using starter kits, and I find them to be
very useful and convenient. This is especially true if you’re just getting started with μ cs.
Although you could read this book without buying anything else, not having minimal components and
a compatible Arduino-based board would seriously dilute the learning experience. You really should have
the electronic components available to you. You might also find out if your community has a local amateur
radio (i.e., ham radio) club. Club members are always willing to offer advice about where you can find
various electronic components at reasonable cost. Your local community college or university is another
possible source of information, as might be the local teacher of the high school physics class. Indeed, when I
taught at Butler University, the Physics department opened its lab on Saturday mornings to people who had
an interest in learning electronics. To his credit, Dr. Marshal Dixon was the instructor who ran the program
free of charge. Perhaps your community has a similar program. It doesn’t hurt to check. Also, there are very
active MakerSpaces in many communities that often have faires with Arduino/Electronics sections. With a
little effort and a few dollars, you should be able to buy what you need.
Installing and Verifying the Software
A μ c without software is about as useful as a bicycle without peddles. Like any other computer, a μ c needs
program instructions for it to do something useful. Arduino has provided all the software tools within their
(free) IDE that you need to write program code. The remainder of this section discusses downloading,
installing, and testing the software you need.
Start your Internet browser and go to http://arduino.cc/en/Main/Software . There you will find the
Arduino software download choices for Windows, Mac OS X, and Linux. Click the link that applies to your
development environment. Because I use the Windows operating system for program development, the
file that was downloaded was named arduino-1.5.8-windows.zip . The latest Arduino IDE available at the
time this is being written is Release 1.5.8 Beta. (Just before we went to press, Release 1.6.0 was announced.
It’s too late to change all the narrative and retest, but the latest release should work just fine.) You are
asked to select the directory where you wish to extract the files. I named my directory Arduino1.5.8 and
placed it off the root of the C drive (e.g., C:\Arduino1.5.8 . ) Regardless of the exact number of the release,
you should see something similar to that shown in Figure 1-3 when you start extracting the files from the
CHAPTER 1 ■ INTRODUCTION
Inside the Arduino directory you just created, double-click the arduino.exe file. In a few moments, you
may see a splash screen similar to that shown in Figure 1-4 .
Figure 1-3. Extracting the Arduino programming tools
Figure 1-4. Arduino IDE splash screen
In a few more seconds, you should see the Arduino IDE. It should look similar to that shown in Figure 1-5 .
CHAPTER 1 ■ INTRODUCTION
If you see the IDE as seen in Figure 1-5 , you can be fairly certain that the software download and
installation was performed successfully. Note that the IDE automatically provides two “empty” functions,
setup() and loop() . Because all Arduino programs require these two functions, the IDE automatically
provides empty shells for them. You fill in these shells as needed to get your program to do your bidding.
■ Note The Diligent chipMAX family is not part of the Atmel family of μ cs. The compiled program code is
different from that for the Arduino boards. The chipMAX IDE, however, looks and feels almost identical to the
Arduino IDE. You should be able to compile and upload the programs presented in this book using the chipMAX
family of boards. You can download the chipMAX IDE at http://chipkit.net/started/ . You might consider
the chipMAX because it has a little more horsepower than most Arduinos.