Contents at a Glance
CHAPTER 1
Introduction
There is one primary goal for this book: to teach you how to use the C programming language to control the Atmel family of microcontrollers. 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, we can give you some facts that might help your decision: 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 in the framework of the Integrated Development Environment (IDE) that is available as a free Internet download from Atmel. This means you will not have to buy additional programming tools to learn C. The implementation of C provided with the IDE is not a full American National Standards Institute (ANSI) implementation of the C programming language. This implementation, which I will henceforth call Arduino C, is a robust subset of ANSI C, and, as such, we are free to skip over those elements of the C language that are not available to you. Although this makes the amount of details to learn a bit smaller, it also means that some features found in ANSI C have to be “worked around.”
Even in light of these first two considerations, 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 will be. True, we will have some small hardware projects to exercise your code, but the real purpose of the projects is to test your understanding of C—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 expertise.
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 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. 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. Also, I wrote my first C programming text 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 (or all?) of them. I 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. (Details about some suppliers can be found in Appendix A.) Some 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 that tests 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. Admittedly, there are some 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 exercises. This means you need to invest in a microcontroller and some additional components. I've made every attempt to keep these component costs as inexpensive as possible while still demonstrating the point at hand. 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. 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.
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. 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. 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 card. (Let's use “µc” for “microcontroller” from now on.) Atmel produces a wide variety of controllers, but 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 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 Flash memory. (Note that 2K–8K of Flash memory is eaten up by the bootloader, which allows you to communicate with the outside world, so plan accordingly.)
Most µc boards are shipped with the required USB (A to B) cable. If your board did not include one, then you can steal your printer cable and use it until you can find a replacement. Again, look online for these and you should be able to buy one for less than a few dollars.
Memory
With regard to memory, you will want to consider the following:
- Flash – The programs you will 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 to the µc board. The program code is stored in the card's flash memory. This 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 it is the flash memory size that will likely limit your program size. As mentioned above, 2K to 8K of flash memory is used for the software that allows you to communicate with the outside world, including your PC.
- SRAM – Simply stated, the Static Random Access Memory (SRAM) is where your program variables (data) get stored during program execution. Data in SRAM are usually lost when power is removed from the controller board. We will have more to say about this in later chapters, but for now, the amount of SRAM probably won't be a real issue for most programs.
- EEPROM – Electrically Erasable Programmable Read Only Memory (EEPROM) is an area of nonvolatile memory where one often stores data that need to be retrievable even after power to the board has been removed, then restored. Unlike the data values stored in SRAM, which are lost when power is lost, data values stored in EEPROM survive power removal. Because of this, EEPROM memory is often used to store configuration or other types of information that are needed when the system powers up. Again, we will have more to say about this type of memory later in the book.
So, should it be the memory or I/O pins that dictate your µc choice? Again, it depends on what you hope to do with the µc, but for most readers, the amount of Flash memory will likely be the most important limitation. Given that, buy the card with the most Flash memory that your pocketbook allows. Table 1.1 shows some of the compatible boards that you may want to consider for use with this book.
Size
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 dictates a larger footprint for the card. Figure 1-1 shows two of the popular µc boards and the relative sizes when compared to a playing card.
There is also a slightly smaller board called the Nano that has similar specs as the Atmel328 board with some minor differences (e.g., no power jack like you see near the upper-left corner of both boards in Figure 1-1).
Cost
As you would 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 $20 and the one based on the ATmega1280 for under $30. Appendix A presents a list of suppliers that you may wish to consider. Note that there are numerous clones for each of the Arduino family available. As a general rule, buy the “biggest” you can comfortably afford. 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.
Breadboard
A breadboard is used to prototype electronic projects. By using special 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 simplify the hardware requirements as much as possible. Still, a 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.) You will 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.
Miscellaneous Parts
Every attempt has been made to minimize the number of electronic parts you will need to complete an exercise. In many cases, we will reuse components between exercises. Appendix B presents a list of the parts that you will need to complete all of 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 µc board). 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.
Although you could read this book without buying anything else, not having the minimal components and a compatible ATmega-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. With a little effort and a few dollars, you should be able to buy what you need.
VERIFYING THE SOFTWARE
A µc without software is like a bicycle without handlebars. Like any other computer, a µc needs program instructions for it to do something useful. Arduino has provided all the software tools you need to write program code as a free download from their website. The remainder of this section discusses downloading, installing, and testing the software you need.
Start your Internet browser and go to:
There you will find the Arduino software download choices for Windows, Mac OS X, and Linux. Click on 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.0.1-windows.zip
. You should see something similar to that shown in Figure 1-3.
After you have downloaded the software, extract the zip file to a directory of your choice. You should see something similar to that shown in Figure 1-3. I named my directory
Arduino1.0.1
. Inside the directory, double-click on the arduino.exe
file. In a few moments, you may see a warning similar to that shown in Figure 1-4. You should click “Run” to install the Arduino software.
Within a few seconds, you should see the IDE for the Arduino. It should look similar to that shown in Figure 1-5.
If you see the IDE, then you can be fairly certain that the software download was performed successfully. Now that you have the software installed, we can check to see whether your controller board is functioning properly.
VERIFYING THE HARDWARE
Now that you have the Arduino IDE software installed, let's connect your computer to the µc board, load a small program, and verify that all components are working together. First, you need to connect the USB cable to your µc board and then plug the other end of the USB cable into your computer.
Attaching the USB Cable
Figure 1-6 shows the µc board with the USB cable connected to it. Most companies give you the A-B type USB cable when you buy the µc board.
As you no doubt have figured out, the unattached end of the USB cable should be plugged into a USB port connector on your computer. The minute you connect the USB cable to your powered-up computer, power is applied to the µc board and an LED will light on the µc board. Obviously, the USB connection is supplying the voltage necessary to drive the µc board. The USB 2.0 specs suggest that the cable must supply between 4.4 and 5.25 volts at a maximum current of 500 mA. This is not a lot of power. However, most µc boards also provide a small power jack (the black barrel-like thing located on the upper-left corner of the board in Figure 1-6) where a “wall wart” with greater power can be plugged into the power jack to drive the system. None of our projects require more current than can be provided by the USB connection. (If you are using a USB hub, then make sure the hub provides 500 mA to each port.)
Selecting Your µc Board in the Integrated Development Environment
The Arduino IDE supports a variety of different µc boards. Therefore, you must tell the IDE which board you will be using for writing your program code. Figure 1-7 shows the menu sequence (Tools Boards) that you use to select your µc board. In this example, I have selected the Arduino Diecimila or Duemilanove w/ ATmega168 menu choice.
You should select the menu choice that matches the µc board you will be using. If you change µc boards at some future date, then simply come back to this menu and reselect the board to which you are changing.
Port Selection
The IDE does a pretty good job of automatically figuring out which USB port you have selected to power and communicate with the µc board. To determine which port is being used, simply use the Tools Serial Port menu sequence, as shown in Figure1-8. For my particular setup, COM port 8 is being used to communicate with the µc board.
If you are having difficulty determining which port should be used, then you can use the Windows Control Panel to examine which ports are assigned to what. For example, using Windows 7, the first step is to select the Device Manager option from the Control Panel list, as shown in Figure 1-9.
If you cannot find the device drivers or if you are having problems configuring the port selection, then the solution consists of the following steps:
- Select Control Panel Devices and Printers.
- The Devices and Printers screen is broken into horizontal panes. The first has icons for Devices (those that fit certain predefined categories). The second pane has icons for installed Printers and Faxes. The third pane lists Unspecified devices. The Arduino Uno showed up in the third pane as an Unknown Device.
- Double-click the Unknown Device icon.
- In the resulting Unknown Device Properties dialog, select the Hardware tab, then click the Properties button.
- On the General tab of the new dialog that pops up (“Unknown device Properties”), click Change Settings.
- Click Update Driver.
- Choose Browse my computer for driver software.
- In the dialog that pops up, browse to the
drivers
subdirectory of the directory that you extracted the Arduino 1.0.1 software into, and click Next.- You will get a Windows security warning that the drivers are not signed. Choose “Install anyway.”
- You should get a message that Windows has updated the driver.
- The port should now show up in the list of serial ports when you select Tools Serial Port in the Arduino IDE.
After the Device Manager loads, you can look at the port devices by clicking on the small triangle next to the Ports list. This is shown in Figure 1-10. As you can see in the figure, the USB Serial Port has been assigned to the COM port 8. This is exactly what you saw in Figure 1-8.
Now that you are reasonably certain that the software and hardware seem to be connected and working properly, let's load a small program into the IDE and see whether we can run it.
LOADING AND RUNNING YOUR FIRST PROGRAM
The Arduino IDE has gone through numerous revisions over the years. The current version is the first to carry the “Arduino1” moniker, suggesting that the IDE software is now consider stable. Earlier versions of the IDE generated a default secondary file name of “pde,” which reflected that the source files (also called “sketches”) were written under the Processing Development Environment (pde). With the latest release, the default secondary file name has been changed to “ino.” The change was made so there wouldn't be conflicts with the source files that were created with earlier versions of the IDE. (Thus far, I have not found out why “ino” was selected. So, I'm just going to assume that it is because it squares with the last three letters in Arduino.) The latest version of the IDE can read the earlier “pde” files but resaves them as “ino” files by default.
What we need to do now is load and run an “ino” project file to see that everything is working properly. Although we could write a short program from scratch, I really don't want to do that yet. We simply don't have enough information under our belt at this junction to make much of a learning experience from the process.
Rather than writing our own program, we will load and run a sample program that is included as part of the IDE download.
The Blink Program
Probably every programming book written for the Arduino family has a short program that blinks an LED. For that reason, the IDE download includes that program in the
Examples
subdirectory that is designed to blink an LED. Figure 1-11 shows you how to locate that program.
As you can see in Figure 1-11, the Blink program file is located by following the directory path of:
Arduino1.0.1\examples\01.Basics\Blink
Because you likely installed your download at a different base directory than I did, the path shown here should be “tacked onto” the directory you chose. For example, if you created a directory named
LearningC
and installed the IDE there, your directory would look like:LearningC\Arduino1.0.1\examples\01.Basics\Blink
Once you know where the files reside, use the File Open menu sequence to navigate to the
Blink
folder. Open the Blink
folder and select the Blink.ino
file. This can be seen in Figure 1-12. Once the source code file is load, a new copy of the IDE with the source code is presented to you.
The new IDE that contains the program code should look similar to Figure 1-13. We're going to ignore the actual program code for now, because our real interest at this moment is simply to see whether the program can be run. You will be able to understand the code soon enough. For now, however, let's get to the good stuff.
Running the Blink Program Code
The program code that appears in Source Code Window in Figure 1-13 is written in the C programming language. (Hopefully, that's not a surprise to you.) The Source Code Window is the area with a white background in the figure and has a white “tab” at the top with the name of the program “Blink” written on it. The Source Code Window is used to enter and edit the code that you want the program to execute. The program code is presented in a more-or-less readable format that looks a little bit like normal English narrative. The computer, however, is as dumb as a box of rocks when it comes to understanding English. Indeed, the computer only understands two things: (1) on or (2) off—hence the term “binary computer.” These two states (on and off) are represented by a 1 for an On state and a 0 for an Off state. Simply stated, by stringing these 1s and 0s together in a very specific sequence, we can make the computer do what we wish.
Back in the early days of PC programming, some computers (e.g., the MITS Altair) actually had switches that were flipped on or off, and, when the sequence formed a computer instruction you wanted to perform, you pressed a button and that sequence of 1s and 0s (i.e., Ons and Offs) was deposited into computer memory. Hours later, you might have a program that said “Hi” on the computer screen. Programming a computer back then was a very laborious and error-prone process. In fact, you could often figure out who was a computer programmer by looking for “binary blisters” on their fingers. (Experienced programmers had binary callouses.)
Luckily, things have changed. Now we have a program, called a compiler, which translates the English-like C language program instructions into the proper 1s and 0s sequences for us. The Arduino IDE has a compiler built into it that does the translation work for us. Because the Blink program was written by someone else and is included in the software IDE download, we can feel pretty safe that there are no errors in the sample program. We'll have a lot to say about finding and fixing program errors later on. For now, however, we'll assume the program is error-free and ready to compile.
Compiling the Blink Program Code
Figure 1-14 shows the toolbar line near the top of the IDE. The left-most button (the one with the checkmark) on the toolbar is used to compile the program that is currently displayed in the Source Code Window of the IDE. After you have loaded the program code for the Blink program, you can click on the Compile button and the IDE examines the code for errors and, finding none, compiles the program.
If no errors are found, then you will see a message similar to that shown in Figure 1-15 near the bottom of the screen. If you look at the message at the bottom of the figure, then you will see it says that the “Binary sketch size” is 1,084 bytes. What this means is that the compiled Blink program used up 1,084 bytes of memory to generate the necessary sequence of 1s and 0s to accomplish the task the program is designed to do. It also tells us that there are about 14,336 bytes of (unused) memory still available to us.
Wait a minute! I'm using a ATmega168, which has 16K (or 16,384) bytes of flash memory. Well, 16,384 minus 1,084 should be 15,300 bytes—not 14,336 bytes. What happened to the extra 964 bytes? Recall from our discussion of Table 1-1 that some of the flash memory is used for the bootloader software. As a result, not all of the flash memory is available for our program code. Although the software documentation says that 2K of memory is used for the bootloader, which really means that it won't use more than 2K of flash memory.
Uploading the Blink Program
After you have compiled the program, it is still sitting in your PC's memory, not the µc. Therefore, you need to click the Upload button (see Figure 1-14) to move the compiled program instructions from your PC's memory to the flash memory on your µc board. (This is also known as the Verify button, but that seems to be a bad name choice since it gives the impression that the button is somehow verifying the code. I'll stick with Upload to describe using this button.) As the upload progresses, you will see small LED's flash on and off on the µc board as the upload proceeds. This simply reflects the communication process that transpires over the serial connection between your PC and the µc board (via the USB cable).The instant the upload is complete, our blink program begins to execute. (On some older boards, you may have to press a reset button on the µc board to start the program running.) Figure 1-16 shows the LED with the blink LED turned on. The LED at the top is also on, but that LED is used to denote that power is being applied to the board. The LED at the lower left is the one that is blinking.
Taa-daa! You have successfully installed the IDE software and connected your µc board to your PC. In addition, you have loaded, compiled, uploaded, and run your first program. Congratulations!
Now the real fun begins.
SUMMARY
In this chapter you learned about the Arduino development environment and some of the board choices you can use that support the Atmel chip family. Some of the hardware details about the boards were discussed to help you decide which board to use while you learn about programming the board using Arduino C. You then downloaded the Arduino development environment and installed the IDE. As a check on the IDE installation, you loaded the sample Blink program from the examples supplied with the IDE, compiled, and downloaded it to the board to verify that everything was installed correctly. You are now ready to start learning Arduino C.
No hay comentarios:
Publicar un comentario