C Programming for Arduino - Julien Bayle - E-Book

C Programming for Arduino E-Book

Julien Bayle

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Physical computing allows us to build interactive physical systems by using software & hardware in order to sense and respond to the real world. C Programming for Arduino will show you how to harness powerful capabilities like sensing, feedbacks, programming and even wiring and developing your own autonomous systems.

C Programming for Arduino contains everything you need to directly start wiring and coding your own electronic project. You'll learn C and how to code several types of firmware for your Arduino, and then move on to design small typical systems to understand how handling buttons, leds, LCD, network modules and much more.

After running through C/C++ for the Arduino, you'll learn how to control your software by using real buttons and distance sensors and even discover how you can use your Arduino with the Processing framework so that they work in unison. Advanced coverage includes using Wi-Fi networks and batteries to make your Arduino-based hardware more mobile and flexible without wires. If you want to learn how to build your own electronic devices with powerful open-source technology, then this book is for you.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 585

Veröffentlichungsjahr: 2013

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

C Programming for Arduino
Credits
About the Author
Acknowledgement
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Let's Plug Things
What is a microcontroller?
Presenting the big Arduino family
About hardware prototyping
Understanding Arduino software architecture
Installing Arduino development environment (IDE)
Installing the IDE
How to launch the environment?
What does the IDE look like?
Installing Arduino drivers
Installing drivers for Arduino Uno R3
Installing drivers for Arduino Duemilanove, Nano, or Diecimilla
What is electricity?
Voltage
Current and power
And what are resistors, capacitors, and so on?
Wiring things and Fritzing
What is Fritzing?
Power supply fundamentals
Hello LED!
What do we want to do exactly?
How can I do that using C code?
Start with a new blank page
Setting up the environment according the board we are using
Let's write the code
Let's upload the code, at last!
Summary
2. First Contact with C
An introduction to programming
Different programming paradigms
Programming style
C and C++?
C is used everywhere
Arduino is programmed with C and C++
The Arduino native library and other libraries
Discovering the Arduino native library
Other libraries included and not directly provided
Some very useful included libraries
Some external libraries
Checking all basic development steps
Using the serial monitor
Baud rate
Serial communication with Arduino
Serial monitoring
Making the Arduino talk to us
Adding serial communication to Blink250ms
Serial functions in more detail
Serial.begin()
Serial.print() and Serial.println()
Digging a bit…
Talking to the board from the computer
Summary
3. C Basics – Making You Stronger
Approaching variables and types of data
What is a variable?
What is a type?
The roll over/wrap concept
Declaring and defining variables
Declaring variables
Defining variables
String
String definition is a construction
Using indexes and search inside String
charAt()
indexOf() and lastIndexOf()
startsWith() and endsWith()
Concatenation, extraction, and replacement
Concatenation
Concat()
Using the + operator on strings
Extract and replace
substring() is the extractor
Splitting a string using a separator
Replacement
Other string functions
toCharArray()
toLowerCase() and toUpperCase()
trim()
length()
Testing variables on the board
Some explanations
The scope concept
static, volatile, and const qualifiers
static
volatile
const
Operators, operator structures, and precedence
Arithmetic operators and types
Character types
Numerical types
Condensed notations and precedence
Increment and decrement operators
Types manipulations
Choosing the right type
Implicit and explicit types conversions
Implicit type conversion
Explicit type conversion
Comparing values and Boolean operators
Comparison expressions
Combining comparisons with Boolean operators
Combining negation and comparisons
Adding conditions in the code
if and else conditional structure
Chaining an if…else structure to another if…else structure
if…else structure with combined comparisons expressions
Finding all cases for a conditional structure
switch…case…break conditional structure
Ternary operator
Making smart loops for repetitive tasks
for loop structure
Playing with increment
More complex increments
Decrements are negative increments
Using imbricated for loops or two indexes
while loop structure
do…while loop structure
Breaking the loops
Infinite loops are not your friends
Summary
4. Improve Programming with Functions, Math, and Timing
Introducing functions
Structure of a function
Creating function prototypes using the Arduino IDE
Header and name of functions
Body and statements of functions
Benefits of using functions
Easier coding and debugging
Better modularity helps reusability
Better readability
C standard mathematical functions and Arduino
Trigonometric C functions in the Arduino core
Some prerequisites
Difference between radians and degrees
Cosine, sine, and tangent
Arccosine, arcsine, and arctangent
Trigonometry functions
Exponential functions and some others
Approaching calculation optimization
The power of the bit shift operation
What are bit operations?
Binary numeral system
Easily converting a binary number to a decimal number
AND, OR, XOR, and NOT operators
AND
OR
XOR
NOT
Bit shift operations
It is all about performance
The switch case labels optimization techniques
Optimizing the range of cases
Optimizing cases according to their frequency
Smaller the scope, the better the board
The Tao of returns
Direct returns concept
Use void if you don't need return
Secrets of lookup tables
Table initialization
Replacing pure calculation with array index operations
Taylor series expansion trick
The Arduino core even provides pointers
Time measure
Does the Arduino board own a watch?
The millis() function
The micros() function
Delay concept and the program flow
What does the program do during the delay?
The polling concept – a special interrupt case
The interrupt handler concept
What is a thread?
A real-life polling library example
Installing an external library
Let's test the code
Summary
5. Sensing with Digital Inputs
Sensing the world
Sensors provide new capacities
Some types of sensors
Quantity is converted to data
Data has to be perceived
What does digital mean?
Digital and analog concepts
Inputs and outputs of Arduino
Introducing a new friend – Processing
Is Processing a language?
Let's install and launch it
A very familiar IDE
Alternative IDEs and versioning
Checking an example
Processing and Arduino
Pushing the button
What is a button, a switch?
Different types of switches
A basic circuit
Wires
The circuit in the real world
The pull-up and pull-down concept
The pseudocode
The code
Making Arduino and Processing talk
The communication protocol
Protocol requirements
Protocol design
The Processing code
Sketching a pseudocode
Let's write that code
Variable definitions
setup()
draw()
The serialEvent() callback
The new Arduino firmware talk-ready
Playing with multiple buttons
The circuit
The Arduino code
The Processing code
Understanding the debounce concept
What? Who is bouncing?
How to debounce
Summary
6. Sensing the World – Feeling with Analog Inputs
Sensing analog inputs and continuous values
How many values can we distinguish?
Reading analog inputs
The real purpose of the potentiometer
Changing the blinking delay of an LED with a potentiometer
How to turn the Arduino into a low voltage voltmeter?
Calculating the precision
Introducing Max 6, the graphical programming framework
A brief history of Max/MSP
Global concepts
What is a graphical programming framework?
Max, for the playground
MSP, for sound
Jitter, for visuals
Gen, for a new approach to code generation
Summarizing everything in one table
Installing Max 6
The very first patch
Playing sounds with the patch
Controlling software using hardware
Improving the sequencer and connecting the Arduino
Let's connect the Arduino to Max 6
The serial object in Max 6
Tracing and Debugging easily in Max 6
Understanding Arduino messages in Max 6
What is really sent on the wire?
Extracting only the payload?
ASCII conversions and symbols
Playing with sensors
Measuring distances
Reading a datasheet?
Let's wire things
Coding the firmware
Reading the distance in Max 6
Measuring flexion
Resistance calculations
Sensing almost everything
Multiplexing with a CD4051 multiplexer/demultiplexer
Multiplexing concepts
Multiple multiplexing/demultiplexing techniques
Space-division multiplexing
Frequency-division multiplexing
Time-division multiplexing
The CD4051B analog multiplexer
What is an integrated circuit?
Wiring the CD4051B IC?
Identifying pin number 1
Supplying the IC
Analog I/O series and the common O/I
Selecting the digital pin
Summary
7. Talking over Serial
Serial communication
Serial and parallel communication
Types and characteristics of serial communications
Synchronous or asynchronous
Duplex mode
Peering and bus
Master and slave buses
Data encoding
Multiple serial interfaces
The powerful Morse code telegraphy ancestor
The famous RS-232
From 25 wires to 3
The elegant I2C
The synchronous SPI
The omnipresent USB
USB system design
USB connectors and cables
FTDI IC converting RS-232 to USB
Summary
8. Designing Visual Output Feedback
Using LEDs
Different types of LEDs
Monochromatic LEDS
Polychromatic LEDs
Remembering the Hello LED example
Multiple monochromatic LEDs
Two buttons and two LEDs
Control and feedback coupling in interaction design
The coupling firmware
More LEDs?
Multiplexing LEDs
Connecting 75HC595 to Arduino and LEDs
Firmware for shift register handling
Global shift register programming pattern
Playing with chance and random seeds
Daisy chaining multiple 74HC595 shift registers
Linking multiple shift registers
Firmware handling two shift registers and 16 LEDs
Current short considerations
Using RGB LEDs
Some control concepts
Different types of RGB LEDs
Lighting an RGB LED
Red, Green, and Blue light components and colors
Multiple imbricated for() loops
Building LED arrays
A new friend named transistor
The Darlington transistors array, ULN2003
The LED matrix
Cycling and POV
The circuit
The 3 x 3 LED matrix code
Simulating analog outputs with PWM
The pulse-width modulation concept
Dimming an LED
A higher resolution PWM driver component
Quick introduction to LCD
HD44780-compatible LCD display circuit
Displaying some random messages
Summary
9. Making Things Move and Creating Sounds
Making things vibrate
The piezoelectric sensor
Wiring a vibration motor
Firmware generating vibrations
Higher current driving and transistors
Controlling a servo
When do we need servos?
How to control servos with Arduino
Wiring one servo
Firmware controlling one servo using the Servo library
Multiple servos with external power supply
Three servos and an external power supply
Driving three servos with firmware
Controlling stepper motors
Wiring a unipolar stepper to Arduino
Firmware controlling the stepper motor
Air movement and sounds
What is sound actually?
How to describe sound
Microphones and speakers
Digital and analog domains
How to digitalize sound
How to play digital bits as sounds
How Arduino helps produce sounds
Playing basic sound bits
Wiring the cheapest sound circuit
Playing random tones
Improving the sound engine with Mozzi
Setting up a circuit and Mozzi library
An example sine wave
Oscillators
Wavetables
Frequency modulation of a sine wave
Adding a pot
Upgrading the firmware for input handling
Controlling the sound using envelopes and MIDI
An overview of MIDI
MIDI and OSC libraries for Arduino
Generating envelopes
Implementing envelopes and MIDI
Wiring a MIDI connector to Arduino
Playing audio files with the PCM library
The PCM library
WAV2C – converting your own sample
Wiring the circuit
Other reader libraries
Summary
10. Some Advanced Techniques
Data storage with EEPROMs
Three native pools of memory on the Arduino boards
Writing and reading with EEPROM core library
External EEPROM wiring
Reading and writing to the EEPROM
Using GPS modules
Wiring the Parallax GPS receiver module
Parsing GPS location data
Arduino, battery, and autonomy
Classic cases of USB power supplying
Supplying external power
Supplying with batteries
Power adapter for Arduino supply
How to calculate current consumption
Drawing on gLCDs
Wiring the device
Demoing the library
Some useful method's families
Global GLCD methods
Drawing methods
Text methods
Using VGA with the Gameduino Shield
Summary
11. Networking
An overview of networks
Overview of the OSI model
Protocols and communications
Data encapsulation and decapsulation
The roles of each layer
Physical layer
Data link layer
Network layer
Transport layer
Application/Host layers
Some aspects of IP addresses and ports
The IP address
The subnet
The communication port
Wiring Arduino to wired Ethernet
Making Processing and Arduino communicate over Ethernet
Basic wiring
Coding network connectivity implementation in Arduino
Coding a Processing Applet communicating on Ethernet
Some words about TCP
Bluetooth communications
Wiring the Bluetooth module
Coding the firmware and the Processing applet
Playing with Wi-Fi
What is Wi-Fi?
Infrastructure mode
Ad hoc mode
Other modes
The Arduino Wi-Fi shield
Basic Wi-Fi connection without encryption
Arduino Wi-Fi connection using WEP or WPA2
Using WEP with Wi-Fi library
Using WPA2 with Wi-Fi library
Arduino has a (light) web server
Tweeting by pushing a switch
An overview of APIs
Twitters API
Using the Twitter library with OAuth support
Grabbing credentials from Twitter
Coding a firmware connecting to Twitter
Summary
12. Playing with Max 6 Framework
Communicating easily with Max 6 – the [serial] object
The [serial] object
Selecting the right serial port
Polling system
Parsing and selecting data coming from Arduino
The readAll firmware
The ReadAll Max 6 patch
Requesting data from Arduino
Parsing the received data
Distributing received data and other tricks
Cordless trick
Encapsulation and subpatching
Abstractions and reusability
Creating a sound-level meter with LEDs
The circuit
The Max 6 patch for calculating sound levels
The firmware for reading bytes
Pitch shift effect controlled by hand
The circuit with the sensor and the firmware
The patch for altering the sound and parsing Arduino messages
Summary
13. Improving your C Programming and Creating Libraries
Programming libraries
The header file
The source file
Creating your own LED-array library
Wiring six LEDs to the board
Creating some nice light patterns
Designing a small LED-pattern library
Writing the LEDpatterns.h header
Writing the LEDpatterns.cpp source
Writing the keyword.txt file
Using the LEDpatterns library
Memory management
Mastering bit shifting
Multiplying/dividing by multiples of 2
Packing multiple data items into bytes
Turning on/off individual bits in a control and port register
Reprogramming the Arduino board
Summary
Conclusion
Index

