Arduino Micro Controller Processing For Everyone
Arduino Micro Controller Processing For Everyone
Embedded Systems Interfacing for Engineers using the Freescale HCS08 Microcontroller
II: Digital and Analog Hardware Interfacing
Douglas H. Summerville
2009
iv
Embedded Systems Interfacing for Engineers using the Freescale HCS08 Microcontroller
I: Assembly Language Programming
Douglas H.Summerville
2009
Pragmatic Power
William J. Eccles
2008
Pragmatic Logic
William J. Eccles
2007
v
PSpice for Filters and Transmission Lines
Paul Tobin
2007
All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in
any form or by any means—electronic, mechanical, photocopy, recording, or any other except for brief quotations in
printed reviews, without the prior permission of the publisher.
DOI 10.2200/S00280ED1V01Y201005DCS028
Lecture #28
Series Editor: Mitchell A. Thornton, Southern Methodist University
Series ISSN
Synthesis Lectures on Digital Circuits and Systems
Print 1932-3166 Electronic 1932-3174
Arduino Microcontroller
Processing for Everyone!
Part I
Steven F. Barrett
University of Wyoming, Laramie, WY
M
&C Morgan & cLaypool publishers
ABSTRACT
This book is about the Arduino microcontroller and the Arduino concept. The visionary Arduino
team of Massimo Banzi, David Cuartielles,Tom Igoe, Gianluca Martino, and David Mellis launched
a new innovation in microcontroller hardware in 2005, the concept of open source hardware. Their
approach was to openly share details of microcontroller-based hardware design platforms to stimulate
the sharing of ideas and promote innovation. This concept has been popular in the software world
for many years. This book is intended for a wide variety of audiences including students of the fine
arts, middle and senior high school students, engineering design students, and practicing scientists
and engineers. To meet this wide audience, the book has been divided into sections to satisfy the
need of each reader. The book contains many software and hardware examples to assist the reader in
developing a wide variety of systems. For the examples, the Arduino Duemilanove and the Atmel
ATmega328 is employed as the target processor.
KEYWORDS
Arduino microcontroller, Arduino Duemilanove, Atmel microcontroller, Atmel AVR,
ATmega328, microcontroller interfacing, embedded systems design
ix
Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
1 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1
1.3 Arduino Duemilanove . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3.1 Arduino host processor — the ATmega328 3
1.4 Example: Autonomous Maze Navigating Robot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4.1 Structure chart 6
1.4.2 UML activity diagrams 8
1.4.3 Arduino Duemilanove Systems 9
1.5 Arduino open source schematic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.6 Other Arduino-based platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.7 Extending the hardware features of the Arduino platform . . . . . . . . . . . . . . . . . . . . . . .9
1.8 Arduino Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.9 Arduino Duemilanove/ATmega328 hardware features . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.9.1 Memory 13
1.9.2 Port System 15
1.9.3 Internal Systems 16
1.10 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.11 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.12 Chapter Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2 Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.2 The Big Picture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
x
2.3 Anatomy of a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.3.1 Comments 24
2.3.2 Include files 25
2.3.3 Functions 25
2.3.4 Program constants 28
2.3.5 Interrupt handler definitions 29
2.3.6 Variables 29
2.3.7 Main program 30
2.4 Fundamental programming concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.4.1 Operators 30
2.4.2 Programming constructs 34
2.4.3 Decision processing 36
2.5 Arduino Development Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.5.1 Background 39
2.5.2 Arduino Development Environment overview 40
2.5.3 Sketchbook concept 41
2.5.4 Arduino software, libraries, and language references 41
2.6 Application 1: Robot IR sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
2.7 Application 2: Art piece illumination system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
2.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
2.9 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
2.10 Chapter Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Author’s Biography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Preface
This book is about the Arduino microcontroller and the Arduino concept. The visionary
Arduino team of Massimo Banzi, David Cuartielles, Tom Igoe, Gianluca Martino, and David Mellis
launched a new innovation in microcontroller hardware in 2005, the concept of open source hardware.
There approach was to openly share details of microcontroller-based hardware design platforms to
stimulate the sharing of ideas and innovation. This concept has been popular in the software world
for many years.
This book is written for a number of audiences. First, in keeping with the Arduino concept,
the book is written for practitioners of the arts (design students, artists, photographers, etc.) who may
need processing power in a project but do not have an in depth engineering background. Second, the
book is written for middle school and senior high school students who may need processing power
for a school or science fair project. Third, we write for engineering students who require processing
power for their senior design project but do not have the background in microcontroller-based appli-
cations commonly taught in electrical and computer engineering curricula. Finally, the book provides
practicing scientists and engineers an advanced treatment of the Atmel AVR microcontroller.
Steve Barrett
1
CHAPTER 1
Getting Started
Objectives: After reading this chapter, the reader should be able to the following:
• Name and describe the different features aboard the Arduino Duemilanove processor board.
• Download, configure, and successfully execute a test program using the Arduino software.
1.1 OVERVIEW
Welcome to the world of Arduino! The Arduino concept of open source hardware was developed
by the visionary Arduino team of Massimo Banzi, David Cuartilles, Tom Igoe, Gianluca Martino,
and David Mellis in Ivrea, Italy. The team’s goal was to develop a line of easy-to-use microcontroller
hardware and software such that processing power would be readily available to everyone.
In keeping with the Arduino concept, this book is intended for a wide variety of readers. For
those wanting a quick exposure to an Arduino microcontroller board and its easy-to-use software,
Chapters 1 and 2 are for you. If you need to tap into some of the other features of the processing
power of the ATmega328 host microcontroller, Chapters 3 through 8 are for you.
In keeping with the Arduino open source spirit, you will find a plethora of hardware and
software examples throughout the book. I hope you enjoy reading the book, and I also hope you will
find it a useful resource in developing Arduino-based projects.
Figure 1.1: Arduino Duemilanove starter kit. (Used with permission from SparkFun Electronics.)
Power supply. The Arduino processing board may be powered from the USB port during
project development. However, it is highly recommended that an external power supply be employed.
1.3. ARDUINO DUEMILANOVE 3
This will allow developing projects beyond the limited current capability of the USB port. SparkFun
Electronics recommends a power supply from 7-12 VDC with a 2.1 mm center positive plug. A
power supply of this type is readily available from a number of electronic parts supply companies.
For example, the Jameco #133891 power supply is a 9 VDC model rated at 300 mA and equipped
with a 2.1 mm center positive plug. It is available for under US$10.
Arduino software. You will also need the Arduino software called the Arduino Development
Environment. It is available as a free download from the Arduino homepage (www.arduino.cc). In
the Application section at the end of this chapter, we describe how to load the software and drivers
and get a sample program operating on the Arduino Duemilanove board.
In the next several sections, we provide information on the layout and capabilities of the
Arduino Duemilanove board and its host the Atmel ATmega328 processor. We also discuss other
Arduino-based processing boards and how to extend the features of the Arduino Duemilanove board
using the shield concept.
e
USB-to-serial LED
nc
re
m
converter
fe
TX LED
om
re
timebase
lc
og
RX LED
ria
al
PW
PW
an
se
LED power
indicator
switch
USB
connector
(to PC)
ISP programming
connector
power supply
connector
(7-12 VDC)
power supply analog inputs
terminals
Figure 1.2: Arduino Duemilanove layout. (Figure adapted and used with permission of Arduino Team
(www.arduino.cc).)
• Memory system,
• Port system,
• Timer system,
• Analog-to-digital converter (ADC),
• Interrupt system,
• and the Serial communications.
Arduino Duemilanove
hosted on the
ATmega328
Memory System Timer System Analog-to-digital converter Serial Communications
- 32K byte, ISP - Two 8-bit timer/counter - 6 channel 10-bit ADC - Serial USART
programmable flash - One 16-bit timer/counter (PDIP) - Serial peripheral interface
- 1K byte, byte - Six PWM channels - Two wire interface (TWI)
addressable EEPROM
- 2K byte RAM
Port System Interrupt System
- 14 digital I/O pins - 26 total interrupts
-- 6 provide PWM - 2 external pin interrupts
- 6 analog input pins
Figure 1.3: Arduino Duemilanove systems.
6 1. GETTING STARTED
In this example, we will equip the Blinky 602A robot platform with three Sharp GP12D IR
sensors as shown in Figure 1.4. The robot will be placed in a maze with white reflective walls. The
goal is for the robot to detect wall placement and navigate through the maze. (Figure 1.5.) The robot
will not be provided any information about the maze. The control algorithm for the robot will be
hosted on the Arduino Duemilanove.
Sharp GP2D12
Center IR sensor
IR sensor
Left Right
IR sensor IR sensor
Arduino
Duemilanove
powered powered
wheel wheel
prototype
area
turn signals
controlling the robot. The structure chart for the robot project is provided in Figure 1.6. As you
can see, the robot has three main systems: the motor control system, the sensor system, and the
digital input/output system. These three systems interact with the main control algorithm to allow
the robot to autonomously (by itself ) navigate through the maze by sensing and avoiding walls.
determine_robot
_action
robot sensor
action data
digital
motor_control ADC
input/output
desired
motor ch for conv
action conv data
left running right
PWM_left ADC
PWM_right ReadADC turn turn
Initialize lights
signal signal
include files
global variables
function prototypes
initialize ports
initialize ADC
initialize PWM
while(1)
determine robot
action
issue motor
control signals
O
R
T
B
P
O
R
D
T
P
O
R
C
T
P
ATmega328
USB-to-USART
converter
Figure 1.8: Arduino Duemilanove open source schematic. (Figure adapted and used with permission of
the Arduino Team (www.arduino.cc).)
1.7. EXTENDING THE HARDWARE FEATURES OF THE ARDUINO PLATFORM 11
Figure 1.9: Arduino variants. (Used with permission from SparkFun Electronics.)
12 1. GETTING STARTED
Figure 1.10: Arduino shield. (Used with permission from SparkFun Electronics.)
Figure 1.11: ATmega328 pin out. (Figure used with permission of Atmel, Incorporated.)
1.9.1 MEMORY
The ATmega328 is equipped with three main memory sections: flash electrically erasable pro-
grammable read only memory (EEPROM), static random access memory (SRAM), and byte-
addressable EEPROM for data storage. We discuss each memory component in turn.
14 1. GETTING STARTED
Figure 1.12: ATmega328 block diagram. (Figure used with permission of Atmel, Incorporated.)
7 0
Port x Data Direction Register - DDRx
7 0
Port x Input Pins Address - PINx
7 0
a) port associated registers
Serial USART The serial USART is used for full duplex (two way) communication between
a receiver and transmitter. This is accomplished by equipping the ATmega328 with independent
hardware for the transmitter and receiver. The USART is typically used for asynchronous commu-
nication. That is, there is not a common clock between the transmitter and receiver to keep them
synchronized with one another. To maintain synchronization between the transmitter and receiver,
framing start and stop bits are used at the beginning and end of each data byte in a transmission
sequence.
The ATmega328 USART is quite flexible. It has the capability to be set to a variety of data
transmission rates known as the Baud (bits per second) rate. The USART may also be set for data
bit widths of 5 to 9 bits with one or two stop bits. Furthermore, the ATmega328 is equipped with
a hardware generated parity bit (even or odd) and parity check hardware at the receiver. A single
parity bit allows for the detection of a single bit error within a byte of data. The USART may
also be configured to operate in a synchronous mode. We discuss the operation, programming, and
application of the USART later in the book.
Serial Peripheral Interface—SPI The ATmega328 Serial Peripheral Interface (SPI) can also be
used for two-way serial communication between a transmitter and a receiver. In the SPI system,
the transmitter and receiver share a common clock source. This requires an additional clock line
between the transmitter and receiver but allows for higher data transmission rates as compared to
the USART.
The SPI may be viewed as a synchronous 16-bit shift register with an 8-bit half residing in
the transmitter and the other 8-bit half residing in the receiver. The transmitter is designated the
master since it is providing the synchronizing clock source between the transmitter and the receiver.
The receiver is designated as the slave. We discuss the operation, programming, and application of
the SPI later in the book.
Two-wire Serial Interface—TWI The TWI subsystem allows the system designer to network a
number of related devices (microcontrollers, transducers, displays, memory storage, etc.) together
into a system using a two wire interconnecting scheme. The TWI allows a maximum of 128 devices
to be connected together. Each device has its own unique address and may both transmit and receive
over the two wire bus at frequencies up to 400 kHz. This allows the device to freely exchange
information with other devices in the network within a small area. We discuss the TWI system later
in the book.
1.9.3.6 Interrupts
The normal execution of a program step follows a designated sequence of instructions. However,
sometimes this normal sequence of events must be interrupted to respond to high priority faults
and status both inside and outside the microcontroller. When these higher priority events occur, the
microcontroller must temporarily suspend normal operation and execute event specific actions called
an interrupt service routine. Once the higher priority event has been serviced, the microcontroller
returns and continues processing the normal program.
The ATmega328 is equipped with a complement of 26 interrupt sources.Two of the interrupts
are provided for external interrupt sources while the remaining interrupts support the efficient oper-
ation of peripheral subsystems aboard the microcontroller. We discuss the operation, programming,
and application of the interrupt system later in the book.
1.10 SUMMARY
In this chapter, we have provided an overview of the Arduino concept of open source hardware.
This was followed by a description of the Arduino Duemilanove processor board powered by the
ATmega328. An overview of ATmega328 systems followed. We then investigated various processing
boards in the Arduino line and concluded with brief guidelines on how to download and run the
Arduino software environment.
1.11 REFERENCES
• SparkFun Electronics, 6175 Longbow Drive, Suite 200, Boulder, CO 80301
(www.sparkfun.com)
• Atmel 8-bit AVR Microcontroller with 4/8/16/32K Bytes In-System Programmable Flash, AT-
mega48PA, 88PA, 168PA, 328P data sheet: 8161D-AVR-10/09, Atmel Corporation, 2325
Orchard Parkway, San Jose, CA 95131.
2. Sketch a block diagram of the ATmega328 and its associated systems. Describe the function
of each system.
20 1. GETTING STARTED
3. What is the purpose of a structure chart?
5. Describe the different types of memory components within the ATmega328. Describe appli-
cations for each memory type.
6. Describe the three different register types associated with each port.
CHAPTER 2
Programming
Objectives: After reading this chapter, the reader should be able to do the following:
• Discuss different programming constructs used for program control and decision processing.
• Describe what features of the Arduino Development Environment ease the program devel-
opment process.
• List the programming support information available at the Arduino home page.
2.1 OVERVIEW
To the novice, programming a microcontroller may appear mysterious, complicated, overwhelming,
and difficult. When faced with a new task, one often does not know where to start. The goal of
this chapter is to provide a tutorial on how to begin programming. We will use a top-down design
approach. We begin with the “big picture” of the chapter followed by an overview of the major
pieces of a program. We then discuss the basics of the C programming language. Only the most
fundamental concepts will be covered. We then discuss the Ardunio Development Environment and
how it may be used to develop a program for the Arduino Duemilanove processor board.Throughout
the chapter, we provide examples and also provide references to a number of excellent references.
22 2. PROGRAMMING
filename.c compiler
filename.h
filename.asm
assembler
filename.hex
filename.eep
computer
Arduino
Duemilanove
Arduino Development
Environment USB
ISP
or
C compiler
filename.hex
filename.eep
ISP
Figure 2.1: Programming the Arduino Duemilanove. (Used with permission from SparkFun Electronics,
and Atmel, Incorporated.)
24 2. PROGRAMMING
//include files
#include<file_name.h>
//function prototypes
A list of functions and their format used within the program
//program constants
#define TRUE 1
#define FALSE 0
#define ON 1
#define OFF 0
//global variables
Listing of variables used throughout the program
//main program
void main(void)
{
//function definitions
A detailed function body and definition
for each function used within the program
2.3.1 COMMENTS
Comments are used throughout the program to document what and how things were accomplished
within a program. The comments help you reconstruct your work at a later time. Imagine that you
wrote a program a year ago for a project. You now want to modify that program for a new project.
The comments will help you remember the key details of the program.
Comments are not compiled into machine code for loading into the microcontroller.Therefore,
the comments will not fill up the memory of your microcontroller. Comments are indicated using
2.3. ANATOMY OF A PROGRAM 25
double slashes (//). Anything from the double slashes to the end of a line is then considered a
comment. A multi-line comment can be constructed using a /∗ at the beginning of the comment
and a ∗/ at the end of the comment.
At the beginning of the program, comments may be extensive. Comments may include some
of the following information:
• file name
• program author
• program description
//include files
#include<file_name1.h>
#include<file_name2.h>
In an upcoming section, we see how the Arduino Development Environment makes it quite
easy to include a header file within a program.
2.3.3 FUNCTIONS
In the next chapter, we discuss in detail the top down design, bottom up implementation approach to
designing microcontroller based systems. In this approach, a microcontroller based project including
both hardware and software is partitioned into systems, subsystems, etc.The idea is to take a complex
project and break it into doable pieces with a defined action.
26 2. PROGRAMMING
We use the same approach when writing computer programs. At the highest level is the main
program which calls functions that have a defined action. When a function is called, program control
is released from the main program to the function. Once the function is complete, program control
reverts back to the main program.
Functions may in turn call other functions as shown in Figure 2.2. This approach results in a
collection of functions that may be reused over and over again in various projects. Most importantly,
the program is now subdivided into doable pieces, each with a defined action. This makes writing
the program easier but also makes it much easier to modify the program since every action is in a
known location.
void main(void)
{
There are three different pieces of code required to properly configure and call the function:
Function prototypes are provided early in the program as previously shown in the program
template. The function prototype provides the name of the function and any variables required by
the function and any variable returned by the function.
The function prototype follows this format:
//return variable
return return_variable;
}
Example: In this example, we describe how to configure the ports of the microcontroller to act
as input or output ports. Briefly, associated with each port is a register called the data direction register
(DDR). Each bit in the DDR corresponds to a bit in the associated PORT. For example, PORTB
28 2. PROGRAMMING
has an associated data direction register DDRB. If DDRB[7] is set to a logic 1, the corresponding
port pin PORTB[7] is configured as an output pin. Similarly, if DDRB[7] is set to logic 0, the
corresponding port pin is configured as an input pin.
During some of the early steps of a program, a function is called to initialize the ports as input,
output, or some combination of both. This is illustrated in Figure 2.3.
//function prototypes
void initialize_ports(void);
//main function
void main(void)
{
//program constants
#define TRUE 1
#define FALSE 0
#define ON 1
#define OFF 0
2.3. ANATOMY OF A PROGRAM 29
2.3.5 INTERRUPT HANDLER DEFINITIONS
Interrupts are functions that are written by the programmer but usually called by some hardware
event during system operation. We discuss interrupts and how to properly configure them in an
upcoming chapter.
2.3.6 VARIABLES
There are two types of variables used within a program: global variables and local variables. A global
variable is available and accessible to all portions of the program. Whereas, a local variable is only
known and accessible within the function where it is declared.
When declaring a variable in C, the number of bits used to store the operator is also specified.
In Figure 2.4, we provide a list of common C variable sizes used with the ImageCraft ICC AVR
compiler. The size of other variables such as pointers, shorts, longs, etc. are contained in the compiler
documentation [ImageCraft].
Figure 2.4: C variable sizes used with the ImageCraft ICC AVR compiler [ImageCraft].
//global variables
unsigned int loop_iterations = 6;
2.4.1 OPERATORS
There are a wide variety of operators provided in the C language. An abbreviated list of common
operators are provided in Figures 2.5 and 2.6. The operators have been grouped by general category.
The symbol, precedence, and brief description of each operator are provided.The precedence column
indicates the priority of the operator in a program statement containing multiple operators. Only
the fundamental operators are provided. For more information on this topic, see Barrett and Pack
in the Reference section at the end of the chapter.
General
Symbol Precedence Description
{} 1 Brackets, used to group program statements
() 1 Parenthesis, used to establish precedence
= 12 Assignment
Arithmetic Operations
Symbol Precedence Description
* 3 Multiplication
/ 3 Division
+ 4 Addition
- 4 Subtraction
Logical Operations
Symbol Precedence Description
< 6 Less than
<= 6 Less than or equal to
> 6 Greater
>= 6 Greater than or equal to
== 7 Equal to
!= 7 Not equal to
&& 9 Logical AND
|| 10 Logical OR
Unary Operations
Symbol Precedence Description
! 2 Unary negative
~ 2 One’s complement (bit-by-bit inversion)
++ 2 Increment
-- 2 Decrement
type(argument) 2 Casting operator (data type conversion)
The assignment operator (=) is used to assign the argument(s) on the right-hand side of an
equation to the left-hand side variable. It is important to insure that the left and the right-hand side
of the equation have the same type of arguments. If not, unpredictable results may occur.
return sum;
2.4. FUNDAMENTAL PROGRAMMING CONCEPTS 33
}
Answer: Variable “variable1” is declared as an eight bit unsigned char and assigned the hex-
adecimal value of (73)16 . In binary this is (0111_0011)2 . The << 2 operator provides a left shift of
the argument by two places. After two left shifts of (73)16 , the result is (cc)16 and will be assigned
to the variable “variable2.”
Note that the left and right shift operation is equivalent to multiplying and dividing the
variable by a power of two.
The bitwise operators perform the desired operation on a bit-by-bit basis. That is, the least
significant bit of the first argument is bit-wise operated with the least significant bit of the second
argument and so on.
Example: Given the following code segment, what will the value of variable3 be after execu-
tion?
Answer: Variable “variable1” is declared as an eight bit unsigned char and assigned the hex-
adecimal value of (73)16 . In binary, this is (0111_0011)2 . Variable “variable2” is declared as an eight
bit unsigned char and assigned the hexadecimal value of (f a)16 . In binary, this is (1111_1010)2 .
34 2. PROGRAMMING
The bitwise AND operator is specified. After execution variable “variable3,” declared as an eight bit
unsigned char, contains the hexadecimal value of (72)16 .
i++;
Example: It is not uncommon in embedded system design projects to have every pin on a
microcontroller employed. Furthermore, it is not uncommon to have multiple inputs and outputs
assigned to the same port but on different port input/output pins. Some compilers support specific
pin reference. Another technique that is not compiler specific is bit twiddling. Figure 2.7 provides
bit twiddling examples on how individual bits may be manipulated without affecting other bits using
bitwise and unary operators.The information provided here was extracted from the ImageCraft ICC
AVR compiler documentation [ImageCraft].
a&b bitwise and if ((PINA & 0x81) == 0) // check bit 7 and bit 0
In the following code fragment the for loop is executed ten times.
The for loop begins with the variable “loop_ctr” equal to 0. During the first pass through the
loop, the variable retains this value. During the next pass through the loop, the variable “loop_ctr”
is incremented by one. This action continues until the “loop_ctr” variable reaches the value of ten.
Since the argument to continue the loop is no longer true, program execution continues after the
close bracket for the for loop.
In the previous example, the for loop counter was incremented at the beginning of each loop
pass. The “loop_ctr” variable can be updated by any amount. For example, in the following code
fragment the “loop_ctr” variable is increased by three for every pass of the loop.
The “loop_ctr” variable may also be initialized at a high value and then decremented at the
beginning of each pass of the loop.
}
36 2. PROGRAMMING
As before, the “loop_ctr” variable may be decreased by any numerical value as appropriate for
the application at hand.
The while loop is another programming construct that allows multiple passes through a
portion of code. The while loop will continue to execute the statements within the open and close
brackets while the condition at the beginning of the loop remains logically true. The code snapshot
below will implement a ten iteration loop. Note how the “loop_ctr” variable is initialized outside of
the loop and incremented within the body of the loop. As before, the variable may be initialized to
a greater value and then decremented within the loop body.
loop_ctr = 0;
while(loop_ctr < 10)
{
//loop body
loop_ctr++;
}
Frequently, within a microcontroller application, the program begins with system initialization
actions. Once initialization activities are complete, the processor enters a continuous loop. This may
be accomplished using the following code fragment.
while(1)
{
• the if statement,
• switch statement.
The if statement will execute the code between an open and close bracket set should the
condition within the if statement be logically true.
Example: To help develop the algorithm for steering the Blinky 602A robot through a maze,
a light emitting diode (LED) is connected to PORTB pin 1 on the ATmega328. The robot’s center
2.4. FUNDAMENTAL PROGRAMMING CONCEPTS 37
IR sensor is connected to an analog-to-digital converter at PORTC, pin 1. The IR sensor provides
a voltage output that is inversely proportional to distance of the sensor from the maze wall. It is
desired to illuminate the LED if the robot is within 10 cm of the maze wall. The sensor provides an
output voltage of 2.5 VDC at the 10 cm range. The following if statement construct will implement
this LED indicator. We provide the actual code to do this later in the chapter.
In the example provided, there is no method to turn off the LED once it is turned on. This
will require the else portion of the construct as shown in the next code fragment.
The if–else if—else construct may be used to implement a three LED system. In this exam-
ple, the left, center, and right IR sensors are connected to analog-to-digital converter channels on
PORTC pins 2, 1, and 0, respectively. The LED indicators are connected to PORTB pins 2, 1, and
0. The following code fragment implements this LED system.
switch(new_PORTD)
{ //process change in PORTD input
case 0x01: //PD0
//PD0 related actions
break;
That completes our brief overview of the C programming language. In the next section, we provide
an overview of the Arduino Development Environment. You will see how this development tool pro-
vides a user-friendly method of quickly developing code applications for the Arduino Duemilanove
processing board.
2.5.1 BACKGROUND
The first version of the Arduino Development Environment was released in August 2005. It was
developed at the Interaction Design Institute in Ivrea, Italy to allow students the ability to quickly put
40 2. PROGRAMMING
processing power to use in a wide variety of projects. Since that time, newer versions incorporating
new features, have been released on a regular basis [www.arduino.cc].
At its most fundamental level, the Arduino Development Environment is a user friendly
interface to allow one to quickly write, load, and execute code on a microcontroller. A barebones
program need only consist of a setup() and loop() function.The Arduino Development Environment
adds the other required pieces such as header files and the main program construct. The ADE is
written in Java and has its origins in the Processor programming language and the Wiring Project
[www.arduino.cc].
In the next several sections, we introduce the user interface and its large collection of user
friendly tools. We also provide an overview of the host of built-in C and C++ software functions
that allows the project developer to quickly put the features of the Arduino Duemilanove processing
board to work for them.
sketch_feb15a
Open
Verify/Compile
Save
Stop
Serial monitor
Menu
repeated here. Instead, we refer to these features at appropriate places throughout the remainder of
the book as we discuss related hardware systems.
Keep in mind the Arduino open source concept. Users throughout the world are constantly
adding new built-in features. As new features are added, they will be released in future Arduino
Development Environment versions. As an Arduino user, you too may add to this collection of
useful tools. In the next section, we illustrate how to use the Arduino Duemilanova board in several
applications.
Display EEPROM Library Liquid Crystal Display Servo Library Stepper Library
- LED bar graph - EEPROM clear Library - Knob - Motor knob
- Row column scanning - EEPROM read - Hello World - Sweep
- EEPROM write - Blink
- Cursor
- Display
- Text Direction
- Scroll
- Serial Input
- SetCursor
6
1-7/16
5 VDC
220
10K
2N2222
3 21 0 9 8 76 5 4 32 1 0
1 1 1 1 DIGITAL
Ground
Arduino
Duemilanove
ANALOG IN
5VGnd 0 123 4 5
R Y B
IR sensor
The IR sensor’s power (red wire) and ground (black wire) connections are connected to the 5V
and Gnd pins on the Arduino Duemilanove board, respectively. The IR sensor’s output connection
(yellow wire) is connected to the ANALOG IN 5 pin on the Arduino Duemilanove board. The
LED circuit shown in the top right corner of the diagram is connected to the DIGITAL 0 pin on
the Arduino Duemilanove board. We discuss the operation of this circuit in the Interfacing chapter
later in the book.
46 2. PROGRAMMING
Earlier in the chapter, we provided a framework for writing the if-else statement to turn the
LED on and off. Here is the actual sketch to accomplish this.
//*************************************************************************
#define LED_PIN 0 //digital pin - LED connection
#define IR_sensor_pin 5 //analog pin - IR sensor
void setup()
{
pinMode(LED_PIN, OUTPUT); //configure pin 0 for digital output
}
void loop()
{
//read analog output from IR sensor
IR_sensor_value = analogRead(IR_sensor_pin);
The sketch begins by providing names for the two Arduino Duemilanove board pins that will
be used in the sketch. This is not required but it makes the code easier to read. We define the pin
for the LED as “LED_PIN.” Any descriptive name may be used here. Whenever the name is used
within the sketch, the number “0” will be substituted for the name by the compiler.
After providing the names for pins, the next step is to declare any variables required by the
sketch. In this example, the output from the IR sensor will be converted from an analog to a digital
value using the built-in Arduino “analogRead” function. A detailed description of the function may
be accessed via the Help menu. It is essential to carefully review the support documentation for a
built-in Arduino function the first time it is used. The documentation provides details on variables
required by the function, variables returned by the function, and an explanation on function operation.
2.7. APPLICATION 2: ART PIECE ILLUMINATION SYSTEM 47
The “analogRead” function requires the pin for analog conversion variable passed to it and
returns the analog signal read as an integer value (int) from 0 to 1023. So, for this example, we
need to declare an integer value to receive the returned value. We have called this integer variable
“IR_sensor_value.”
Following the declaration of required variables are the two required functions for an Arduino
Duemilanove program: setup and loop. The setup function calls an Arduino built-in function, pin-
Mode, to set the “LED_PIN” as an output pin. The loop function calls several functions to read the
current analog value on pin 5 (the IR sensor output) and then determine if the reading is above 512
(2.5 VDC). If the reading is above 2.5 VDC, the LED on DIGITAL pin 0 is illuminated, else it is
turned off.
After completing writing the sketch with the Arduino Development Environment, it must be
compiled and then uploaded to the Arduino Duemilanove board. These two steps are accomplished
using the “Sketch – Verify/Compile” and the “File – Upload to I/O Board” pull down menu selections.
In the next example, we adapt the IR sensor project to provide custom lighting for an art
piece.
2.8 SUMMARY
The goal of this chapter was to provide a tutorial on how to begin programming. We used a top-
down design approach. We began with the “big picture” of the chapter followed by an overview
of the major pieces of a program. We then discussed the basics of the C programming language.
Only the most fundamental concepts were covered. We then discussed the Arduino Development
Environment and how it may be used to develop a program for the Arduino Duemilanove processor
48 2. PROGRAMMING
Figure 2.14: Lac Laronge, Saskatchewan. Image used with permission, Jonny Barrett, Closer to the Sun
Fine Art and Design, Park City, Utah. [www.closertothesunfineartndesign.com]
board. Throughout the chapter, we provided examples and also provided references to a number of
excellent references.
2.9 REFERENCES
• ImageCraft Embedded Systems C Development Tools, 706 Colorado Avenue, #10-88, Palo
Alto, CA, 94303, www.imagecraft.com
• S. F. Barrett and D.J. Pack, Embedded Systems Design and Applications with the 68HC12
and HCS12, Pearson Prentice Hall, 2005.
• Jonny Barrett, Closer to the Sun Fine Art and Design, Park City, UT,
www.closertothesunfineartndesign.com
2.10. CHAPTER PROBLEMS 49
• Barrett S, Pack D (2006) Microcontrollers Fundamentals for Engineers and Scientists. Morgan
and Claypool Publishers. DOI: 10.2200/S00025ED1V01Y200605DCS001
• Barrett S and Pack D (2008) Atmel AVR Microcontroller Primer Programming and Inter-
facing. Morgan and Claypool Publishers. DOI: 10.2200/S00100ED1V01Y200712DCS015
• Barrett S (2010) Embedded Systems Design with the Atmel AVR Microcontroller. Morgan
and Claypool Publishers. DOI: 10.2200/S00225ED1V01Y200910DCS025
5. What are the three pieces of code required for a program function?
7. Provide the C program statement to set PORTB pins 1 and 7 to logic one. Use bit-twiddling
techniques.
8. Provide the C program statement to reset PORTB pins 1 and 7 to logic zero. Use bit-twiddling
techniques.
10. When should a switch statement be used versus the if-then statement construct?
11. What is the serial monitor feature used for in the Arduino Development Environment?
12. Describe what variables are required and returned and the basic function of the following
built-in Arduino functions: Blink, Analog Input.
51
CHAPTER 3
To answer these questions, the designer interacts with the client to ensure clear agreement
on what is to be done. If you are completing this project for yourself, you must still carefully and
thoughtfully complete this step. The establishment of clear, definable system requirements may
require considerable interaction between the designer and the client. It is essential that both parties
agree on system requirements before proceeding further in the design process. The final result of
this step is a detailed listing of system requirements and related specifications.
Project Description
- What is the system supposed to do?
- Operating conditions and environment
- Formal requirements
Background Research
- Thoroughly understand desired requirements and features
- Determine applicable codes, guidelines, and protocols
- Determine interface requirements
Pre-Design
- Brainstorm possible solutions
- Thoroughly investigate alternatives
- Choose best possible solution
- Identify specific target microcontroller
- Choose a design approach
Implement Prototype
- Top down versus bottom up
- Develop low risk hardware test platform
- Software implementation
Preliminary Testing
- Develop test plan to insure requirements
have been met
- Test under anticipated conditions
- Test under abusive conditions
- Redo testing if errors found
- Test in low cost, low risk environment
- Full up test
no
Complete and Accurate Documentation
- System description
- Requirements
- Structure chart
- UML activity diagram
- Circuit diagram
- Well-documented code
- Test plan
Deliver Prototype
3.2.3 PRE-DESIGN
The goal of the pre-design step is to convert a thorough understanding of the project into possible
design alternatives. Brainstorming is an effective tool in this step. Here, a list of alternatives is devel-
oped. Since an embedded system typically involves both hardware and/or software, the designer can
investigate whether requirements could be met with a hardware only solution or some combination
of hardware and software. Generally, speaking a hardware only solution executes faster; however, the
design is fixed once fielded. On the other hand, a software implementation provides flexibility and
a typically slower execution speed. Most embedded design solutions will use a combination of both
hardware and software to capitalize on the inherent advantages of each.
Once a design alternative has been selected, the general partition between hardware and
software can be determined. It is also an appropriate time to select a specific hardware device to
implement the prototype design. If a microcontroller technology has been chosen, it is now time to
select a specific controller. This is accomplished by answering the following questions:
• What microcontroller systems or features i.e., ADC, PWM, timer, etc.) are required by the
design?
• How many input and output pins are required by the design?
• What is the maximum anticipated operating speed of the microcontroller expected to be?
Recall from Chapter 1 there are a wide variety of Arduino-based microcontrollers available
to the designer.
3.2.4 DESIGN
With a clear view of system requirements and features, a general partition determined between
hardware and software, and a specific microcontroller chosen, it is now time to tackle the actual
design. It is important to follow a systematic and disciplined approach to design. This will allow
for low stress development of a documented design solution that meets requirements. In the design
step, several tools are employed to ease the design process. They include the following:
• Using a Unified Modeling Language (UML) activity diagram to work out program flow, and
• Propelled through the maze using the two powered wheels provided in the Blinky 602A kit
and a third drag wheel for stability.
• Equipped with LEDs, one for each IR sensor, to indicate a wall has been detected by a specific
sensor.
Pre-design. With requirements clearly understood, the next step is normally to brainstorm
possible solutions. In this example, we have already decided to use the Arduino Duemilanove pro-
cessing board. Other alternatives include using analog or digital hardware to determine robot action
or another microcontroller.
Circuit diagram. The circuit diagram for the robot is provided in Figure 3.4. The three IR
sensors (left, middle, and right) will be mounted on the leading edge of the robot to detect maze
walls. The output from the sensors is fed to three Arduino Duemilanove ADC channels (ANALOG
IN 0-2). The robot motors will be driven by PWM channels (PWM: DIGITAL 11 and PWM:
DIGITAL 10). The Arduino Duemilanove is interfaced to the motors via a transistor (2N2222)
with enough drive capability to handle the maximum current requirements of the motor. Since the
microcontroller is powered at 5 VDC and the motors are rated at 3 VDC, two 1N4001 diodes are
placed in series with the motor. This reduces the supply voltage to the motor to be approximately 3
3.3. EXAMPLE: BLINKY 602A AUTONOMOUS MAZE NAVIGATING ROBOT SYSTEM DESIGN 59
Sharp GP2D12
IR sensor
ANALOG IN
0 123 4 5
3 21 0 9 8 76 5 4 32 1 0
Duemilanove
Arduino
1 1 1 1 DIGITAL
5VGnd
prototype
wall detected LEDs area
turn signals
Figure 3.3: Robot layout with the Arduino Duemilanove processing board.
60 3. EMBEDDED SYSTEMS DESIGN
VDC. The robot will be powered by a 9 VDC battery which is fed to a 5 VDC voltage regulator.
The details of the interface electronics are provided in a later chapter. To save on battery expense, it
is recommended to use a 9 VDC, 2A rated inexpensive, wall-mount power supply to provide power
to the 5 VDC voltage regulator. A power umbilical of braided wire may be used to provide power
to the robot while navigating about the maze.
Structure chart: The structure chart for the robot project is provided in Figure 3.5.
UML activity diagrams: The UML activity diagram for the robot is provided in Figure 3.6.
Arduino Duemilanove Program: We will develop the entire control algorithm for the Ar-
duino Duemilanove board in the Application sections in the remainder of the book. We get started
on the control algorithm in the next section.
ANALOG IN
0 123 4 5
1N4001 1N4001
1N4001 + + 1N4001
Arduino
5VGnd
3 VDC 3 VDC protection
Duemilanove
M M diode
at 100 mA at 100 mA
-
3 21 0 9 8 76 5 4 32 1 0
1 1 1 1 DIGITAL
-
240 240
D10 2N2222 motor
2N2222 D11
current
right motor/wheel
left motor/wheel interface
interface
determine_robot
_action
robot sensor
action data
digital
motor_control ADC
input/output
desired
motor ch for conv
action conv data
left wall right
PWM_left ADC
PWM_right ReadADC turn detect turn
Initialize
signal LEDS signal
turns signals are flashed and a 1.5 s total delay is provided. This provides the robot 1.5 s to render a
turn. This delay may need to be adjusted during the testing phase.
//*************************************************************************
//analog input pins
#define left_IR_sensor 0 //analog pin - left IR sensor
include files
global variables
function prototypes
initialize ports
initialize ADC
initialize PWM
setup()
- configure pins for output
define global variables
while(1)
loop()
read sensor outputs
(left, middle, right)
determine robot
illuminate LEDs action
- wall detected
illuminate LEDs
issue motor - wall detected
control signals
issue motor
illuminate LEDs control signals
- turn signals
illuminate LEDs
- turn signals
delay - delay
Left Middle Right Wall Wall Wall Left Right Left Right
Sensor Sensor Sensor Left Middle Right Motor Motor Signal Signal Comments
0 0 0 0 0 0 0 1 1 0 0 Forward
1 0 0 1 0 0 1 1 1 0 0 Forward
2 0 1 0 0 1 0 1 0 0 1 Right
3 0 1 1 0 1 1 0 1 1 0 Left
4 1 0 0 1 0 0 1 1 0 0 Forward
5 1 0 1 1 0 1 1 1 0 0 Forward
6 1 1 0 1 1 0 1 0 0 1 Right
7 1 1 1 1 1 1 1 0 0 1 Right
//motor outputs
#define left_motor 11 //digital pin - left_motor
#define right_motor 10 //digital pin - right_motor
void setup()
{
//LED indicators - wall detectors
pinMode(wall_left, OUTPUT); //configure pin 1 for digital output
pinMode(wall_center, OUTPUT); //configure pin 2 for digital output
pinMode(wall_right, OUTPUT); //configure pin 3 for digital output
void loop()
{
//read analog output from IR sensors
left_IR_sensor_value = analogRead(left_IR_sensor);
center_IR_sensor_value = analogRead(center_IR_sensor);
right_IR_sensor_value = analogRead(right_IR_sensor);
Testing the control algorithm: It is recommended that the algorithm be first tested without
the entire robot platform. This may be accomplished by connecting the three IR sensors and LEDS
to the appropriate pins on the Arduino Duemilanove as specified in Figure 3.4. In place of the two
motors and their interface circuits, two LEDs with the required interface circuitry may be used. The
LEDs will illuminate to indicate the motors would be on during different test scenarios. Once this
algorithm is fully tested in this fashion, the Arduino Duemilanove may be mounted to the robot
platform and connected to the motors. Full up testing in the maze may commence. Enjoy!
3.5 SUMMARY
In this chapter, we discussed the design process, related tools, and applied the process to a real world
design. As previously mentioned, this design example will be periodically revisited throughout the
text. It is essential to follow a systematic, disciplined approach to embedded systems design to
successfully develop a prototype that meets established requirements.
3.6 REFERENCES
• M. Anderson, Help Wanted: Embedded Engineers Why the United States is losing its edge
in embedded systems, IEEE-USA Today’s Engineer, Feb 2008.
• Barrett S, Pack D (2006) Microcontrollers Fundamentals for Engineers and Scientists. Morgan
and Claypool Publishers. DOI: 10.2200/S00025ED1V01Y200605DCS001
• Barrett S and Pack D (2008) Atmel AVR Microcontroller Primer Programming and Inter-
facing. Morgan and Claypool Publishers. DOI: 10.2200/S00100ED1V01Y200712DCS015
• Barrett S (2010) Embedded Systems Design with the Atmel AVR Microcontroller. Morgan
and Claypool Publishers. DOI: 10.2200/S00225ED1V01Y200910DCS025
• M. Fowler with K. Scott “UML Distilled - A Brief Guide to the Standradr Object Modeling
Language,” 2nd edition. Boston:Addison-Wesley, 2000.
72 3. EMBEDDED SYSTEMS DESIGN
• N. Dale and S.C. Lilly “Pascal Plus Data Structures,” 4th edition. Englewood Cliffs, NJ: Jones
and Bartlett, 1995.
3. What is the purpose of the structure chart, UML activity diagram, and circuit diagram?
4. Why is a system design only as good as the test plan that supports it?
5. During the testing process, when an error is found and corrected, what should now be accom-
plished?
9. Update the robot action truth table if the robot was equipped with four IR sensors.
73
CHAPTER 4
Serial Communication
Subsystem
Objectives: After reading this chapter, the reader should be able to
• Describe the differences between serial and parallel communication.
• Provide definitions for key serial communications terminology.
• Describe the operation of the Universal Synchronous and Asynchronous Serial Receiver and
Transmitter (USART).
• Program the USART for basic transmission and reception using the built-in features of the
Arduino Development Environment.
• Program the USART for basic transmission and reception using C.
• Describe the operation of the Serial Peripheral Interface (SPI).
• Program the SPI system using the built-in features of the Arduino Development Environment.
• Program the SPI system using C.
• Describe the purpose of the Two Wire Interface (TWI).
• Program the Arduino Duemilanove processing board using ISP programming techniques.
4.1 OVERVIEW
Serial communication techniques provide a vital link between the Arduino Duemilanove processing
board an certain input devices, output devices, and other microcontrollers. In this chapter, we inves-
tigate the serial communication features beginning with a review of serial communication concepts
and terminology. We then investigate in turn the following serial communication systems available
on the Arduino Duemilanove processing board: the Universal Synchronous and Asynchronous Se-
rial Receiver and Transmitter (USART), the Serial Peripheral Interface (SPI) and the Two Wire
Interface (TWI). We provide guidance on how to program the USART and SPI using built-in
Arduino Development Environment features and the C programming language. We conclude the
chapter with examples on how to connect an SD card to the Arduino Duemilanove and also how
to program using In System Programming (ISP) techniques.
74 4. SERIAL COMMUNICATION SUBSYSTEM
Figure 4.1: ASCII Code.The ASCII code is used to encode alphanumeric characters.The “0x” indicates
hexadecimal notation in the C programming language.
the beginning and end of each data byte in a transmission sequence. The Atmel USART also has
synchronous features. Space does not permit a discussion of these USART enhancements.
The ATmega328 USART is quite flexible. It has the capability to be set to a variety of data
transmission or Baud (bits per second) rates. The USART may also be set for data bit widths of
5 to 9 bits with one or two stop bits. Furthermore, the ATmega328 is equipped with a hardware
generated parity bit (even or odd) and parity check hardware at the receiver. A single parity bit allows
for the detection of a single bit error within a byte of data. The USART may also be configured to
operate in a synchronous mode. We now discuss the operation, programming, and application of
the USART. Due to space limitations, we cover only the most basic capability of this flexible and
powerful serial communication system.
Figure 4.2: Atmel AVR ATmega328 USART block diagram. (Figure used with permission of Atmel,
Incorporated.)
78 4. SERIAL COMMUNICATION SUBSYSTEM
4.4.1.1 USART Clock Generator
The USART Clock Generator provides the clock source for the USART system and sets the
Baud rate for the USART. The Baud Rate is derived from the overall microcontroller clock source.
The overall system clock is divided by the USART Baud rate Registers UBRR[H:L] and several
additional dividers to set the Baud rate. For the asynchronous normal mode (U2X bit = 0), the Baud
Rate is determined using the following expression:
UBRRL
UBRR7 UBRR6 UBRR5 UBRR4 UBRR3 UBRR2 UBRR1 UBRR0
7 0
USART Control and Status Register A (UCSRA) The UCSRA register contains the RXC, TXC,
and the UDRE bits. The function of these bits have already been discussed.
USART Control and Status Register B (UCSRB) The UCSRB register contains the Receiver
Enable (RXEN) bit and the Transmitter Enable (TXEN) bit. These bits are the “on/off ” switch
for the receiver and transmitter, respectively. The UCSRB register also contains the UCSZ2 bit.
80 4. SERIAL COMMUNICATION SUBSYSTEM
The UCSZ2 bit in the UCSRB register and the UCSZ[1:0] bits contained in the UCSRC register
together set the data character size.
USART Control and Status Register C (UCSRC) The UCSRC register allows the user to customize
the data features to the application at hand. It should be emphasized that both the transmitter and
receiver be configured with the same data features for proper data transmission.The UCSRC contains
the following bits:
• USART Parity Mode (UPM[1:0])- 00: no parity, 10: even parity, 11: odd parity
• USART Character Size (data width) (UCSZ[2:0]) – 000: 5-bit, 001: 6-bit, 010: 7-bit, 011:
8-bit, 111: 9-bit
Command Description
Serial.end() Disables serial communication. Allows Digital 1(TX) and Digital (0) RX
to be used for digital input and output.
Serial.available() Determines how many bytes have already been received and stored in the
128 byte buffer.
Serial.print() Prints data to the serial port as ASCII text. An optional second parameter
specifies the format for printing (BYTE, BIN, OCT, DEC, HEX).
Serial.println() Prints data to the serial port as ASCII text followed by a carriage return.
Serial.write() Writes binary data to the serial port. A single byte, a series of bytes, or an
array of bytes may be sent.
algorithm to provide a status update. These status updates are handy during sketch development.
These status updates would not be available while the robot is progressing through the maze since
the robot would no longer be connected to the host PC via the USB cable.
//*************************************************************************
//analog input pins
#define left_IR_sensor 0 //analog pin - left IR sensor
//motor outputs
#define left_motor 11 //digital pin - left_motor
#define right_motor 10 //digital pin - right_motor
void setup()
{
Serial.begin(9600); //set USART Baud rate to 9600
//LED indicators - wall detectors
pinMode(wall_left, OUTPUT); //configure pin 1 for digital output
pinMode(wall_center, OUTPUT); //configure pin 2 for digital output
pinMode(wall_right, OUTPUT); //configure pin 3 for digital output
void loop()
{
//read analog output from IR sensors
left_IR_sensor_value = analogRead(left_IR_sensor);
center_IR_sensor_value = analogRead(center_IR_sensor);
right_IR_sensor_value = analogRead(right_IR_sensor);
Set USART
no Has UDRE communication parameters no Has RXC
flag set? (data bits, stop bit, parity) flag set?
yes yes
Load UDR register with Turn on transmitter Retrieve received data
data byte for transmission and/or receiver from UDR register
b) USART initialization
To program the USART, we implement the flow diagrams provided in Figure 4.5. In the
sample code provided, we assume the ATmega328 is operating at 10 MHz, and we desire a Baud
Rate of 9600, asynchronous operation, no parity, one stop bit, and eight data bits.
To achieve 9600 Baud with an operating frequency of 10 MHz requires that we set the UBRR
registers to 64 which is 0x40.
//*************************************************************************
//USART_init: initializes the USART system
//*************************************************************************
void USART_init(void)
{
UCSRA = 0x00; //control register initialization
UCSRB = 0x08; //enable transmitter
UCSRC = 0x86; //async, no parity, 1 stop bit, 8 data bits
//Baud Rate initialization
UBRRH = 0x00;
UBRRL = 0x40;
4.6. SYSTEM OPERATION AND PROGRAMMING IN C 85
}
//*************************************************************************
//USART_transmit: transmits single byte of data
//*************************************************************************
//*************************************************************************
//USART_receive: receives single byte of data
//*************************************************************************
//*************************************************************************
MISO MISO
SPI Data Register (SDR) (PB6) (PB6) SPI Data Register (SDR)
MSB LSB MSB LSB
MOSI MOSI
(PB5) (PB5)
SCK SCK shift
system enable
clock SPI Clock Generator SCK SCK
(PB7) (PB7)
SPI Status Register (SPSR)
SPI Control Register (SPCR) The SPI Control Register (SPCR) contains the “on/off ” switch for
the SPI system. It also provides the flexibility for the SPI to be connected to a wide variety of devices
with different data formats. It is important that both the SPI master and slave devices be configured
for compatible data formats for proper data transmission. The SPCR contains the following bits:
• SPI Enable (SPE) is the “on/off ” switch for the SPI system. A logic one turns the system on
and logic zero turns it off.
• Data Order (DORD) allows the direction of shift from master to slave to be controlled. When
the DORD bit is set to one, the least significant bit (LSB) of the SPI Data Register (SPDR)
is transmitted first. When the DORD bit is set to zero the Most Significant Bit (MSB) of the
SPDR is transmitted first.
• The Master/Slave Select (MSTR) bit determines if the SPI system will serve as a master (logic
one) or slave (logic zero).
• The Clock Polarity (CPOL) bit allows determines the idle condition of the SCK pin. When
CPOL is one, SCK will idle logic high; whereas, when CPOL is zero, SCK will idle logic
zero.
• The Clock Phase (CPHA) determines if the data bit will be sampled on the leading (0) or
trailing (1) edge of the SCK.
88 4. SERIAL COMMUNICATION SUBSYSTEM
• The SPI SCK is derived from the microcontroller’s system clock source. The system clock
is divided down to form the SPI SCK. The SPI Clock Rate Select bits SPR[1:0] and the
Double SPI Speed Bit (SPI2X) are used to set the division factor. The following divisions may
be selected using SPI2X, SPR1, SPR0:
SPI Status Register (SPSR) The SPSR contains the SPI Interrupt Flag (SPIF). The flag sets when
eight data bits have been transferred from the master to the slave. The SPIF bit is cleared by first
reading the SPSR after the SPIF flag has been set and then reading the SPI Data Register (SPDR).
The SPSR also contains the SPI2X bit used to set the SCK frequency.
SPI Data Register (SPDR) As previously mentioned, writing a data byte to the SPDR initiates
SPI transmission.
• dataPin: the Arduino Duemilanove DIGITAL pin to be used for serial output.
• clockPin: the Arduino Duemilanove DIGITAL pin to be used for the clock.
• bitOrder: indicates whether the data byte will be sent most significant bit first (MSBFIRST)
or least significant bit first (LSBFIRST).
To use the shiftOut command, the appropriate pins are declared as output using the pinMode
command in the setup() function. The shiftOut command is then called at the appropriate place
within the loop() function using the following syntax:
4.8. SPI PROGRAMMING IN C 89
shiftOut(dataPin, clockPin, LSBFIRST, value);
As a result of the this command, the value specified will be serially shifted out of the data pin
specified, least significant bit first, at the clock rate provided at the clock pin.
//*************************************************************************
//spi_init: initializes spi system
//*************************************************************************
//*************************************************************************
//spi_write: Used by SPI master to transmit a data byte
//*************************************************************************
//*************************************************************************
//spi_read: Used by SPI slave to receive data byte
//*************************************************************************
return SPDR;
}
//*************************************************************************
1 20 5 VDC
SOUT TXD
SIN RXD
GND GND
DNLD SDIN 10K
VCC
RST
10 11
SD Card
3 21 0 9 8 76 5 4 32 1 0
1 1 1 1 DIGITAL
RX
TX
Arduino
Duemilanove
ANALOG IN
5VGnd 0 123 4 5
Figure 4.8: Arduino Duemilanove and SD/MMC card interface circuit [Comfile Technology].
stored and the file option. In this example we have used the “w” option to indicate a write to the file.
The phrase for storage is then provided followed by a carriage return (\r) and a line feed (\n).
Before data can be written to the file, some preparatory steps are required:
• Set the Baud rate for communication.
• Set the SD/MMC for MCU (microcontroller) mode.This mode provides simplified responses
back to the Arduino Duemilanove.
• Initialize the SD/MMC card.
• Create a file.
Commands are provided for each of these actions in Figure 4.9. We will provide a complete
sketch to communicate with the SD/MMC in the Applications section of the next chapter.
Once data has been written to an SD/MMC card, it may be removed from the card socket
in the breakout board and read via a PC using a universal card reader. Universal card readers are
92 4. SERIAL COMMUNICATION SUBSYSTEM
Command format:
Command [Filename] [Option] [Data] [CR] [LF]
3. Connect the STK500 as shown in Figure 4.10. Note: For ISP programming, the 6-wire ribbon
cable is connected from the ISP6PIN header pin on the STK500 to the 6-pin header pin on
the Arduino Duemilanove, not the position of the red guide wire in the diagram.
ATMEL to power
red
AVR supply
wire
VTARGET
RESET
PORTB RS232
cable
XTAL1 to host PC
ribbon
cables
OSCSEL
PORTC RS232
CTRL
red
wire BSEL2
PORTD
SPROG3 PJUMP
RS232
LEDS
SPARE
Note: red wire ISP6PIN
PORTE ISP10PIN
ribbon cable
3 21 0 9 8 76 5 4 32 1 0 connecting
1 11 1 STK500 ISP6PIN
to Arduino Duemilanove
6-pin header
Figure 4.10: Programming the ATmega328 onboard the Arduino Duemilanove with the STK500.
4.12. SUMMARY 95
5. Start up AVR Studio on your PC.
6. Pop up window “Welcome to AVR Studio” should appear. Close this window by clicking on
the “Cancel button.”
7. Click on the “AVR icon.” It looks like the silhouette of an integrated circuit. It is on the second
line of the toolbar about half way across the screen.
8. This should bring up a STK500 pop up window with eight tabs (Main, Program, Fuses, Lock-
bits, Advanced, HW Settings, HW Info). At the bottom of the Main tab window, verify that
the STK500 was autodetected. Troubleshoot as necessary to ensure STK500 was autodetected
by AVR Studio.
• Main:
– Device and Signature Bytes: ATmega328P
– Programming Mode and Target Setting: ISP Mode
– Depress “Read Signature” to insure the STK500 is communicating with the Arduino
Duemilanove
• Program:
– Flash: Input HEX file, Browse and find machine code file: <yourfilename.hex>
– EEPROM: Input HEX file, Browse and find machine code file:
<yourfilename.EEP>
11. Power down the STK500. Disconnect the STK500 from the Arduino Duemilanove processing
board.
4.12 SUMMARY
In this chapter, we have discussed the differences between parallel and serial communications and
key serial communication related terminology. We then in turn discussed the operation of USART,
SPI and TWI serial communication systems. We also provided basic code examples to communicate
with the USART and SPI systems.
96 4. SERIAL COMMUNICATION SUBSYSTEM
4.13 REFERENCES
• Atmel 8-bit AVR Microcontroller with 4/8/16/32K Bytes In-System Programmable Flash, AT-
mega48PA/88PA/168PA/328P data sheet: 8161D-AVR-10/09, Atmel Corporation, 2325 Or-
chard Parkway, San Jose, CA 95131.
• Barrett S, Pack D (2006) Microcontrollers Fundamentals for Engineers and Scientists. Morgan
and Claypool Publishers. DOI: 10.2200/S00025ED1V01Y200605DCS001
• Barrett S and Pack D (2008) Atmel AVR Microcontroller Primer Programming and Inter-
facing. Morgan and Claypool Publishers. DOI: 10.2200/S00100ED1V01Y200712DCS015
• Barrett S (2010) Embedded Systems Design with the Atmel AVR Microcontroller. Morgan
and Claypool Publishers. DOI: 10.2200/S00225ED1V01Y200910DCS025
2. Summarize the differences between the USART, SPI, and TWI methods of serial communi-
cation.
3. Draw a block diagram of the USART system, label all key registers, and all keys USART flags.
4. Draw a block diagram of the SPI system, label all key registers, and all keys USART flags.
7. Draw the schematic of a system consisting of two ATmega328s that will exchange data via
the SPI system.
8. Write the code to implement the system described in the question above.
97
Author’s Biography
STEVEN F. BARRETT
Steven F. Barrett, Ph.D., P.E., received the BS Electronic Engineering Technology from the
University of Nebraska at Omaha in 1979, the M.E.E.E. from the University of Idaho at Moscow
in 1986, and the Ph.D. from The University of Texas at Austin in 1993. He was formally an active
duty faculty member at the United States Air Force Academy, Colorado and is now the Associate
Dean of Academic Programs at the University of Wyoming. He is a member of IEEE (senior)
and Tau Beta Pi (chief faculty advisor). His research interests include digital and analog image
processing, computer-assisted laser surgery, and embedded controller systems. He is a registered
Professional Engineer in Wyoming and Colorado. He co-wrote with Dr. Daniel Pack six textbooks
on microcontrollers and embedded systems. In 2004, Barrett was named “Wyoming Professor of the
Year” by the Carnegie Foundation for the Advancement of Teaching and in 2008 was the recipient of
the National Society of Professional Engineers (NSPE) Professional Engineers in Higher Education,
Engineering Education Excellence Award.
99
Index