Preface - Make: AVR Programming (2014)

Make: AVR Programming (2014)


Microcontroller projects are ubiquitous in the hobbyist/hacker/Maker world, and with good reason. Microcontrollers stand directly in the middle ground between the hardware world of buttons, motors, and lights and the software world of algorithms, connectivity, and infinite possibility. Microcontrollers are part computer and part electrical component. They can also be the metaphorical glue between the real world and the virtual world.

Why This Book?

Are you sending a balloon with a small payload to near space? Need a small bit of computing power to read your temperature sensors and accelerometer and log the data to an SD card without using too much power? A microcontroller is just what you need. Would you like to build your own small robot or a cute interactive toy for your niece? There’s a microcontroller application there, too. I’m sure that you’ve seen a million interesting projects online, wondered, “How’d they do that?” and gotten the answer: a microcontroller. Without their capable microcontroller brains, the homegrown 3D printing scene would be nowhere. Microcontrollers are at the center of an emerging culture of people building the previously impossible.

The goal of this book is to get you building projects with microcontrollers and writing your own firmware (or using libraries from other people) in C. I’ve chosen the Atmel AVR series microcontrollers to focus on because they have a fantastic free and open toolchain, easily available programming hardware, and many of you probably have one or two already on hand in the form of Arduinos. A large part of the collaborative hacker community uses these chips, so it’s as good a starting point as any. The ATmega168 chip family that we’ll be using is right now the sweet spot in price-per-functionality, but it is not hard to port your code to smaller and cheaper if you want to or move over to other AVR chips if you need to.

I picked the C language because it’s pretty much the standard for programming microcontrollers. It’s just at the right point, for my taste, in terms of being abstract enough to read but low-level enough that turning an individual bit on or off doesn’t require subclassing or overriding anything. Your C code will compile down to something that is nearly as efficient as the best-written assembler, but it’s a heck of a lot easier to maintain. There’s also a ton of code examples out there on the Web for you to look at and learn from. (That said, if you really want a good feel for how the hardware works, teach yourself AVR assembler when you’re done with this book.)

On the other hand, this book is really a book about programming and using microcontrollers in general. Though the particular naming conventions and some of the implementation details are different across different brands of microcontrollers, the basic principles will be the same. More on this in just a minute.

Software Type or Hardware Type?

In a class on programming microcontrollers that I taught at my local hackerspace, I discovered that the students would identify largely as either hardware types or software types. Some people coded JavaScript for web applications all day, while others worked in electrical and machine shops. One guy had never seen a for loop, and another didn’t know that the red wire is the positive side of a battery pack. Everyone had something to learn, but it was almost never the same thing for everyone.

In building your microcontroller projects, you’re going to need to think both like a software type and a hardware type, even if only one of these initially comes naturally to you. At times you’re going to need to debug code algorithms, and at other times you’re going to need to figure out exactly what’s going on electrically when that button is pushed or that motor is energized. This need to put on two different hats, sometimes even at the same time, characterizes microcontroller and embedded applications.

Throughout this book, there’ll be some concepts that are too obvious to you, but which may be entirely perplexing to others. I’ll be swapping my software-type and hardware-type hats accordingly. In the end, you’ll become familiar enough with both worlds that you’ll be able to navigate the middle ground. You’ll know you’ve reached embedded-design nirvana when you begin coding with the hardware. Then you’ll have become a microcontroller type!


And so we come to my sincerest goal in writing this book instead of simply another blinky-LEDs-on-an-Arduino manual—to turn you into a true microcontroller type. Although the Arduino environment is good for getting people hooked on microcontrollers, it’s a cheap high. Arduino/Wiring goes to great lengths to abstract away from the microcontroller’s hardware. Here, I want to teach you about the hardware—because it’s useful—so getting further away from it won’t help. (My friend Ash once described working with the Arduino environment as being “like knitting in boxing gloves.”)

I don’t think that the built-in hardware timer modules are something to be abstracted away from. I believe the timers should be understood thoroughly enough to be abused to create a small AM radio transmitter that can play the Mario theme song within a room using nothing more than a wire or your finger as an antenna (in Chapter 9). And I believe that this code should fit in under 500 bytes of program memory.

More seriously, many of the hardware peripherals inside the AVR are common to most microcontrollers, from the “prehistoric” 8051 or the tiniest PIC or ATtiny chips, through the MSP430s and the ATmegas, to the mighty XMega and ARM chips. These hardware peripherals have been developed and honed over 40 years of microcontroller design development, and they’re not going away any time soon because they have been designed to be helpful to getting your project realized. The microcontroller hardware has been designed by very clever engineers to solve your problems. My goal in writing this book is to show you how common problems are solved. You need to learn the hardware, and apply the hardware, to love the hardware.

Although every microcontroller design implements things a little bit differently, once you’ve seen it here, it will make sense there. Every microcontroller that I’ve ever come across is programmable in C. Almost all of what you learn working through this book istransferrable to other chips and other architectures, because what you’re learning here is the way things work rather than an abstraction wrapped around the way things work, designed to protect you from the way things work. Some of what you learn (for instance bitwise binary manipulations in Chapter 4) might seem boring, but in the end it will give you simple and direct access to the common hardware bits that are put there to help you, and the techniques will work with any brand of microcontroller that you choose to use.