C Programming for Arduino

C Programming for Arduino

Copyright © 2013 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: May 2013

Production Reference: 1070513

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-84951-758-4

www.packtpub.com

Cover Image by Asher Wishkerman (<[email protected]>)

Credits

Author

Julien Bayle

Reviewers

Darwin Grosse

Pradumn Joshi

Phillip Mayhew

Glenn D. Reuther

Steve Spence

Acquisition Editor

Edward Gordon

Erol Staveley

Lead Technical Editor

Susmita Panda

Technical Editors

Worrell Lewis

Varun Pius Rodrigues

Lubna Shaikh

Sharvari Baet

Copy Editors

Laxmi Subramanian

Sajeev Raghavan

Insiya Morbiwala

Brandt D'mello

Aditya Nair

Alfida Paiva

Project Coordinator

Leena Purkait

Proofreaders

Claire Cresswell-Lane

Martin Diver

Indexer

Tejal R. Soni

Graphics

Ronak Dhruv

Production Coordinator

Pooja Chiplunkar

Cover Work

Pooja Chiplunkar

About the Author

Julien Bayle completed his Master's degree in Biology and Computer Sciences in 2000. After several years working with pure IT system design, he founded Design the Media in early 2010 in order to provide his own courses, training, and tools for art fields. As a digital artist, he has designed some huge new media art installations, such as the permanent exhibition of La Maison des Cinématographies de la Méditerranée (Château de la Buzine) in Marseille, France, in 2011. He has also worked as a new media technology consultant for some private and public entities. As a live AV performer, he plays his cold electronic music right from New York to Marseille where he actually lives. The Arduino framework is one of his first electronic hardware studies since early 2005, and he also designed the famous protodeck controller with various open source frameworks. As an Art and Technology teacher also certified by Ableton in 2010, he teaches a lot of courses related to the digital audio workstation Ableton Live, the real-time graphical programming framework Max 6, and Processing and Arduino.

