Professional Documents
Culture Documents
Warwick A. Smith
C PROGRAMMING
WITH ARDUINO
PROGRAMMING
WITH ARDUINO
Warwick A. Smith lives in Technology is constantly changing. New microcontrollers
South Africa and works become available every year. The one thing that has stayed
as an Electronics Engineer the same is the C programming language used to program
and Embedded System these microcontrollers. If you would like to learn this standard
Programmer. He is a language to program microcontrollers, then this book is for you!
bestselling author of the Arduino is the hardware platform used to teach the C
books C Programming for programming language as Arduino boards are available
Embedded Microcontrol- worldwide and contain the popular AVR microcontrollers from
lers, ARM Microcontroller Atmel.
Interfacing and Open Atmel Studio is used as the development environment for
Source Electronics on writing C programs for AVR microcontrollers. It is a full-featured
Linux. integrated development environment (IDE) that uses the GCC C
software tools for AVR microcontrollers and is free to download.
Elektor International Media BV • Use the AVR Dragon programmer / debugger in conjunction
DESIGN
LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● S
SHARE
● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE
GN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ●
LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ●
● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE ● LEARN ● DESIGN ● SHARE
C Programming with Arduino
Warwick Smith
an Elektor Publication
LEARN DESIGN SHARE
● This is an Elektor Publication. Elektor is the media brand of
Elektor International Media B.V.
78 York Street
London W1H 1DP, UK
Phone: (+44) (0)20 7692 8344
© Elektor International Media BV 2016
First published in the United Kingdom 2016
159020-1/EN
● All rights reserved. No part of this book may be reproduced in any material form, including photocopying,
or storing in any medium by electronic means and whether or not transiently or incidentally to some other
use of this publication, without the written permission of the copyright holder except in accordance with
the provisions of the Copyright, Designs and Patents Act 1988 or under the terms of a licence issued by the
Copyright Licensing Agency Ltd, 90 Tottenham Court Road, London, England W1P 9HE. Applications for the
copyright holder’s written permission to reproduce any part of this publication should be addressed to the
publishers. The publishers have used their best efforts in ensuring the correctness of the information contained
in this book. They do not assume, and hereby disclaim, any liability to any party for any loss or damage caused
by errors or omissions in this book, whether such errors or omissions result from negligence, accident or any
other cause.
● ISBN 978-1-907920-46-2
EISBN 978-3-89576-352-6
EPUB 978-3-89576-353-3
Elektor is part of EIM, the world’s leading source of essential technical information and electronics products for pro engineers,
electronics designers, and the companies seeking to engage them. Each day, our international team develops and delivers
high-quality content - via a variety of media channels (e.g., magazines, video, digital media, and social media) in several
languages - relating to electronics design and DIY electronics. www.elektor.com
LEARN DESIGN SHARE
Table of Contents
Table of Contents
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Learning C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Target Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
AVR Microcontrollers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Embedded Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Hardware Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Arduino Board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Programmer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
●5
C Programming with Arduino
1.8 Analysing the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.8.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
1.10 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
1.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Chapter 2 C Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
2.1.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
2.1.2 Getting Input from the User Using the scanf() Function . . . . . . . . . . . . . . . 44
2.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
2.8 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
●6
Table of Contents
2.8.2 Solution to 2.7.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
2.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
3.2 Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
3.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
3.4 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
3.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
4.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
4.7.1 Subtract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
●7
C Programming with Arduino
4.8 Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
4.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Chapter 5 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
●8
Table of Contents
6.3.1 A Quick Look at Decimal Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
●9
C Programming with Arduino
8.4.2 Post-increment and Post-decrement . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
● 10
Table of Contents
10.9.1 Passing an Address to a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
● 11
C Programming with Arduino
11.8.2 Solution to 11.7.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
● 12
Table of Contents
14.1 Configuring Arduino Boards for Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . 267
14.5.8 Viewing Variable Value Changes & Setting Conditional Breakpoints . . . . . 276
● 13
C Programming with Arduino
16.7 The goto Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
● 14
Table of Contents
Appendix D References and Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
● 15
C Programming with Arduino
● 16
Introduction
Introduction
This book will teach you the C programming language using AVR microcontroller based
Arduino boards, such as the Uno and MEGA, as a teaching platform. Atmel Studio for
Windows operating systems is the IDE and software tool used in this book for writing,
compiling and loading C programs to the Arduino boards.
Atmel Studio and the standard C language are used as an alternative to the Arduino
IDE which was designed to help those with less technical knowledge of electronics and
microcontrollers to get started with microcontroller projects. Standard C is taught by
Universities as part of electronic engineering courses and is used throughout industry for
programming microcontrollers. C programming can be used on any microcontroller for
which C programming tools are available and is not restricted to Arduino. Arduino is used
with this book for teaching C as it is very convenient to use and readily available.
Learning C
Learning a new programming language and learning how to program embedded systems
covers a lot of ground as there are many things to learn: the C programming language
itself, some knowledge of microcontroller architecture, some electronics, microcontroller
peripherals, number systems and logic. There is also the software programming toolchain
and IDE to learn, which in the case of this book is the Atmel Studio IDE that uses the
GNU toolchain for AVR microcontrollers. It may seem to be a daunting task to learn about
all these aspects of an embedded system and programming language, but taking it one
step at a time as this book does makes it easy, enjoyable and a lot of fun.
Technical Terms
Target Audience
This book has been written for the hobbyist, student and engineer wanting to learn the C
programming language in an embedded environment using microcontrollers.
AVR Microcontrollers
AVR microcontrollers, the microcontrollers found on Arduino boards such as the Uno and
MEGA are used in this book. The C language applies equally to other microcontrollers, but
when learning to program, a particular microcontroller architecture must be chosen as
hardware differences between microcontrollers will change how they are programmed.
● 17
C Programming with Arduino
in 8-bit and 32-bit series. These microcontrollers contain a “AVR core” that is interfaced
to memory and peripheral devices and packaged in a single chip. Only 8-bit AVR
microcontrollers are presented in this text.
Technical Terms
RISC – RISC stands for Reduced Instruction Set Computer and is a processor that is
designed with a simplified instruction set in order to produce higher performance. The
AVR architecture has been designed this way.
Embedded Systems
Technical Terms
● 18
Introduction
Abbreviations
Arduino has been chosen as the embedded system for this book, and specifically Arduino
boards that have 8-bit AVR microcontrollers on-board and can be fitted with the standard
add-on boards called shields.
Arduino has been chosen because it is so widely available, is an open source project
and has many second-source compatible boards available. Before Arduino became
popular, a specific proprietary board would have to be recommended for any embedded
programming book. With Arduino we now have standard off-the-shelf hardware that is
open source, allowing anyone to view and modify the circuit diagram and board.
Here are some of the reasons that Arduino was chosen:
• Powered by USB – no external power supply needed
• Easy to connect hardware using an electronic breadboard and jumper wires
• USB port on-board that is configured as a virtual COM port on the PC for serial
communications
• Widely available with alternative sources and clone boards / derivative boards
• Has ICSP header for programming and debugging
In the pages that follow, you will learn to write programs that run on an Arduino board
or embedded system and switch LEDs on and off, read switches to see if they are being
pressed or released, send messages out of the serial port to be displayed on a PC and
more.
● 19
C Programming with Arduino
If I think of all the technology changes that have taken place in the world of
microelectronics since the start of my career as an embedded programmer, the one
thing that has stayed the same is the C language. Processor architectures and systems
have come and gone, but the common thing between all of them is that they were
programmed in C.
The reason for the popularity and use of C is that C is a standard language and ideally
suited to embedded programming where access to the hardware of a system is required.
C programming tools produce small and fast programs – a requirement when you
have limited amounts of memory available on an embedded system. Whenever a new
processor architecture comes on the market, you can be pretty sure that there will be C
programming tools available for it.
C programming is necessary to move beyond Arduino in order to program other
embedded systems that are not supported by the Arduino IDE, as well as gain more
control over Arduino boards.
You may have heard that C is cryptic and difficult to learn, but this is nonsense. C is a
simple language with very few keywords and is easy to learn. As with any new language,
you need to become familiar with the syntax of the language. This book will explain
everything to you, starting with simple and easy programs. When I leaned to program in
C, I thoroughly enjoyed it and I hope that you will too.
Prerequisites
In order to use this book you will need to be able to operate a computer running Windows
and know how to download and install software on a Windows system.
Any knowledge of electronics will help, for example you should know what an LED is, a
switch, I.C. and a resistor. I will refer to basic electronic components such as these in
the text. If you don’t know what these items are, there are plenty of books available that
teach basic electronics. A good online resource for basic electronics, breadboard circuits
and an introduction to Arduino is: startingelectronics.org/beginners/start-electronics-now/
Any knowledge of programming in any language will help, but is not required.
Basic mathematics is also assumed. i.e. addition, subtraction, multiplication, division,
counting and a little algebra. If you are not good at mathematics, that is not a problem as
the mathematics is very basic and the programs that you will write will actually help you
to understand mathematics better.
● 20
Introduction
You will need to have an Internet connection in order to download software programs and
example programs used with this book (all software used is free).
Hardware Requirements
A standard USB cable will be needed for powering the Arduino board and communicating
between the Arduino and PC. An external power supply can be used to power the Arduino
board, but a USB cable will still be needed for serial communications with the PC.
Electronic components such as LEDs, resistors and switches will be needed and are listed
in each section of the book when they are required.
When using the Atmel Studio IDE, a programming device is needed to load programs to
the microcontroller on the Arduino board. The programmer is connected to the PC using a
USB cable and to the 6-pin header on the Arduino board labelled ICSP. More details of the
Arduino board and programmer required can be found below.
Arduino Board
● 21
C Programming with Arduino
Programmer
Technical Terms
● 22
Introduction
This book uses free or open source software only. You will start learning to program right
from chapter 1 after installing and setting up programming tools.
The first 7 chapters of the book teach the basics of the C language, concentrating on the
language by sending output from C programs running on an Arduino to the PC for display
in a terminal window, and receiving data from the terminal window typed in by a user.
Chapter 8 and beyond builds on the C basics already learned in the first chapters and
starts to look at programs that use the microcontroller’s peripherals for more practical
embedded applications.
Take your time to learn and understand how the programs work before moving to the
next chapter. Experiment with the code by changing it to see what happens and try to
write your own programs, or modified versions of the example programs to aid in learning
as you progress through the book.
If you can’t type, learn to type while learning C. This is what I did when learning to
program and have never regretted it. I always entered the example programs by typing
them in rather than just running the downloaded example programs from disk.
Learning C and embedded systems is great fun and a big adventure, so it is my wish that
you will thoroughly enjoy using this book and learning new things.
An accompanying zipped file is available for download from Elektor that contains all of
the C source code for the example programs in this book. Download the accompanying
files from the Elektor website at www.elektor.com by browsing for the book from the books
menu or using the search box to find the book’s page.
An accompanying website can be found at wspublishing.net/avr-c that contains extra
articles and information related to this book and will be updated with any errata found.
● 23
C Programming with Arduino
● 24
Chapter 1 • Your First C Program
Downloading and installing Atmel Studio is straightforward and should not pose any
problems. Brief download and installation instructions are presented below. More detailed
instructions with screen captures can be found on the supporting website at:
wspublishing.net/avr-c.
Atmel Studio can be downloaded by visiting the Atmel Studio web page and scrolling
down the page to find a link to the Atmel Studio installer.
Atmel Studio web page: www.atmel.com/tools/atmelstudio.aspx
Two downloads of Atmel Studio are available – a web installer version and an offline
installer version. I would suggest downloading the offline installer version which will allow
Atmel Studio to be installed to any PC whether it is connected to the Internet or not.
● 25
C Programming with Arduino
account. If you do the download as a guest, you can always create an Atmel account
later.
When the download has finished, a file with a name such as as-installer-7.0.582-full.exe
will be found in the download folder. The exact file name may be different, depending on
whether the downloaded file is a newer version or not.
To install Atmel Studio, simply double-click the downloaded file to run it, which will start
the installation. You will need to agree with the license to be able to continue with the
installation. Do a standard full installation and leave the installation folder names at their
defaults.
A terminal emulator program called Tera Term is used for program input / output between
a PC and Arduino board using a USB cable. Tera Term can be downloaded from:
en.osdn.jp/projects/ttssh2/releases/
Download the zipped Tera Term file, which was at version 4.88 at the time of writing, and
named teraterm-4.88.zip containing a folder called teraterm-4.88.
It is not necessary to install Tera Term, simply copy the teraterm-4.88 folder from the
zipped file to any convenient location on the PC, e.g. to the desktop. Double-click the file
called ttermpro.exe in the teraterm-4.88 folder to run Tera Term.
It is best to enable Windows to show file extensions in the file manager to more easily
identify file types. Enabling file extensions to be visible will show the .exe extension of
ttermpro.exe as well as the .c extension of C program files.
To display file name extensions in file manager, first open file manager and then click
Organize → Folder and search options to pop up the Folder Options dialog box. In
the dialog box, click the View tab. In the Advanced settings box, uncheck the Hide
extensions for known file types box. Click the OK button in the dialog box to save the
changes.
Included with the accompanying download from Elektor are two template files used to
start new projects in Atmel Studio called template_mega_dragon.zip and template_
uno_dragon.zip found in the Templates folder of the download file. To install these
template files, open your Documents folder and then Atmel Studio → 7.0 → Templates
→ ProjectTemplates and copy the files into the ProjectTemplates sub-folder.
If you are using a newer version of Atmel Studio, substitute the new version number in
place of 7.0 in the above path.
The full path to the ProjectTemplates folder is:
C:\Users\<your user name>\Documents\Atmel Studio\7.0\Templates\
ProjectTemplates
● 26
Chapter 1 • Your First C Program
Use a standard USB cable to connect the AVRISP programmer or AVR Dragon
programmer / debugger to the PC that has Atmel Studio loaded on it. Drivers for the
programming device will automatically be installed.
Connect the 6-way ribbon cable from the programming device (AVRISP or Dragon) to
the 6-pin header labelled ICSP on the Arduino board. Don't connect the programmer to
the 6-pin header that is near the USB connector on the Arduino. On the AVR Dragon, the
6-way ribbon cable is connected to the 6-pin header labelled ISP. Pin 1 of the ISP header
on the Dragon is marked with a 1. Pin 1 of the ICSP header on the Arduino board is
marked with a small dot.
Connect the Arduino board to a second USB port on the PC using a second standard USB
cable. On a Windows 7 system the Arduino drivers will need to be installed if the Arduino
has never been programmed using the Arduino IDE software on the PC. The drivers will
enable the Arduino to be seen as a virtual COM port on the PC. A Windows 10 system
should automatically configure the Arduino as a virtual COM port. For more detailed
hardware connection instructions, see the supporting website at: wspublishing.net/avr-c
C programs are written using a text editor and saved to a file with a .c file extension e.g.
myprog.c. When the C compiler is run it reads the C text file, known as the C source file,
and creates an executable file that can be loaded to and run on the embedded system.
The text editor in Atmel Studio has "syntax highlighting" which will highlight C language
keywords making the program a lot easier to read.
With the software tools installed and hardware connected, you are now ready to write
your first C program. Start by creating a new sub-folder in which to store the C programs
that you will write when following the examples in this book. The sub-folder can be
created in Documents → Atmel Studio or Documents → Atmel Studio → 7.0 assuming
that the version of Atmel Studio that you are using is version 7.0. A sub-folder called c_
book in Documents → Atmel Studio → 7.0 will be used in the text when describing how
to create new Atmel Studio projects.
You may want to install the code examples for the book that are included with the
accompanying files downloaded from Elektor, so that you can check your code against the
examples. Copy the Arduino_C folder from the accompanying zipped file to Documents
→ Atmel Studio.
When writing a new C program using Atmel Studio, a new project must be created that
will contain the C code as well as other files that store the project settings, such as the
part number of the target microcontroller, which programming device is being used and
various settings for the C toolchain.
Start Atmel Studio, which can easily be found by clicking the Windows start button and
typing "Atmel", or by double-clicking the Atmel Studio icon on the desktop.
A new project can be created by clicking the New Project... item on the Start Page in
Atmel Studio. If the Start Page is not visible, use the top menu to open it by clicking
● 27
C Programming with Arduino
View → Start Page. Alternatively click the New Project icon on the top left toolbar or use
File → New → Project... from the top menu.
In the New Project dialog box that appears (Figure 1-2), select template_mega_dragon
if you are using the Arduino MEGA or template_uno_dragon if you are using the Arduino
Uno. If the template files do not appear in the dialog box, then refer to section 1.3 on
page 26 which explains how to install the templates.
● 28
Chapter 1 • Your First C Program
● 29