In short, almost none of the time you spend learning about how to create projects on the AVR in C will be wasted. Yeah, it’s a bit harder than just reusing someone’s shields and code. Yeah, you might need to stop sometimes and leaf through a C programming book or an electronics text (or just look it up on the Net). But when you find out that you need more processing power, or a different set of peripherals, you can just buy yourself a $8 chip in place of the $4 one you were using and bring most of your code, and more importantly your knowledge, along with you.

This book is meant to be the red pill, and I sincerely hope that you find it worth your time once you’ve seen how deep the rabbit hole goes.

You Will Need…

Before we get too much into detail about the AVR chips and what they can do for you, let me provide you with a shopping list. Order this stuff now so that you can be ready to start programming chips in a few days when the delivery truck shows up.

The Basic Kit

Here is a basic kit of parts that you’ll need throughout the rest of your AVR life. A lot of this gear is multipurpose, and you’ll have some of these parts on hand if you’re playing around with electronics. The following is the basic kit that you’ll use for programming AVRs throughout the book:

§ A solderless breadboard or two or three. I like the 800-contact type because of the extra working space, but a few smaller breadboards can be nice for building subcircuits on. You can never have too much workspace.

§ A number of wire jumpers to plug in to the breadboard. I really like the prebuilt ones with rubber grips and pins on the end. You can often find these sold in combination with breadboards for cheap at online auction websites.

§ You should probably have a small resistor assortment on hand. You’ll need a bunch in the 200–500 ohm range for LEDs, a few around 1k ohm, and at least five in the 10k ohm range.

§ An ISP programmer (see Flash Programmers I Have Known and Loved for recommendations) or Arduino (see AVR and the Arduino).

§ An ATmega168, 168A, 168P, or 168PA. Make sure you get one in the DIP package if you want to plug it into the breadboard. The parts I’m using at the moment are called ATMEGA 168A-PU, where the “PU” denotes a DIP part. See The AVR Family of Microcontrollers for more on chip selection.

§ A USB-to-serial adapter. I’m a big fan of the FTDI USB-Serial cable. Get the 3.3 V-compatible one for maximum flexibility. It works painlessly with all operating systems, and at all speeds. A variety of online geekery stores have slightly cheaper options as well.

§ At least 10 LEDs (any color) and 10 appropriately sized resistors: 200–500 ohms. You can never have enough LEDs.

§ A source of 5 V DC power (optional). Many of the ISP programmers provide power to the breadboard. If yours doesn’t, cutting up a 5 V wall-wart power supply or using a 4xAA battery pack will work. Rechargeable batteries are even better.

For the Basic Projects

§ A small 8 ohm (normal) speaker and roughly 10–100 uF capacitor. I got my speaker from an old keyboard toy.

§ Two or more pushbuttons. Normally open. Cheap tactile switches are great.

§ At least 5x 2N7000 MOSFETs.

§ Two light-dependent resistors (LDRs), but you might as well buy an assorted pack.

§ Two potentiometers. 10k ohms is ideal. Anything above 1k ohms will work.

For the Intermediate Projects

§ A piezo disk, preferably with wires attached.

§ A servo. Any old hobby servo will do. I get my cheap ones from Tower Hobbies.

§ A laser pointer that you’re willing to take apart.

§ An I2C device to talk to—my example uses the very common LM75 temperature sensor.

§ An SPI device to talk to. Here, I’m using a 25LC256 32K SPI EEPROM chip.

For the Motors and H-Bridge Chapters

§ A small DC motor (3–12 V is good). I got mine from a racecar toy.

§ MOSFETs for building an H-Bridge. I use two IRF9530s and two IRF530s.

§ SN754410 or L293D motor driver chip instead of or in addition to the MOSFETs.

§ A stepper motor and a power supply to drive it.

§ Random switch-like devices: relays, SSRs, Darlington transistors (TIP120, etc.).

§ Random DC-powered devices like LED lamps or pumps or fans or solenoids or kids’ toys or…

§ A 5 V relay.

Deluxe and Frills

§ A standalone voltmeter.

§ An amplified speaker—computer speakers are ideal.

§ A soldering iron and some solder.

§ A prototype board for soldering up your circuits permanently.

§ Extras of everything in the first list so that you can create permanent versions of each chapter’s project that you like. Nothing beats having a bunch of souvenirs around to show off what you’ve learned and to go back to and modify later on.

Conventions Used in This Book

The following typographical conventions are used in this book:


Indicates new terms, URLs, email addresses, filenames, and file extensions.

Constant width

Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords.

Constant width bold

Shows commands or other text that should be typed literally by the user.

Constant width italic

Shows text that should be replaced with user-supplied values or by values determined by context.

This icon signifies a tip, suggestion, or general note.

This icon indicates a warning or caution.