As a minimalist digital artist, he works at the crossroads between sound, visual, and data. He explores the relationship between sounds and visuals through his immersive AV installations, his live performances, and his released music. His work, often described as "complex, intriguing, and relevant", tries to break classical codes to bring his audience a new vision of our world through his pure digital and real-time-generated stimuli.

He's deeply involved in the open source community and loves to share and provide workshops and masterclasses online and on-site too. His personal website is http://julienbayle.net.

Acknowledgement

I would like to thank my sweet wife Angela and our daughter Alice for having been my unconditional supporters. Special thanks to our son Max, who was born between the writing of Chapter 11 and Chapter 12!

I would also like to thank my two great friends Laurent Boghossian and Denis Laffont because they were there for me all through the course of this huge project with their advices, jokes, and unconditional support.

I would like to extend many thanks to two very nice persons and friends whom I asked to review this book for me: Glenn D. Reuther and Darwin Grosse.

I thank the following great programmers who coded some libraries that have been used in this book: Marcello Romani (the SimpleTimer library), Juan Hernandez (the ShiftOutX library), Thomas Ouellet Fredericks (the Bounce library), Tim Barrass (the Mozzi library), David A. Mellis from MIT (the PCM library), Michael Margolis and Bill Perry (the glcd-arduino library), and Markku Rossi (Arduino Twitter Library with OAuth Support).

I want to thank the creators of the following powerful frameworks used in this book besides the Arduino framework itself: Max 6, Processing, and Fritzing.

Lastly, I'd like to hug Massimo Banzi and Arduino's project team for having initiated this great project and inspired us so much.

About the Reviewers

Darwin Grosse is the Director of Education and Services with Cycling '74, the developer of the Max media programming system. He is also an Adjunct Professor at the University of Denver, and teaches sonic art, programming, and hardware interface in the Emerging Digital Practices department.

Pradumn Joshi is currently pursuing his Bachelor's degree in Electrical Engineering from NIT Surat. He is an avid elocutionist and debate enthusiast, and is also interested in economics, freelance writing, and Western music. His area of technical expertise lies in open source hardware development and embedded systems.

Phillip Mayhew is a Bachelor of Science in Computer Science from North Carolina State University. He is the Founder and Managing Principal of Rextency Technologies LLC based in Statesville, North Carolina. His primary expertise is in software application performance testing and monitoring.

Glenn D. Reuther's own personal journey and fascination began with music technology during the 1970s with private lessons in "Electronic Music Theory and Acoustic Physics". He then attended Five Towns College of Music in NY and has been a home studio operator since 1981, playing multiple instruments and designing a few devices for his studio configuration.

Since then, he has spent several years with Grumman Aerospace as a Ground and Flight Test Instrumentation Technician, before moving through to the IT field. Beginning with an education in Computer Operations and Programming, he went on to work as network and system engineer having both Microsoft and Novell certifications. After over 10 years at the University of Virginia as Sr. Systems Engineer, he spends much of his spare time working with the current state of music technology. His website is http://lico.drupalgardens.com.

He is also the author of "One Complete Revelation", a photo journal of his nine-month trek throughout Europe during the early 90s.

I would like to thank the author for his friendship, and I would also like to thank my wonderful wife Alice and son Glenn for their patience, understanding, and support during the editing process of this book.

Steve Spence has been a veteran of the IT industry for more than 20 years, specializing in network design and security. Currently he designs microcontroller-based process controls and database-driven websites. He lives off grid and teaches solar and wind power generation workshops. He's a former firefighter and rescue squad member, and a current Ham Radio operator.

In the past, he's been a technical reviewer of various books on alternative fuels (From the Fryer to the Fuel Tank, Joshua Tickell) and authored DIY alternative energy guides.

www.PacktPub.com

Support files, eBooks, discount offers and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. 

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print and bookmark contentOn demand and accessible via web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

Preface

Our futuristic world is full of smart and connected devices. Do-it-yourself communities have always been fascinated by the fact that each one could design and build its own smart system, dedicated or not, for specific tasks. From small controllers switching on the lights when someone is detected to a smart sofa sending e-mails when we sit on them, cheap electronics projects have become more and more easy to create and, for contributing to this, we all have to thank the team, who initiated the Arduino project around 2005 in Ivrea, Italy.

Arduino's platform is one of the most used open source hardware in the world. It provides a powerful microcontroller on a small printed circuit board with a very small form factor. Arduino users can download the Arduino Integrated Development Environment (IDE) and code their own program using the C/C++ language and the Arduino Core library that provides a lot of helpful functions and features.

With C Programming for Arduino, users will learn enough of C/C++ to be able to design their own hardware based on Arduino. This is an all-in-one book containing all the required theory illustrated with concrete examples. Readers will also learn about some of the main interaction design and real-time multimedia frameworks such as Processing and the Max 6 graphical programming framework.

C Programming for Arduino will teach you the famous "learning-by-making" way of work that I try to follow in all of my courses from Max 6 to Processing and Ableton Live.

Lastly, C Programming for Arduino will open new fields of knowledge by looking at the input and output concept, communication and networking, sound synthesis, and reactive systems design. Readers will learn the necessary skills to be able to continue their journey by looking at the modern world differently, not only as a user but also as a real maker.

For more details, you can visit my website for the book at http://cprogrammingforarduino.com/.

What this book covers

Chapter 1, Let's Plug Things, is your first contact with Arduino and microcontroller programming. We will learn how to install the Arduino Integrated Development Environment on our computer and how to wire and test the development toolchain to prepare the further study.

Chapter 2, First Contact with C, covers the relation between the software and the hardware. We will introduce the C language, understand how we can compile it, and then learn how to upload our programs on the Arduino Board. We will also learn all the steps required to transform a pure idea into firmware for Arduino.

Chapter 3, C Basics—Making You Stronger, enters directly into the C language. By learning basics, we learn how to read and write C programs, discovering the datatype, basic structures, and programming blocks.

Chapter 4, Improving Programming with Functions, Math, and Timing, provides the first few keys to improve our C code, especially by using functions. We learn how to produce reusable and efficient programming structures.

Chapter 5, Sensing with Digital Inputs, introduces digital inputs to Arduino. We will learn how to use them and understand their inputs and outputs. We will also see how Arduino uses electricity and pulses to communicate with everything.

Chapter 6, Sensing the World—Feeling with Analog Inputs, describes the analog inputs of Arduino through different concrete examples and compares them to digital pins. Max 6 frameworks are introduced in this chapter as one of the ideal companions for Arduino.

Chapter 7, Talking over Serial, introduces the communication concept, especially by teaching about Serial communication. We will learn how to use the Serial communication console as a powerful debugging tool.

Chapter 8, Designing Visual Output Feedback, talks about the outputs of Arduino and how we can use them to design visual feedback systems by using LEDs and their systems. It introduces the powerful PWM concept and talks about LCD displays too.

Chapter 9, Making Things Move and Creating Sounds, shows how we can use the Arduino's outputs for movement-related projects. We talk about motors and movement and also about air vibration and sound design. We describe some basics about digital sound, MIDI, and the OSC protocol, and have fun with a very nice PCM library providing the feature of reading digitally encoded sound files from Arduino itself.

Chapter 10, Some Advanced Techniques, delivers many advanced concepts, from data storage on EEPROM units, and communication between multiple Arduino boards, to the use of GPS modules. We will also learn how to use our Arduino board with batteries, play with LCD displays, and use the VGA shield to plug the microcontroller to a typical computer screen.

Chapter 11, Networking, introduces the network concepts we need to understand in order to use our Arduino on Ethernet, wired or wireless networks. We will also use a powerful library that provides us a way to tweet messages directly by pushing a button on our Arduino, without using any computer.

Chapter 12, Playing with the Max 6 Framework, teaches some tips and techniques we can use with the Max 6 graphical programming framework. We will completely describe the use of the Serial object and how to parse and select data coming from Arduino to the computer. We will design a small sound-level meter using both real LEDs and Max 6 and finish by designing a Pitch shift sound effect controlled by our own hand and a distance sensor.

Chapter 13, Improving Your C Programming and Creating Libraries, is the most advanced chapter of the book. It describes some advanced C concepts that can be used to make our code reusable, more efficient, and optimized, through some nice and interesting real-world examples.

Appendix provides us with details of data types in C programming language, operator precedence in C and C++, important Math functions, Taylor series for calculation optimizations, an ASCII table, instructions for installing a library, and a list of components' distributors.

Appendix can be downloaded from http://www.packtpub.com/sites/default/files/downloads/7584OS_Appendix.pdf.

What you need for this book

If you want to take benefits of each example in this book, the following software is required:

The Arduino environment (free, http://arduino.cc/en/main/software). This is required for all operations related to Arduino programming.Fritzing (free, http://fritzing.org/download). This is an open source environment that helps us design circuits.Processing (free, http://processing.org/download). This is an open source framework for rapid prototyping using Java. Some examples use it as a communication partner for our Arduino boards.The Max 6 framework (trial version of 30 days, http://cycling74.com/downloads). This framework is a huge environment that is used in this book too.

Some other libraries are also used in this book. Every time they are needed, the example description explains where to download them from and how to install them on our computer.

Who this book is for

This book is for people who want to master do-it-yourself electronic hardware making with Arduino boards. It teaches everything we need to know to program firmware using C and how to connect the Arduino to the physical world, in great depth. From interactive-design art school students to pure hobbyists, from interactive installation designers to people wanting to learn electronics by entering a huge and growing community of physical computing programmers, this book will help everyone interested in learning new ways used to design smart objects, talking objects, efficient devices, and autonomous or connected reactive gears.

This book opens new vistas of learning-by-making, which will change readers' lives.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

[default] exten => s,1,Dial(Zap/1|30) exten => s,2,Voicemail(u100) exten => s,102,Voicemail(b100) exten => i,1,Voicemail(s0)

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

[default] exten => s,1,Dial(Zap/1|30) exten => s,2,Voicemail(u100) exten => s,102,Voicemail(b100) exten => i,1,Voicemail(s0)

Any command-line input or output is written as follows:

# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.conf

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "clicking the Next button moves you to the next screen."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Let's Plug Things

Arduino is all about plugging things. We are going to do that in a couple of minutes after we have learned a bit more about microcontrollers in general and especially the big and amazing Arduino family. This chapter is going to teach you how to be totally ready to code, wire, and test things with your new hardware friend. Yes, this will happen soon, very soon; now let's dive in!

What is a microcontroller?

A microcontroller is an integrated circuit (IC) containing all main parts of a typical computer, which are as follows:

ProcessorMemoriesPeripheralsInputs and outputs

The processor is the brain, the part where all decisions are taken and which can calculate.

Memories are often both spaces where both the core inner-self program and the user elements are running (generally called Read Only Memory (ROM) and Random Access Memory (RAM)).

I define peripherals by the self-peripherals contained in a global board; these are very different types of integrated circuits with a main purpose: to support the processor and to extend its capabilities.

Inputs and outputs are the ways of communication between the world (around the microcontroller) and the microcontroller itself.

The very first single-chip processor was built and proposed by Intel Corporation in 1971 under the name Intel 4004. It was a 4-bit central processing unit (CPU).

Since the 70s, things have evolved a lot and we have a lot of processors around us. Look around, you'll see your phone, your computer, and your screen. Processors or microprocessors drive almost everything.

Compared to microprocessors, microcontrollers provide a way to reduce power consumption, size, and cost. Indeed, microprocessors, even if they are faster than processors embedded in microcontrollers, require a lot of peripherals to be able to work. The high-level of integration provided by a microcontroller makes it the friend of embedded systems that are car engine controller, remote controller of your TV, desktop equipment including your nice printer, home appliances, games of children, mobile phones, and I could continue…

There are many families of microcontrollers that I cannot write about in this book, not to quote PICs (http://en.wikipedia.org/wiki/PIC_microcontroller) and Parallax SX microcontroller lines. I also want to quote a particular music hardware development open source project: MIDIbox (PIC-, then STM32-based, check http://www.ucapps.de). This is a very strong and robust framework, very tweakable. The Protodeck controller (http://julienbayle.net/protodeck) is based on MIDIbox.

Now that you have understood you have a whole computer in your hands, let's specifically describe Arduino boards!

Presenting the big Arduino family

Arduino is an open source (http://en.wikipedia.org/wiki/Open_source) singleboard-based microcontroller. It is a very popular platform forked from the Wiring platform (http://www.wiring.org.co/) and firstly designed to popularize the use of electronics in interaction design university students' projects.

My Arduino MEGA in my hand

It is based on the Atmel AVR processor (http://www.atmel.com/products/microcontrollers/avr/default.aspx) and provides many inputs and outputs in only one self-sufficient piece of hardware. The official website for the project is http://www.arduino.cc.

The project was started in Italy in 2005 by founders Massimo Banzi and David Cuartielles. Today it is one of the most beautiful examples of the open source concept, brought to the hardware world and being often used only in the software world.

We talk about Arduino family because today we can count around 15 boards 'Arduino-based', which is a funny meta-term to define different type of board designs all made using an Atmel AVR processor. The main differences between those boards are the:

Type of processorNumber of inputs and outputsForm factor

Some Arduino boards are a bit more powerful, considering calculation speed, some other have more memory, some have a lot of inputs/outputs (check the huge Arduino Mega), some are intended to be integrated in more complex projects and have a very small form factor with very few inputs and outputs… as I used to tell my students each one can find his friend in the Arduino family. There are also boards that include peripherals like Ethernet Connectors or even Bluetooth modules, including antennas.

The magic behind this family is the fact we can use the same Integrated Development Environment (IDE) on our computers with any of those boards (http://en.wikipedia.org/wiki/Integrated_development_environment). Some bits need to be correctly setup but this is the very same software and language we'll use:

Some notable Arduino family members: Uno R3, LilyPad, Arduino Ethernet, Arduino Mega, Arduino Nano, Arduino Pro, and a prototyping shield

A very nice but non-exhaustive reference page about this can be found at http://arduino.cc/en/Main/Hardware.

I especially want you to check the following models:

Arduino Uno is the basic one with a replaceable chipsetArduino Mega, 2560 provides a bunch of inputs and outputsArduino LilyPad, is wearable as clothesArduino Nano, is very small

Throughout this book I'll use an Arduino Mega and Arduino Uno too; but don't be afraid, when you've mastered Arduino programming, you'll be able to use any of them!

About hardware prototyping

We can program and build software quite easily today using a lot of open source frameworks for which you can find a lot of helpful communities on the Web. I'm thinking about Processing (Java-based, check http://processing.org), and openFrameworks (C++-based, check http://www.openframeworks.cc), but there are many others that sometimes use very different paradigms like graphical programming languages such as Pure Data (http://puredata.info), Max 6 (http://cycling74.com/products/max/), or vvvv (http://vvvv.org) for Windows.

Because we, the makers, are totally involved in do-it-yourself practices, we all want and need to build and design our own tools and it often means hardware and electronics tools. We want to extend our computers with sensors, blinking lights, and even create standalone gears.

Even for testing very basic things like blinking a light emitting diode (LED), it involves many elements from supplying power to chipset low-level programming, from resistors value calculations to voltage-driven quartz clock setup. All those steps just gives headache to students and even motivated ones can be put off making just a first test.

Arduino appeared and changed everything in the landscape by proposing an inexpensive and all-included solution (we have to pay $30 for the Arduino Uno R3), a cross-platform toolchain running on Windows, OS X, and Linux, a very easy high-level C language and library that can also tweak the low-level bits, and a totally extensible open source framework.

Indeed, with an all-included small and cute board, an USB cable, and your computer, you can learn electronics, program embedded hardware using C language, and blink your LED.

Hardware prototyping became (almost) as easy as software prototyping because of the high level of integration between the software and the hardware provided by the whole framework.

One of the most important things to understand here is the prototyping cycle.

One easy hardware prototyping steps list

From our idea to our final render, we usually have to follow these steps.

If we want to make that LED blink, we have to define several blinking characteristics for instance. It will help to precisely define the project, which is a key to success.

Then we'll have to sketch a schematic with our Arduino board and our LED; it will dig the question, "How are they connected together?"

The firmware programming using C language can directly be started after we have sketched the circuit because, as we'll see later, it is directly related to the hardware. This is one of the strong powers of Arduino development. You remember? The board design has been designed only to make us think about our project and not to confuse us with very low-level abstract learning bits.

The upload step is a very important one. It can provide us a lot of information especially in case of further troubleshooting. We'll learn that this step doesn't require more than a couple of clicks once the board is correctly wired to our computer.

Then, the subcycle test and fix will occur. We'll learn by making, by testing, and it means by failing too. It is an important part of the process and it will teach you a lot. I have to confess something important here: at the time when I first began my bonome project (http://julienbayle.net/bonome), an RGB monome clone device, I spent two hours fixing a reverse wired LED matrix. Now, I know them very well because I failed one day.

The last step is the coolest one. I mentioned it because we have to keep in our mind the final target, the one that will make us happy in the end; it is a secret to succeed!

Understanding Arduino software architecture

In order to understand how to make our nice Arduino board work exactly as we want it to, we have to understand the global software architecture and the toolchain that we'll be using quite soon.

Take your Arduino board in hand. You'll see a rectangle-shaped IC with the word ATMEL written on the top; this is the processor.

This processor is the place that will contain the entire program that we'll write and that will make things happen.

When we buy (check Appendix G, List of Components' Distributors, and this link: http://arduino.cc/en/Main/Buy) an Arduino, the processor, also named chipset, is preburnt. It has been programmed by careful people in order to make our life easier. The program already contained in the chipset is called the bootloader (http://en.wikipedia.org/wiki/Booting). Basically, it takes care of the very first moment of awakening of the processor life when you supply it some power. But its major role is the load of our firmware (http://en.wikipedia.org/wiki/Firmware), I mean, our precious compiled program.

Let's have a look at a small diagram for better understanding:

I like to define it by saying that the bootloader is the hardware's software and the firmware is the user's software. Indeed, it also has some significance because memory spaces in the chipset are not equal for write operations (within a specific hardware which we'll discuss in the future sections of this book). Using a programmer, we cannot overwrite the bootloader (which is safer at this point of our reading) but only the firmware. This will be more than enough even for advanced purposed, as you'll see all along the book.

Not all Arduino boards' bootloaders are equivalent. Indeed, they have been made to be very specific to the hardware part, which provides us more abstraction of the hardware; we can focus on higher levels of design because the bootloader provides us services such as firmware upload via USB and serial monitoring.

Let's now download some required software:

FTDI USB drivers: http://www.ftdichip.com/Drivers/VCP.htmArduino IDE: http://arduino.cc/en/Main/SoftwareProcessing: http://processing.org/download/

Processing is used in this book but isn't necessary to program and use Arduino boards.

Tip

What is the Arduino's toolchain?

Usually, we call Arduino's toolchain a set of software tools required to handle all steps from the C code we are typing in the Arduino IDE on our computer to the firmware uploaded on the board. Indeed, the C code you type has to be prepared before the compilation step with avr-gcc and avr-g++ compilers. Once the resulting object's files are linked by some other programs of the toolchain, into usually only one file, you are done. This can later be uploaded to the board. There are other ways to use Arduino boards and we'll introduce that in the last chapter of this book.

Installing Arduino development environment (IDE)

Let's find the compressed file downloaded from http://arduino.cc/en/Main/Software in the previous part and let's decompress it on our computer.

Whatever the platform, the IDE works equally and even if I'll describe some specific bits of three different platforms, I'll only describe the use of the IDE and show screenshots from OS X.

Installing the IDE

There isn't a typical installation of the IDE because it runs into the Java Virtual Machine. This means you only have to download it, to decompress it somewhere on your system, and then launch it and JAVA will execute the program. It is possible to use only the CLI (command-line interface, the famous g33ks window in which you can type the command directly to the system) to build your binaries instead of the graphical interface, but at this point, I don't recommend this.

Usually, Windows and OS X come with Java installed. If that isn't the case, please install it from the java.com website page at http://www.java.com/en/download/.

On Linux, the process really depends on the distribution you are using, so I suggest to check the page http://www.arduino.cc/playground/Learning/Linux and if you want to check and install all the environment and dependencies from sources, you can also check the page http://www.arduino.cc/playground/Linux/All.

How to launch the environment?

In Windows, let's click on the .exe file included in the uncompressed folder. On OS X, let's click on the global self-contained package with the pretty Arduino logo. On Linux, you'll have to start the Arduino script from the GUI or by typing in the CLI.

You have to know that using the IDE you can do everything we will make in this book.

What does the IDE look like?

The IDE provides a graphical interface in which you can write your code, debug it, compile it, and upload it, basically.

The famous Blink code example opened in the Arduino IDE

There are six icons from left to right that we have to know very well because we'll use them every time:

Verify (check symbol): This provides code checking for errorsUpload (right-side arrow): This compiles and uploads our code to the Arduino boardNew (small blank page): This creates a new blank sketchOpen (up arrow): This opens a list of all sketches already existing in our sketchbookSave (down arrow): This saves our sketch in our sketchbookSerial Monitor (small magnifying glass): This provides the serial monitoring

Each menu item in the top bar provides more options we will discover progressively all throughout this book.

However, the Tools menu deserves closer attention:

Auto Format: This provides code formatting with correct and standard indentationsArchive Sketch: This compresses the whole current sketch with all filesBoard: This provides a list of all boards supportedSerial Port: This provides a list of all serial devices on the systemProgrammer: This provides a list of all programmer devices supported and used in case of total reprogramming of the AVR chipsetBurn Bootloader: This is the option used when you want to overwrite (or even write) a new bootloader on your board.

The Tools menu

The preferences dialog is also a part we have to learn about right now. As usual, the preferences dialog is a place where we don't really need to go often but only for changing global parameters of the IDE. You can choose the sketchbook location and the Editor language in this dialog. You can also change a couple of bits like automatic check-up of IDE updates at start up or Editor font size.

The sketchbook concept will make our life easier. Indeed, the sketchbook is a folder where, basically, all your sketches will go. On my personal point of view, it is very precious to use it like this because it really organizes things for you and you can retrieve your pieces of code easier. Follow me there; you'll thank me later.

When we start a sketch from scratch, we basically type the code, verify it, upload it, and save it. By saving it, the first time, the IDE creates a folder in which it will put all the files related to our current sketch. By clicking on the sketch file inside this folder, the Arduino IDE will open and the related code will be displayed in the edit/typing part of the window.

We are almost done!

Let's install the drivers of the Arduino USB interface on our system.

Installing Arduino drivers

Arduino boards provide an USB interface. Before we plug the USB cable and link the board to our computer, we have to install specific drivers in the latter.

There is a huge difference between Windows and OS X here; basically, OS X doesn't require any specific drivers for Arduino Uno or even Mega 2560. If you are using older boards, you'd have to download the latest version of drivers on the FTDI website, double-click the package, then follow instructions, and finally, restart your computer.

Let's describe how it works on Windows-based systems, I mean, Windows 7, Vista, and XP.

Installing drivers for Arduino Uno R3

It is important to follow the steps mentioned next to be able to use the Arduino Uno R3 and some other boards. Please check the Arduino website for up-to-date references.

Plug your board in and wait for Windows to begin the driver installation process. After a few moments, the process fails.Click on the Start menu, and open Control Panel.In Control Panel, navigate to System and Security. Next, click on System. Once the System window is up, open Device Manager.Look under Ports (COM & LPT). Check the open port named Arduino UNO (COMxx).Right-click on the Arduino UNO (COMxx) port and choose the Update Driver Software option.Next, choose the Browse my computer for driver software option.Finally, navigate and select the Uno's driver file, named ArduinoUNO.inf, located in the Drivers folder of the Arduino software download (be careful: not the FTDI USB Drivers subdirectory).Windows will finish the driver installation from there and everything will be fine.

Installing drivers for Arduino Duemilanove, Nano, or Diecimilla

When you connect the board, Windows should initiate the driver installation process (if you haven't used the computer with an Arduino board before).

On Windows Vista, the driver should be automatically downloaded and installed. (Really, it works!)

On Windows XP, the Add New Hardware wizard will open:

When asked Can Windows connect to Windows Update to search for software? select No, not this time. Click on Next.Select Install from a list or specified location (Advanced) and click on Next.Make sure that Search for the best driver in these locations is checked, uncheck Search removable media, check Include this location in the search, and browse to the drivers/FTDI USB Drivers directory of the Arduino distribution. (The latest version of the drivers can be found on the FTDI website.) Click on Next.The wizard will search for the driver and then tell you that a USB Serial Converter was found. Click on Finish.The new hardware wizard will appear again. Go through the same steps and select the same options and location to search. This time, a USB Serial Port will be found.

You can check that the drivers have been installed by opening Windows Device Manager (in the Hardware tab of the System control panel). Look for a USB Serial Port in the Ports section; that's the Arduino board.

Now, our computer can recognize our Arduino board. Let's move to the physical world a bit to join together the tangible and intangible worlds.