Making Things Talk (PDFDrive)
Making Things Talk (PDFDrive)
Making Things Talk (PDFDrive)
Things Talk
Second Edition
Tom Igoe
Copyright © 2011 O’Reilly Media, Inc. All rights reserved. Printed in Canada.
O’Reilly books may be purchased for educational, business, or sales promotional use.
For more information, contact our corporate/institutional sales department:
800-998-9938 or [email protected].
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. The MAKE: Projects series
designations, Making Things Talk, and related trade dress are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed
as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of
the trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author
assume no responsibility for errors or omissions, or for damages resulting from the use of the
information contained herein.
Please note: Technology, and the laws and limitations imposed by manufacturers and content owners,
are constantly changing. Thus, some of the projects described may not work, may be inconsistent
with current laws or user agreements, or may damage or adversely affect some equipment.
Your safety is your own responsibility, including proper use of equipment and safety gear, and
determining whether you have adequate skill and experience. Power tools, electricity, and other
resources used for these projects are dangerous unless used properly and with adequate precautions,
including safety gear. Some illustrative photos do not depict safety precautions or equipment, in
order to show the project steps more clearly. These projects are not intended for use by children.
Use of the instructions and suggestions in Making Things Talk is at your own risk. O’Reilly Media, Inc.,
disclaims all responsibility for any resulting damage, injury, or expense. It is your responsibility to
make sure that your activities comply with applicable laws, including copyright.
ISBN: 978-1-449-39243-7
[TI]
Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
Who This Book Is For. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . viii
What You Need to Know. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
Contents of This Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
On Buying Parts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . x
Using Code Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
Using Circuit Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
Acknowledgments for the First Edition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xii
Note on the Second Edition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiv
Chapter 10: Mobile Phone Networks and the Physical World. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
Supplies for Chapter 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
One Big Network. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
Project 29: CatCam Redux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Project 30: Phoning the Thermostat. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
Text-Messaging Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
Native Applications for Mobile Phones. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
Project 31: Personal Mobile Datalogger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
Conclusion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
vi MAKING THINGS TALK
Making Things Talk
MAKE: PROJECTS
Preface
A few years ago, Neil Gershenfeld wrote a smart book called When
information about our identities, abilities, and actions. It’s a good read,
but I think he got the title wrong. I would have called it When Things
are worthwhile only once you start to talk to someone else about them.
Making Things Talk teaches you how to make things that have compu-
tational power talk to each other, and about giving people the ability to
For a couple of decades now, computer scientists have In the physical world, we’re surrounded by all kinds of
used the term object-oriented programming to refer to a electronic objects: clock radios, toasters, mobile phones,
style of software development in which programs and sub- music players, children’s toys, and more. It can take a
programs are thought of as objects. Like physical objects, lot of work and a significant amount of knowledge to make
they have properties and behaviors. They inherit these a useful electronic gadget—it can take almost as much
properties from the prototypes from which they descend. knowledge to make those gadgets talk to each other in
The canonical form of any object in software is the code useful ways. But that doesn’t have to be the case. Electronic
that describes its type. Software objects make it easy to devices can be—and often are—built up from simple
recombine objects in novel ways. You can reuse a software modules. As long as you understand the interfaces, you
object if you know its interface—the collection of proper- can make anything from them. Think of it as object-oriented
ties and methods to which its creator allows you access hardware. Understanding the ways in which things talk to
(as well as the documents so that you know how to use each other is central to making this work, regardless of
them). It doesn’t matter how a software object does what whether the object is a toaster, an email program on your
it does, as long as it does it consistently. Software objects laptop, or a networked database. All of these objects can
are most effective when they’re easy to understand and be connected if you can figure out how they communicate.
when they work well with other objects. This book is a guide to some of the tools for making those
connections.
X
components used here strike a balance between simplic- to get you to the end goal of making things talk to each
ity, flexibility, and cost. They use object-oriented hardware, other as quickly as possible.
requiring relatively little wiring or code. They’re designed X
In Chapter 1, you’ll encounter the major programming those things separate in your mind helps troubleshooting.
tools in the book and get to “Hello World!” on each of them. You’ll build a simple project that features one-to-one serial
communication between a microcontroller and a personal
Chapter 2 introduces the most basic concepts needed to computer using Bluetooth radios as an example of modem
make things talk to each other. It covers the characteristics communication. You’ll learn about data protocols, modem
that need to be agreed upon in advance, and how keeping devices, and address schemes.
x MAKING THINGS TALK
Chapter 3 introduces a more complex network: the Chapter 7 offers a contrast to the socket connections of
Internet. It discusses the basic devices that hold it Chapter 5, by introducing message-based protocols like
together, as well as the basic relationships among those UDP on the Internet, and ZigBee and 802.15.4 for wireless
devices. You’ll see the messages that underlie some of the networks. Instead of using the client-server model from
most common tasks you do on the Internet every day, and earlier chapters, here you’ll learn how to design conversa-
learn how to send those messages. You’ll write your first tions where each object in a network is equal to the others,
set of programs to send data across the Net based on a exchanging information one message at a time.
physical activity in your home.
Chapter 8 is about location. It introduces a few tools to
In Chapter 4, you’ll build your first embedded device. You’ll help you locate things in physical space, and it offers some
get more experience with command-line connections to thoughts on the relationship between physical location and
the Net, and you’ll connect a microcontroller to a web network relationships.
server without using a desktop or laptop computer as an
intermediary. Chapter 9 deals with identification in physical space and
network space. You’ll learn a few techniques for generat-
Chapter 5 takes the Net connection a step further by ing unique network identities based on physical charac-
explaining socket connections, which allow for longer teristics. You’ll also learn a bit about how to determine a
interaction. You’ll learn how to write your own server networked device’s characteristics.
program that you can connect to anything connected to
the Net. You’ll connect to this server program from the Chapter 10 introduces mobile telephony networks, covering
command line and from a microcontroller, so that you can many of the things that you can now do with phones and
understand how different types of devices can connect to phone networks.
each other through the same server.
Chapter 11 provides a look back at the different types of
Chapter 6 introduces wireless communication. You’ll learn protocols covered in this book, and gives you a framework
some of the characteristics of wireless, along with its pos- to fit them all into for future reference.
sibilities and limitations. Several short examples in this X
chapter enable you to say “Hello World!” over the air in a
number of ways.
On Buying Parts
You’ll need a lot of parts for all of the projects in this book. As a result, you’ll learn about
a lot of vendors. Because there are no large electronics parts retailers in my city, I buy
parts online all the time. If you’re lucky enough to live in an area where you can buy from
a brick-and-mortar store, good for you! If not, get to know some of these online vendors.
Jameco (http://jameco.com), Digi-Key (www.digikey. Because it’s easy to order goods online, you might be
com), and Farnell (www.farnell.com) are general electron- tempted to communicate with vendors entirely through
ics parts retailers, and they sell many of the same things. their websites. Don’t be afraid to pick up the phone as well.
Others, like Maker Shed (www.makershed.com), SparkFun Particularly when you’re new to this type of project, it
(www.sparkfun.com), and Adafruit (http://adafruit.com) helps to talk to someone about what you’re ordering and to
carry specialty components, kits, and bundles that make ask questions. You’re likely to find helpful people at the end
it easy to do popular projects. A full list of suppliers is of the phone line for most of the retailers listed here. I’ve
included in the Appendix. Feel free to substitute parts for listed phone numbers wherever possible—use them.
things with which you are familiar. X
PREFACE xi
For example, writing a program that uses several chunks of We appreciate attribution. An attribution usually includes
code from this book does not require permission. Selling the title, author, publisher, and ISBN. For example:
or distributing a CD-ROM of examples from O’Reilly books “Making Things Talk: Practical Methods for Connecting
does require permission. Answering a question by citing Physical Objects, by Tom Igoe. Copyright 2011 O’Reilly
this book and quoting example code does not require Media, 978-1-4493-9243-7.” If you feel that your use of
permission. Incorporating a significant amount of example code examples falls outside fair use or the permission
code from this book into your product’s documentation given above, feel free to contact us at permissions@
does require permission. oreilly.com.
X
Even though we want you to be adventurous, we also want Please keep in mind that the projects and circuits shown
you to be safe. Please don’t take any unnecessary risks in this book are for instructional purposes only. Details like
when building this book’s projects. Every set of instruc- power conditioning, automatic resets, RF shielding, and
tions is written with safety in mind; ignore the safety other things that make an electronic product certifiably
instructions at your own peril. Be sure you have the appro- ready for market are not included here. If you’re designing
priate level of knowledge and experience to get the job real products to be used by people other than yourself,
done in a safe manner. please do not rely on this information alone.
X
xii MAKING THINGS TALK
The Interactive Telecommunications Program in the Tisch networked objects, and made things possible for the
School of the Arts at New York University has been my other faculty and me, as well as the students. Research
home for more than the past decade. It is a lively and residents Carlyn Maw, Todd Holoubek, John Schimmel,
warm place to work, crowded with many talented people. Doria Fan, David Nolen, Peter Kerlin, and Michael Olson
This book grew out of a class, Networked Objects, that I assisted faculty and students over the past few years
have taught there for several years. I hope that the ideas to realize projects that influenced the ones you see in
herein represent the spirit of the place and give you a these chapters. Faculty members Patrick Dwyer, Michael
sense of my enjoyment in working there. Schneider, Greg Shakar, Scott Fitzgerald, Jamie Allen,
Shawn Van Every, James Tu, and Raffi Krikorian have used
Red Burns, the department’s founder, has supported the tools from this book in their classes, or have lent their
me since I first entered this field. She indulged my many own techniques to the projects described here.
flights of fancy and brought me firmly down to earth when
needed. On every project, she challenges me to make sure The students of ITP have pushed the boundaries of pos-
that I use technology not for its own sake, but always so it sibility in this area, and their work is reflected in many
empowers people. of the projects. I cite specifics where they come up, but
in general, I’d like to thank all the students who took my
Dan O’Sullivan, my colleague and now chair of the program, Networked Objects class—they helped me understand
introduced me to physical computing and then generously what this is all about. Those from the 2006 and 2007
allowed me to share in teaching it and shaping its role at classes were particularly influential, because they had to
ITP. He is a great advisor and collaborator, and offered learn the stuff from early drafts of this book. They have
constant feedback as I worked. Most of the chapters caught several important mistakes in the manuscript.
started with a rambling conversation with Dan. His finger-
prints are all over this book, and it’s a better book for it. A few people contributed significant amounts of code,
ideas, or labor to this book. Geoff Smith gave me the
Clay Shirky, Daniel Rozin, and Dan Shiffman were also original title for the course, Networked Objects, and intro-
close advisors on this project. Clay watched indulgently as duced me to the idea of object-oriented hardware. John
the pile of parts mounted in our office, and he graciously Schimmel showed me how to get a microcontroller to
interrupted his own writing to give opinions on my ideas. make HTTP calls. Dan O’Sullivan’s server code was the
Daniel Rozin offered valuable critical insight as well, and root of all of my server code. All of my Processing code
his ideas are heavily influential in this book. Dan Shiffman is more readable because of Dan Shiffman’s coding style
read many drafts and offered helpful feedback. He also advice. Robert Faludi contributed many pieces of code,
contributed many great code samples and libraries. made the XBee examples in this book simpler to read, and
corrected errors in many of them. Max Whitney helped
Fellow faculty members Marianne Petit, Nancy Hechinger, me get Bluetooth exchanges working and get the cat bed
and Jean-Marc Gauthier were supportive throughout this finished (despite her allergies!). Dennis Crowley made the
writing, offering encouragement and inspiration, covering possibilities and limitations of 2D barcodes clear to me.
departmental duties for me, and offering inspiration Chris Heathcote heavily influenced my ideas on location.
through their own work. Durrell Bishop helped me think about identity. Mike
Kuniavsky and the folks at the “Sketching in Hardware”
The rest of the faculty and staff at ITP also made this workshops in 2006 and 2007 helped me see this work
possible. George Agudow, Edward Gordon, Midori Yasuda, as part of a larger community, and introduced me to a lot
Megan Demarest, Nancy Lewis, Robert Ryan, John Duane, of new tools. Noodles the cat put up with all manner of
Marlon Evans, Tony Tseng, and Gloria Sed tolerated all silliness in order to finish the cat bed and its photos. No
kinds of insanity in the name of physical computing and animals were harmed in the making of this book, though
one was bribed with catnip.
PREFACE xiii
Casey Reas and Ben Fry made the software side of this endlessly encouraging. It’s an understatement to say that
book possible by creating Processing. Without Processing, I couldn’t have done this without him. I could not have
the software side of networked objects was much more asked for a better editor. Thanks to Nancy Kotary for her
painful. Without Processing, there would be no simple, excellent copyedit of the manuscript. Katie Wilson made
elegant programming interface for Arduino and Wiring. The this book far better looking and readable than I could ever
originators of Arduino and Wiring made the hardware side have hoped. Thanks also to Tim Lillis for the illustrations.
of this book possible: Massimo Banzi, Gianluca Martino, Thanks to all of the MAKE team.
David Cuartielles, and David Mellis on Arduino; Hernando
Barragán on Wiring; and Nicholas Zambetti bridging the Thanks to my agents: Laura Lewin, who got the ball rolling;
two. I have been lucky to work with them. Neil Salkind, who picked it up from her; and the whole
support team at Studio B. Thanks finally to my family and
Though I’ve tried to use and cite many hardware vendors friends who listened to me rant enthusiastically or complain
in this book, I must give a special mention to Nathan bitterly as this book progressed. Much love to you all.
Seidle at Spark Fun. This book would not be what it is X
without him. While I’ve been talking about object-oriented
hardware for years, Nathan and the folks at SparkFun have
been quietly making it a reality.
Thanks also to the support team at Lantronix. Their We’d Like to Hear from You
products are good and their support is excellent. Garry Please address comments and questions concerning this book
Morris, Gary Marrs, and Jenny Eisenhauer answered my to the publisher:
countless emails and phone calls helpfully and cheerfully.
O’Reilly Media, Inc.
In this book’s projects, I drew ideas from many colleagues 1005 Gravenstein Highway North
from around the world through conversations in workshops Sebastopol, CA 95472
and visits. Thanks to the faculty and students I’ve worked (800) 998-9938 (in the United States or Canada)
with at the Royal College of Art’s Interaction Design program, (707) 829-0515 (international or local)
UCLA’s Digital Media | Arts program, the Interaction Design (707) 829-0104 (fax)
program at the Oslo School of Architecture and Design,
Interaction Design Institute Ivrea, and the Copenhagen We have a website for this book, where we list errata,
Institute of Interaction Design. examples, and any additional information. You can access
this page at: www.makezine.com/go/MakingThingsTalk
Many networked object projects inspired this writing.
Thanks to those whose work illustrates the chapters: To comment or ask technical questions about this book,
Tuan Anh T. Nguyen, Joo Youn Paek, Doria Fan, Mauricio send email to: [email protected]
Melo, and Jason Kaufman; Tarikh Korula and Josh
Rooke-Ley of Uncommon Projects; Jin-Yo Mok, Alex Beim, Maker Media is a division of O’Reilly Media devoted entirely
Andrew Schneider, Gilad Lotan and Angela Pablo; Mouna to the growing community of resourceful people who believe
Andraos and Sonali Sridhar; Frank Lantz and Kevin Slavin that if you can imagine it, you can make it. Consisting of MAKE
of Area/Code; and Sarah Johansson. Magazine, CRAFT Magazine, Maker Faire, and the Hacks series
of books, Maker Media encourages the Do-It-Yourself mentality
Working for MAKE has been a great experience. Dale by providing creative inspiration and instruction.
Dougherty encouraged of all of my ideas, dealt patiently
with my delays, and indulged me when I wanted to try new For more information about Maker Media, visit us online:
things. He’s never said no without offering an acceptable MAKE: www.makezine.com
alternative (and often a better one). Brian Jepson has gone CRAFT: www.craftzine.com
above and beyond the call of duty as an editor, building all Maker Faire: www.makerfaire.com
of the projects, suggesting modifications, debugging code, Maker SHED: www.makershed.com
helping with photography and illustrations, and being
xiv MAKING THINGS TALK
Before any technology is adopted in general use, there The growth of Arduino shields and libraries has been big
has to be a place for it in the popular imagination. People enough that I almost could have written this edition so
with no knowledge of the technology must have some that you wouldn’t have to do any programming or circuit
idea what it is and for what it can be used. Prior to 2005, building. There’s a shield or a library to do almost every
I spent a lot of time explaining to people what physical project in this book. However, you can only learn so much
computing was and what I meant by “networked objects.” by fitting premade pieces together, so I’ve tried to show
Nowadays, everyone knows the Wii controller or the Kinect some of the principles underlying electronic communica-
as an example of a device that expands the range of tions and physical interfaces. Where there is a simple
human physical expression available to computers. These hardware solution, I’ve indicated it but shown the circuit
days, it’s difficult to find an electronic device that isn’t it encloses as well. The best code libraries and circuit
networked. designs practice what I think of as “glass-box enclosure”—
they enclose the gory details and give you a convenient
While it’s been great to see these ideas gain a general interface, but they let you look inside and see what’s
understanding, what’s even more exciting is seeing them going on if you’re interested. Furthermore, they’re well-
gain in use. People aren’t just using their Kinects for constructed so that the gory details don’t seem that gory
gaming, they’re building them into assistive interfaces for when you look closely at them. Hopefully, this edition will
physically challenged clients. They’re not just playing with work in much the same way.
the Wii, they’re using it as a musical instrument controller.
People have become accustomed to the idea that they can
modify the use of their electronics—and they’re doing it. Software Reference
There have been a number of large changes made to the
When I joined the project, my hope for Arduino was that Arduino platform since I started this edition. The Arduino
it might fill a need for something more customizable than IDE was in beta development, but by the time this book
consumer electronic devices were at the time, yet be less comes out, version 1.0 will be available. If you’re already
difficult to learn than microcontroller systems. I thought familiar with Arduino, please make sure you’ve downloaded
the open source approach was a good way to go because version 1,0beta1 or later of the IDE. This book was written
it meant that hopefully the ideals of the platform would using Arduino 1.0 beta1, which is available online at http://
spread beyond the models we made. That hope has been code.google.com/p/arduino/wiki/Arduino1. The final 1.0
realized in the scores of derivative boards, shields, spinoff version will be available on the Download page at www.
products, and accessories that have popped up in the last arduino.cc. Check the Arduino site for the latest updates.
several years. It’s wonderful to see so many people not The code for this book can be found online on my gitHub
just making electronics for others to build on, but doing it repository at https://github.com/tigoe/MakingThing-
in a way that doesn’t demand professional expertise to get sTalk2 and I’ll write about any changes on the blog, www.
started. makingthingstalk.com.
PREFACE xv
The Tools
This book is a cookbook of sorts, and this chapter covers the key ingre-
dients. The concepts and tools you’ll use in every chapter are intro-
duced here. There’s enough information on each tool to get you to the
point where you can make it say “Hello World!” Chances are you’ve
used some of the tools in this chapter before—or ones just like them.
Skip past the things you know and jump into learning the tools that are
new to you. You may want to explore some of the less-familiar tools
on your own to get a sense of what they can do. The projects in the
following chapters only scratch the surface of what’s possible for most
of these tools. References for further investigation
are provided.
An object’s interface is made up of three elements. First, not all software interfaces are as simple as you’d like them
there’s the physical interface. This is the stuff you touch— to be, so be prepared to experiment a little to get some
such as knobs, switches, keys, and other sensors—that software objects to do what you think they should do.
react to your actions. The connectors that join objects When you’re learning a new software interface, it helps
are also part of the physical interface. Every network of to approach it mentally in the same way you approach
objects begins and ends with a physical interface. Even a physical interface. Don’t try to use all the functions
though some objects in a network (such as software at once; first, learn what each function does on its own.
objects) have no physical interface, people construct You don’t learn to play the piano by starting with a Bach
mental models of how a system works based on the fugue—you start one note at a time. Likewise, you don’t
physical interface. A computer is much more than the learn a software interface by writing a full application with
keyboard, mouse, and screen, but that’s what we think of it it—you learn it one function at a time. There are many
as, because that’s what we see and touch. You can build all projects in this book; if you find any of their software
kinds of wonderful functions into your system, but if those functions confusing, write a simple program that demon-
functions aren’t apparent in the things people see, hear, strates just that function, then return to the project.
and touch, they will never be used. Remember the lesson
of the VCR clock that constantly blinks 12:00 because no Finally, there’s the electrical interface—the pulses of electri-
one can be bothered to learn how to set it? If the physical cal energy sent from one device to another to be interpreted
interface isn’t good, the rest of the system suffers. as information. Unless you’re designing new objects or the
connections between them, you never have to deal with
Second, there’s the software interface—the commands this interface. When you’re designing new objects or the
that you send to the object to make it respond. In some networks that connect them, however, you have to under-
projects, you’ll invent your own software interface; in stand a few things about this interface, so that you know
others, you’ll rely on existing interfaces to do the work for how to match up objects that might have slight differences
you. The best software interfaces have simple, consistent in their electrical interfaces.
functions that result in predictable outputs. Unfortunately, X
Serial protocols like RS-232, USB, and IEEE 1394 (also by sending timed pulses of energy across a shared con-
known as FireWire and i.Link) connect computers to nection. The USB connection from your mouse to your
printers, hard drives, keyboards, mice, and other periph- computer uses two wires for transmission and reception,
eral devices. Network protocols like Ethernet and TCP/ sending timed pulses of electrical energy across those
IP connect multiple computers through network hubs, wires. Likewise, wired network connections are made up of
routers, and switches. A communications protocol usually timed pulses of electrical energy sent down the wires. For
defines the rate at which messages are exchanged, the longer distances and higher bandwidth, the electrical wires
arrangement of data in the messages, and the grammar of may be replaced with fiber optic cables , which carry timed
the exchange. If it’s a protocol for physical objects, it will pulses of light. In cases where a physical connection is
also specify the electrical characteristics, and sometimes inconvenient or impossible, the transmission can be sent
even the physical shape of the connectors. Protocols using pulses of radio energy between radio transceivers (a
don’t specify what happens between objects, however. transceiver is two-way radio, capable of transmitting and
The commands to make an object do something rely on receiving). The meaning of data pulses is independent of
protocols in the same way that clear instructions rely on the medium that’s carrying them. You can use the same
good grammar—you can’t give useful instructions if you sequence of pulses whether you’re sending them across
can’t form a good sentence. wires, fiber optic cables, or radios. If you keep in mind that
all of the communication you’re dealing with starts with
One thing that all communications protocols have in a series of pulses—and that somewhere there’s a guide
common—from the simplest chip-to-chip message to the explaining the sequence of those pulses—you can work
most complex network architecture—is this: it’s all about with any communication system you come across.
pulses of energy. Digital devices exchange information X
The second type of computer you’ll encounter in this book, In other words, the microcontroller’s physical interface is
the microcontroller, has no physical interface that humans whatever you make of it.
can interact with directly. It’s just an electronic chip with
input and output pins that can send or receive electrical The third type of computer in this book, the network
pulses. Using a microcontroller is a three-step process: server, is basically the same as a desktop computer—it
may even have a keyboard, screen, and mouse. Even
1. You connect sensors to the inputs to convert physical though it can do all the things you expect of a personal
energy like motion, heat, and sound into electrical energy. computer, its primary function is to send and receive data
2. You attach motors, speakers, and other devices to the over a network. Most people don’t think of servers as
outputs to convert electrical energy into physical action. physical things because they only interact with them over
3. Finally, you write a program to determine how the input a network, using their local computers as physical inter-
changes affect the outputs. faces to the server. A server’s most important interface for
most users’ purposes is its software interface.
4 MAKING THINGS TALK
The fourth group of computers is a mixed bag: mobile these devices as computers, they are. When you think of
phones, music synthesizers, and motor controllers, to them as programmable objects with interfaces that you
name a few. Some of them will have fully developed can manipulate, it’s easier to figure out how they can all
physical interfaces, some will have minimal physical inter- communicate, regardless of their end function.
faces but detailed software interfaces, and most will have X
a little of both. Even though you don’t normally think of
Good Habits
Networking objects is a bit like love. The fundamental problem in both is that when
you’re sending a message, you never really know whether the receiver understands
what you’re saying, and there are a thousand ways for your message to get lost or
garbled in transmission.
You may know how you feel but your partner doesn’t. Never Assume
All he or she has to go on are the words you say and the What you say is not always what the other person hears.
actions you take. Likewise, you may know exactly what Sometimes it’s a matter of misinterpretation, and other
message your local computer is sending, how it’s sending times, you may not have been heard clearly. If you assume
it, and what all the bits mean, but the remote computer that the message got through and continue on oblivi-
has no idea what they mean unless you program it to ously, you’re in for a world of hurt. Likewise, you may be
understand them. All it has to go on are the bits it receives. inclined to first work out all the logic of your system—and
If you want reliable, clear communications (in love or net- all the steps of your messages before you start to connect
working), there are a few simple things you have to do: things—then build it, and finally test it all at once. Avoid
that temptation.
• Listen more than you speak.
• Never assume that what you said is what they heard. It’s good to plan the whole system out in advance, but
• Agree on how you’re going to say things in advance. build it and test it in baby steps. Most of the errors that
• Ask politely for clarification when messages aren’t clear. occur when building these projects happen in the com-
munication between objects. Always send a quick “Hello
World!” message from one object to the others, and make
Listen More Than You Speak sure that the message got there intact before you proceed
The best way to make a good first impression, and to main- to the more complex details. Keep that “Hello World!”
tain a good relationship, is to be a good listener. Listening example on hand for testing when communication fails.
is more difficult than speaking. You can speak anytime you
want, but since you never know when the other person Getting the message wrong isn’t the only misstep you can
is going to say something, you have to listen all the time. make. Most of the projects in this book involve building the
In networking terms, this means you should write your physical, software, and electrical elements of the interface.
programs such that they’re listening for new messages most One of the most common mistakes people make when
of the time, and sending messages only when necessary. developing hybrid projects like these is to assume that
It’s often easier to send out messages all the time rather the problems are all in one place. Quite often, I’ve sweated
than figure out when it’s appropriate, but it can lead to all over a bug in the software transmission of a message,
kinds of problems. It usually doesn’t take a lot of work to only to find out later that the receiving device wasn’t even
limit your sending, and the benefits far outweigh the costs. connected, or wasn’t ready to receive messages. Don’t
THE TOOLS 5
assume that communication errors are in the element of Ask Politely for Clarification
the system with which you’re most familiar. They’re most Messages get garbled in countless ways. Perhaps you hear
often in the element with which you’re least familiar, and something that may not make much sense, but you act
therefore, are avoiding. When you can’t get a message on it, only to find out that your partner said something
through, think about every link in the chain from sender entirely different from what you thought. It’s always best
to receiver, and check every one. Then check the links you to ask nicely for clarification to avoid making a stupid
overlooked. mistake. Likewise, in network communications, it’s wise
to check that any messages you receive make sense.
When they don’t, ask for a repeat transmission. It’s also
Agree on How You Say Things wise to check, rather than assume, that a message was
In good relationships, you develop a shared language sent. Saying nothing can be worse than saying something
based on shared experience. You learn the best ways to wrong. Minor problems can become major when no one
say things so that your partner will be most receptive, speaks up to acknowledge that there’s an issue. The same
and you develop shorthand for expressing things that you thing can occur in network communications. One device
repeat all the time. Good data communications also rely may wait forever for a message from the other side, not
on shared ways of saying things, or protocols. Sometimes knowing, for example, that the remote device is unplugged.
you make up a protocol for all the objects in your system, When you don't receive a response, send another
and other times you have to rely on existing protocols. message. Don’t resend it too often, and give the other
If you’re working with a previously established protocol, party time to reply. Acknowledging messages may seem
make sure you understand all the parts before you start like a luxury, but it can save a whole lot of time and energy
trying to interpret it. If you have the luxury of making when you’re building a complex system.
up your own protocol, make sure you’ve considered the X
needs of both the sender and receiver when you define
it. For example, you might decide to use a protocol that’s
easy to program on your web server, but that turns out to
be impossible to handle on your microcontroller. A little
thought to the strengths and weaknesses on both sides of
the transmission, and a bit of compromise before you start
to build, will make things flow much more smoothly.
Tools
As you’ll be working with the physical, software, and electrical interfaces of objects,
you’ll need physical tools, software, and (computer) hardware.
Physical Tools
If you’ve worked with electronics or microcontrollers NOTE: You’ll find a number of component suppliers in this book. I
before, chances are you have your own hand tools already. buy from different vendors depending on who’s got the best and
Figure 1-1 shows the ones used most frequently in this the least expensive version of each part. Sometimes it’s easier to
book. They’re common tools that can be obtained from buy from a vendor that you know carries what you need, rather
many vendors. A few are listed in Table 1-1. than search through the massive catalog of a vendor who might
carry it for less. Feel free to substitute your favorite vendors. A list
In addition to hand tools, there are some common elec- of vendors can be found in the Appendix.
tronic components that you’ll use all the time. They’re
listed as well, with part numbers from the retailers
featured most frequently in this book. Not all retailers will
carry all parts, so there are many gaps in the table.
6 MAKING THINGS TALK
8 1
10
3
11
2
12 18
17
5
4
26
27
13 16
15
14
22
23 28
25
21
19
29
20
24
1 Soldering iron Middle-of-the-line is best Diagonal cutter: Jameco: 161411; Farnell: TOL-10244 (v2); Seeed Studio (www.seeed-
here. Cheap soldering irons die fast, but 3125397; Spark Fun: TOL-00070; studio.com): (TOL114C3M; Maker SHED
a mid-range iron like the Weller WLC-100 RadioShack: 640-2043 (www.makershed.com): MKSEEED11
works great for small electronic work. Needlenose pliers: Jameco: 35473;
Avoid the Cold Solder irons. They solder Farnell: 3127199; Spark Fun: TOL-00079; 10 9–12V DC power supply You’ll use this
by creating a spark, and that spark RadioShack: 640-2033 all the time, and you’ve probably got a
can damage static-sensitive parts like spare from some dead electronic device.
microcontrollers. Jameco (http://jameco. 5 Mini-screwdriver Get one with both Make sure you know the polarity of the
com): 146595; Farnell (www.farnell.com): Phillips and slotted heads. You’ll use it all plug so you don’t reverse polarity on
1568159; RadioShack (http://radioshack. the time. Jameco: 127271; Farnell: 4431212; a component and blow it up! Most of
com): 640-2801 and 640-2078 RadioShack: 640-1963 the devices shown in this book have a
DC power jack that accepts a 2.1mm
2 Solder 21-23 AWG solder is best. Get 6 Safety goggles Always a good idea when inner diameter/5.5mm outer diameter
lead-free solder if you can; it’s healthier soldering, drilling, or other tasks. Spark plug, so look for an adapter with the
for you. Jameco: 668271; Farnell: 419266; Fun:SWG-09791; Farnell: 1696193 same dimensions. Jameco: 170245 (12V,
RadioShack: 640-0013 1000mA); Farnell: 1176248 (12V, 1000mA);
7 Helping hands These make soldering Spark Fun: TOL-00298; RadioShack: 273-355
3 Desoldering pump This helps when you much easier. Jameco: 681002; Farnell: (9V 800mA)
mess up while soldering. Jameco: 305226; 1367049
Spark Fun (www.SparkFun.com): TOL- 11 Power connector, 2.1mm inside
00082; Farnell: 3125646 8 Multimeter You don’t need an diameter/5.5mm outside diameter You’ll
expensive one. As long as it measures need this to connect your microcon-
4 Wire stripper, Diagonal cutter, Needle- voltage, resistance, amperage, and con- troller module or breadboard to a DC
nose pliers Avoid the 3-in-1 versions tinuity, it’ll do the job. Jameco: 220812; power supply. This size connector is the
of these tools. They’ll only make you Farnell: 7430566; Spark Fun: TOL-00078; most common for the power supplies
grumpy. These three tools are essential RadioShack: 22-182 that will work with the circuits you’ll be
for working with wire, and you don’t building here. Jameco: 159610; Digi-Key
need expensive ones to have good ones. 9 Oscilloscope Professional oscilloscopes (www.digikey.com): CP-024A-ND; Farnell:
Wire stripper: Jameco: 159291; Farnell: are expensive, but the DSO Nano is 3648102
609195; Spark Fun: TOL-00089; only about $100 and a valuable aid
RadioShack: 640-2129A when working on electronics. Spark Fun:
THE TOOLS 7
12 9V Battery snap adapter and 9V battery 19 Prototyping shields These are add-on and force-sensing resistors are handy
When you want to run a project off boards for the Arduino microcontroller for testing a circuit or a program. Flex
battery power, these adapters are a module that have a bare grid of holes to sensors: Jameco: 150551; Images SI (www.
handy way to do it. Spark Fun: PRT- which you can solder. You can build your imagesco.com): FLX-01
09518; Adafruit (http://adafruit.com): own circuits on them by soldering, or you Force-sensing resistors: Parallax (www.
80; Digi-Key: CP3-1000-ND and 84-4K-ND; can use a tiny breadboard (also shown) parallax.com): 30056; Images SI: FSR-400,
Jameco: 28760 and 216452; Farnell: 1650675 to test circuits quickly. These are handy 402, 406, 408
and 1737256; RadioShack: 270-324 and for projects where you need to prototype
274-1569 quickly, as well as a compact form to the 25 Pushbuttons There are two types
electronics. Adafruit: 51; Arduino Store: you’ll find handy: the PCB-mount type,
13 USB cables You’ll need both USB A000024; Spark Fun: DEV-07914; Maker like the ones you find on Wiring and
A-to-B (the most common USB cables) SHED: MSMS01 Arduino boards, used here mostly as
and USB A-to-mini-B (the kind that’s Breadboards for protoshields: Spark Fun: reset buttons for breadboard projects;
common with digital cameras) for the PRT-08802; Adafruit: included with board; and panel-mount types used for
projects in this book. Spark Fun: CAB- Digi-Key: 923273-ND interface controls for end users. But you
00512, CAB-00598; Farnell: 1838798, can use just about any type you want.
1308878 20 Solderless breadboard Having a few PCB-mount type: Digi-Key: SW400-ND;
around can be handy. I like the ones Jameco: 119011; Spark Fun: COM-00097
14 Alligator clip test leads It’s often hard with two long rows on either side so that Panel-mount type: Digi-Key: GH1344-ND;
to juggle the five or six things you have you can run power and ground on both Jameco: 164559PS
to hold when metering a circuit. Clip sides. Jameco: 20723 (2 bus rows per side);
leads make this much easier. Jameco: Farnell: 4692810; Digi-Key: 438-1045-ND; 26 Potentiometers You’ll need potentiom-
10444; RS (www.rs-online.com): 483-859; Spark Fun: PRT-00137; RadioShack: 276-002 eters to let people adjust settings in your
Spark Fun: CAB-00501; RadioShack: project. Jameco: 29081; Spark Fun: COM-
278-016 21 Spare LEDs for tracing signals LEDs 09939; RS: 91A1A-B28-B15L; RadioShack:
are to the hardware developer what 271-1715; Farnell: 1760793
15 Serial-to-USB converter This converter print statements are to the software
lets you speak TTL serial from a USB developer. They let you see quickly 27 Ethernet cables A couple of these
port. Breadboard serial-to-USB modules, whether there’s voltage between two will come in handy. Jameco: 522781;
like the FT232 modules shown here, are points, or whether a signal is going RadioShack: 55010852
cheaper than the consumer models and through. Keep spares on hand. Jameco:
easier to use in the projects in this book. 3476; Farnell: 1057119; Digi-Key: 160-1144- 28 Black, red, blue, yellow wire 22 AWG
Spark Fun: BOB-00718; Arduino Store ND; RadioShack: 278-016 solid-core hook-up wire is best for
(store.arduino.cc): A000014 making solderless breadboard connec-
22 Resistors You’ll need resistors of tions. Get at least three colors, and
16 Microcontroller module The microcon- various values for your projects. Common always use red for voltage and black for
troller shown here is an Arduino Uno. values are listed in Table 1-1. ground. A little organization of your wires
Available from Spark Fun and Maker can go a long way.
SHED (http://store.arduino.cc/ww/) in 23 Header pins You’ll use these all the Black: Jameco: 36792
the U.S., and from multiple distributors time. It’s handy to have female ones Blue: Jameco: 36767
internationally. See http://arduino.cc/en/ around as well. Jameco: 103377; Digi-Key: Green: Jameco: 36821
Main/Buy for details about your region. A26509-20-ND; Farnell: 1593411 Red: Jameco: 36856;
RadioShack: 278-1215
17 Voltage regulator Voltage regulators 24 Analog sensors (variable resistors) Yellow: Jameco: 36919
take a variable input voltage and output There are countless varieties of variable Mixed: RadioShack: 276-173
a constant (lower) voltage. The two most resistors to measure all kinds of physical
common you’ll need for these projects properties. They’re the simplest of 29 Capacitors You’ll need capacitors
are 5V and 3.3V. Be careful when using a analog sensors, and they’re very easy of various values for your projects.
regulator that you’ve never used before. to build into test circuits. Flex sensors Common values are listed in Table 1-1.
Check the data sheet to make sure you
have the pin connections correct.
3.3V: Digi-Key: 576-1134-ND; Jameco:
242115; Farnell: 1703357; RS: 534-3021
5V: Digi-Key: LM7805CT-ND; Jameco: 51262;
Farnell: 1703357; RS: 298-8514
! You're going to run across some hardware in the following chapters
that was brand new when this edition was written, including the
18 TIP120 Transistor Transistors act as
digital switches, allowing you to control Arduino Ethernet board, the Arduino WiFi shield, wireless shield, RFID
a circuit with high current or voltage shield, USB-to-Serial adapter, and more. The distributors listed here didn't
from one with lower current and voltage. have part numbers for them as of this writing, so check for them by name.
There are many types of transistors, the
By the time you read this, distributors should have them in stock.
TIP120 is one used in a few projects in
this book. Note that the TIP120 looks
just like the voltage regulator next to
it. Sometimes electronic components
with different functions come in the
same physical packages, so you need to
check the part number written on the
part. Digi-Key: TIP120-ND; Jameco: 32993;
Farnell: 9804005
8 MAKING THINGS TALK
RESISTORS LED
100Ω D 100QBK-ND, J 690620, F 9337660, T1, Green clear D 160-1144-ND, J 34761, F 1057119, R 247-1662
R 707-8625 T1, Red, clear D 160-1665-ND, J 94511, F 1057129,
220Ω D 220QBK-ND, J 690700, F 9337792, R 826-830
R 707-8842
470Ω D 470QBK-ND, J 690785, F 9337911, Transistors
R 707-8659 2N2222A D P2N2222AGOS-ND, J 38236, F 1611371,
1K D 1.0KQBK, J 29663, F 1735061, R 295-028
R 707-8669 TIP120 D TIP120-ND, J 32993, F 9804005
10K D 10KQBK-ND, J 29911, F 9337687, Diodes
R 707-8906 1N4004-R D 1N4004-E3, J 35992, F 9556109,
22K D 22KQBK-ND, J 30453, F 9337814, R 628-9029
R 707-8729 3.3V zener (1N5226) D 1N5226B-TPCT-ND, J 743488, F 1700785
100K D 100KQBK-ND, J 29997, F 9337695,
R 707-8940 Pushbuttons
1M D 1.0MQBK-ND, J 29698, F 9337709, PCB D SW400-ND, j 119011, F 1555981
R 131-700 Panel Mount D GH1344-ND, j 164559PS, F 1634684,
R 718-2213
CAPACITORS
0.1µF ceramic D 399-4151-ND, J 15270, F 3322166, Solderless Breadboards
R 716-7135 various D 438-1045-ND, j 20723, 20600, F 4692810
1µF electrolytic D P10312-ND, J 94161, F 8126933,
R 475-9009 Hookup Wire
10µF electrolytic D P11212-ND, J 29891, F 1144605, red D C2117R-100-ND, j 36856, F 1662031
R 715-1638 black D C2117B-100-ND, j 36792, F 1662027
100µF electrolytic D P10269-ND, J 158394, F 1144642, blue j 36767, F 1662034
R 715-1657 yellow J 36920, F 1662032
Battery Snap
9V D 2238K-ND, J 101470PS, S PRT-00091
THE TOOLS 9
Figure 1-2
The Processing editor window.
Software Tools
Processing
The multimedia programming environment used in this Processing programs. It runs on Mac OS X, Windows,
book is called Processing. Based on Java, it's made for and Linux, so you can run Processing on your favorite
designers, artists, and others whowant to get something operating system. There's also Processing for Android
done without having to know all the gory details of pro- phones and Processing for JavaScript, so you can use
gramming. It’s a useful tool for explaining programming it in many ways. If you don’t like working in Processing,
ideas because it takes relatively little Processing code to you should be able to use this book's code samples and
make big things happen, such as opening a network con- comments as pseudocode for whatever multimedia envi-
nection, connecting to an external device through a serial ronment you prefer. Once you’ve downloaded and installed
port, or controlling a camera. It’s a free, open source tool Processing on your computer, open the application. You’ll
available at www.processing.org. Because it’s based on get a screen that looks like Figure 1-2.
Java, you can include Java classes and methods in your
It’s not too flashy a program, but it’s a classic. It get in your way. The toolbar has buttons to run and stop
should print Hello World! in the message box at a sketch, create a new file, open an existing sketch, save
the bottom of the editor window. It’s that easy. the current sketch, or export to a Java applet. You can also
export your sketch as a standalone application from the
Programs in Processing are called sketches, and all the File menu. Files are normally stored in a subdirectory of
data for a sketch is saved in a folder with the sketch’s your Documents folder called Processing, but you can save
name. The editor is very basic, without a lot of clutter to them wherever you like.
10 MAKING THINGS TALK
*/
NOTE: All code examples in this book
will have comments indicating the // declare your variables:
context in which they're to be used: float redValue = 0; // variable to hold the red color
Processing, Processing Android mode, float greenValue = 0; // variable to hold the green color
Arduino, PHP, and so forth. float blueValue = 0; // variable to hold the blue color
void setup() {
size(320, 240); // sets the size of the applet window
background(0); // sets the background of the window to black
fill(0); // sets the color to fill shapes with (0 = black)
smooth(); // draw with antialiased edges
}
void draw() {
Every Processing program has two main routines, setup() (integers), booleans (true or false values), Strings of text,
and draw(). setup() happens once at the beginning of the and bytes.
program. It’s where you set all your initial conditions, like
the size of the applet window, initial states for variables, Like C, Java, and many other languages, Processing uses
and so forth. draw() is the main loop of the program. It C-style syntax. All functions have a data type, just like
repeats continuously until you close the applet window. variables (and many of them are the void type, meaning
that they don’t return any values). All lines end with a
In order to use variables in Processing, you have to declare semicolon, and all blocks of code are wrapped in curly
the variable’s data type. In the preceding program, the braces. Conditional statements (if-then statements),
variables redValue, greenValue, and blueValue are all for-next loops, and comments all use the C syntax as
float types, meaning that they’re floating decimal-point well. The preceding code illustrates all of these except the
numbers. Other common variable types you’ll use are ints for-next loop.
8 Here’s a typical for-next loop. for (int myCounter = 0; myCounter <=10; myCounter++) {
Try this in a sketch of its own (to println(myCounter);
start a new sketch, select New from }
Processing’s File menu).
BASIC users: If you’ve never used a C-style for-next loop, it can seem forbidding. What this bit
of code does is establish a variable called myCounter. As long as a number is less than or equal
to 10, it executes the instructions in the curly braces. myCounter++ tells the program to add
one to myCounter each time through the loop. The equivalent BASIC code is:
for myCounter = 0 to 10
Print myCounter
next
Windows
On Windows, you’ll need to start up PuTTY (see Figure
1-3). To get started, type myhost.com (your web
host’s name) in the Host Name field, choose the SSH
protocol, and then click Open.
NOTE: You should check with your web host to learn how the files To return to your home directory, use the ~ symbol, which
and directories in your home directory are set up. is shorthand for your home directory:
To find out what files are in a given directory, use the list cd ~
(ls) command, like so:
If you type cd on a line by itself, it also takes you to your
ls –l . home directory.
NOTE: The dot is shorthand for “the current working directory.” If you want to go into a subdirectory of a directory,
Similarly, a double dot is shorthand for the directory (the parent for example the cgi-bin directory inside the public_html
directory) that contains the current directory. directory, you’d type cd public_html/cgi-bin. You can type
the absolute path from the main directory of the server
The -l means “list long.” You’ll get a response like this: (called the root) by placing a / at the beginning of the file’s
pathname. Any other file pathname is called a relative path.
total 44
drwxr-xr-x 13 igoe users 4096 Apr 14 11:42 public_html To make a new directory, type:
drwxr-xr-x 3 igoe users 4096 Nov 25 2005 share
mkdir directoryname
14 MAKING THINGS TALK
This command will make a new directory in the current chmod go +wx filename
working directory. If you then use ls -l to see a list of files
in the working directory, you’ll see a new line with the new A combination of u for user, g for group, and o for others,
directory. If you then type cd directoryname to switch to and a combination of + and - and r for read, w for write,
the new directory and ls -la to see all of its contents, you’ll and x for execute gives you the capability to change
see only two listings: permissions on your files for anyone on the system. Be
careful not to accidentally remove permissions from
drwxr-xr-x 2 tqi6023 users 4096 Feb 17 10:19 . yourself (the user). Also, get in the habit of not leaving files
drwxr-xr-x 4 tqi6023 users 4096 Feb 17 10:19 .. accessible to the group and others unless you need to—
on large hosting providers, it’s not unusual for you to be
The first file, . , is a reference to this directory itself. The sharing a server with hundreds of other users!
second, .. , is a reference to the directory that contains it.
Those two references will exist as long as the directory
exists. You can’t change them. Creating, Viewing, and Deleting Files
Two other command-line programs you’ll find useful are
To remove a directory, type: nano and less. nano is a text editor. It’s very bare-bones,
so you may prefer to edit your files using your favorite
rmdir directoryname text editor on your own computer and then upload them
to your server. But for quick changes right on the server,
You can remove only empty directories, so make sure that nano is great. To make a new file, type:
you’ve deleted all the files in a directory before you remove
it. rmdir won’t ask you if you’re sure before it deletes your nano filename.txt
directory, so be careful. Don’t remove any directories or
files that you didn’t make yourself. The nano editor will open up. Figure 1-4 shows how it looks
like after I typed in some text.
Controlling Access to Files All the commands to work in nano are keyboard
Type ls –l to get a list of files in your current directory commands you type using the Ctrl key. For example, to
and to take a closer look at the permissions on the files. exit the program, type Ctrl-X. The editor will then ask
For example, a file marked drwx------ means that it’s a whether you want to save, and prompt you for a filename.
directory, and that it’s readable, writable, and executable The most common commands are listed along the bottom
by the system user who created the directory (also known of the screen.
as the owner of the file). Or, consider a file marked -rw-rw-
rw. The - at the beginning means it’s a regular file (not a While nano is for creating and editing files, less is for
directory) and that the owner, the group of users to which reading them. less takes any file and displays it to the
the file belongs (usually, the owner is a member of this screen one screenful at a time. To see the file you just
group), and everyone else who accesses the system can created in nano, for example, type:
read and write to this file. The first rw- refers to the owner,
the second refers to the group, and the third refers to less filename.txt
the rest of the world. If you're the owner of a file, you can
change its permissions using the chmod command: You’ll get a list of the file's contents, with a colon (:)
prompt at the bottom of the screen. Press the space bar
chmod go–w filename for the next screenful. When you’ve read enough, type q to
quit. There’s not much to less, but it’s a handy way to read
The options following chmod refer to which users you want long files. You can even send other commands through
to affect. In the preceding example, you’re removing write less (or almost any command-line program) using the pipe
permission (-w) for the group (g) that the file belongs (|) operator. For example, try this:
to, and for all others (o) besides the owner of the file. To
restore write permissions for the group and others, and to ls –la . | less
also give them execute permission, you’d type:
THE TOOLS 15
Figure 1-4
The nano text editor.
Once you’ve created a file, you can delete it using the rm To get started with PHP, you’ll need to make a remote
command, like this: connection to your web hosting account using ssh as you
did in the last section. Some of the more basic web hosts
rm filename don’t allow ssh connections, so check to see whether
yours does (and if not, look around for an inexpensive
Like rmdir, rm won’t ask whether you’re sure before it hosting company that does; it will be well worth it for the
deletes your file, so use it carefully. flexibility of working from the command line). Once you’re
connected, type:
There are many other commands available in the Unix
command shell, but these will suffice to get you started. php -v
For more information, type help at the command prompt
to get a list of commonly used commands. For any You should get a reply like this:
command, you can get its user manual by typing man
commandname. When you’re ready to close the con- PHP 5.3.4 (cli) (built: Dec 15 2010 12:15:07)
nection to your server, type: logout. For more on getting Copyright (c) 1997-2010 The PHP Group
around Unix and Linux systems using the command line, Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend
see Learning the Unix Operating System by Jerry Peek, Technologies
Grace Todino-Gonguet, and John Strang (O'Reilly).
This tells what version of PHP is installed on your server.
The code in this book was written using PHP5, so as long
PHP as you’re running that version or later, you’ll be fine. PHP
The server programs in this book are mostly in PHP. PHP makes it easy to write web pages that can display results
is one of the most common scripting languages for appli- from databases, send messages to other servers, send
cations that run on the web server (server-side scripts). email, and more.
Server-side scripts are programs that allow you to do
more with a web server than just serve fixed pages of text Most of the time, you won’t be executing your PHP scripts
or HTML. They allow you to access databases through a directly from the command line. Instead, you’ll be calling
browser, save data from a web session to a text file, send the web server application on your server—most likely a
mail from a browser, and more. You’ll need a web hosting program called Apache—and asking it for a file (this is all
account with an Internet service provider for most of the accomplished simply by opening a web browser, typing
projects in this book, and it’s likely that your host already in the address of a document on your web server, and
provides access to PHP. pressing Enter—just like visiting any other web page). If
16 MAKING THINGS TALK
Figure 1-5
The results of your first PHP script,
in a browser.
the file you ask for is a PHP script, the web server applica-
tion will look for your file and execute it. It’ll then send a ! If you see the PHP source code instead of what’s
message back to you with the results. shown in Figure 1-5, you may have opened up the
PHP script as a local file (make sure your web browser’s
For more on this, see Chapter 3. For now, let’s get a location bar says http:// instead of file://).
simple PHP program or two working. Here’s your first
PHP program. Open your favorite text editor, type in the
following code, and save it on the server with the name hello.
php in your public_html directory (your web pages may be (replace example.com with your website and any addi-
stored in a different directory, such as www or web/public): tional path info needed to access your home files, such as
http://tigoe.net/~tigoe/hello.php). You should get a web
<?php page like the one shown in Figure 1-5.
echo "<html><head></head><body>\n";
echo "hello world!\n"; If it still doesn’t work, your web server may not be configured
echo "</body></html>\n"; for PHP. Another possibility is that your web server uses a
?> different extension for php scripts, such as .php4. Consult
with your web hosting provider for more information.
Now, back at the command line, type the following to see
the results: You may have noticed that the program is actually printing
out HTML text. PHP was made to be combined with HTML.
php hello.php In fact, you can even embed PHP in HTML pages, by using
the <? and ?> tags that start and end every PHP script. If
You should get the following response: you get an error when you try to open your PHP script in a
browser, ask your system administrator whether there are
<html><head></head><body> any requirements as to which directories PHP scripts need
hello world! to be in on your server, or on the file permissions for your
</body></html> PHP scripts.
Here’s a slightly more complex PHP script. Save it to your In PHP, there are three important built-in variables, called
server in the public_html directory as time.php: environment variables, with which you should be familiar:
$_REQUEST, $_GET, and $_POST. These give you the
<?php results of an HTTP request. Whether your PHP script was
/* called by a HTML form or by a user entering a URL with a
Date printer string of variables afterwards, these variables will give you
Context: PHP the results. $_GET gives you the results if the PHP script
was called using an HTTP GET request, $_POST gives the
Prints the date and time in an HTML page. results of an HTTP POST request, and $_REQUEST gives
*/ you the results regardless of what type of request was
// Get the date, and format it: made.
$date = date("Y-m-d h:i:s\t");
Since HTTP requests might contain a number of
// print the beginning of an HTML page: different pieces of information (think of all the fields
echo "<html><head></head><body>\n"; you might fill out in a typical web form), these are all
echo "hello world!<br>\n"; array variables. To get at a particular element, you can
// Include the date: generally ask for it by name. For example, if the form
echo "Today’s date: $date<br>\n"; you filled out had a field called Name, the name you
// finish the HTML: fill in would end up in the $_REQUEST variable in an
echo "</body></html>\n"; element called $_REQUEST['Name']. If the form made an
?> HTTP POST request, you could also get the name from
$_POST['Name']. There are other environment variables
To see it in action, type http://www.example.com/ you'll learn about as well, but these three are the most
time.php into your browser (replacing example.com as useful for getting information from a client—whether it's a
before). You should get the date and time. You can see web browser or a microcontroller. You'll learn more about
this program uses a variable, $date, and calls a built-in these, and see them in action, later in the book.
PHP function, date(), to fill the variable. You don’t have to
declare the types of your variables in PHP. Any simple, or For more on PHP, check out www.php.net, the main source
scalar, variable begins with a $ and can contain an integer, for PHP, where you’ll find some good tutorials on how to
a floating-point number, or a string. PHP uses the same use it. You can also read Learning PHP 5 by David Sklar
C-style syntax as Processing, so you’ll see that if-then (O'Reilly) for a more in-depth treatment.
statements, repeat loops, and comments all look familiar.
Mac OS X serial communication This command will give you a list of available serial ports.
To get started, open CoolTerm and click the Options icon. The names of the serial ports in Mac OS X and Linux are
In the Options tab, you'll see a pulldown menu for the port. more unique, but they're more cryptic than the COM1,
In Mac OS X, the port names are similar to this: /dev/tty. COM2, and so on that Windows uses. Pick your serial port
usbmodem241241. To find your port for sure, check the and type:
list when your Arduino is unplugged, then plug it in and
click Re-scan Serial Ports in the Options tab. The new screen portname datarate.
port listed is your Arduino's serial connection. To open the
serial port, click the Connect button in the main menu. To
disconnect, click Disconnect.
THE TOOLS 19
Figure 1-6
Configuring a serial connection in PuTTY.
20 MAKING THINGS TALK
For example, to open the serial port on an Arduino board microcontroller family, Atmel's ATmega series (www.
(discussed shortly) at 9600 bits per second, you might atmel.com), and they're both programmed in C/C++.
type screen /dev/tty.usbmodem241241 9600 on Mac OS The "dialect" they speak is based on Processing, as is the
X. On Linux, the command might be screen /dev/ttyUSB0 software integrated development environments (IDEs)
9600. The screen will be cleared, and any characters you they use. You'll see that some Processing commands
type will be sent out the serial port you opened. They won’t have made their way into Arduino and Wiring, such as the
show up on the screen, however. Any bytes received in the setup() and loop() methods (Processing's draw() method
serial port will be displayed in the window as characters. To was originally called loop()), the map() function, and more.
close the serial port, type Ctrl-A followed by Ctrl-\.
When this book was first written, there was one Wiring
In the next section, you’ll use a serial communications board, four or five variants of Arduino, and almost no deriv-
program to communicate with a microcontroller. atives. Now, there are several Arduino models, two new
Wiring models coming out shortly, and scores of Arduino-
compatible derivatives, most of which are compatible
Hardware enough that you can program them directly from the
Arduino IDE. Others have their own IDEs and will work with
Arduino, Wiring, and Derivatives some (but not all) of the code in this book. Still others are
The main microcontroller used in this book is the Arduino compatible in their physical design but are programmed
module. Arduino and Wiring, another microcontroller with other languages. The derivatives cover a wide range
module, both came out of the Institute for Interaction of applications.
Design in Ivrea, Italy, in 2005. They're based on the same
Figure 1-7
The CoolTerm serial terminal program.
THE TOOLS 21
The following projects have been tested extensively on as it’s much quicker (and more reliable, for most people).
Arduino boards and, when possible, on the classic Wiring Figure 1-8 shows some of your options.
board. Though you'll find some differences, code written
for a Wiring board should work on an Arduino board, One of the best things about Wiring and Arduino is that
and vice versa. For Arduino derivatives, check with the they are cross-platform; they work well on Mac OS X,
manufacturer of your individual board. Many of them are Windows, and Linux. This is a rarity in microcontroller
very active in the Arduino forums and are happy to lend development environments.
support.
Another good thing about these environments is that, like
You’ll find that the editors for Arudino and Wiring look very Processing, they can be extended. Just as you can include
similar. These free and open source programming environ- Java classes and methods in your Processing programs,
ments are available through their respective websites: you can include C/C++ code, written in AVR-C, in your
www.arduino.cc and www.wiring.org.co. Wiring and Arduino programs. For more on how to do this,
visit their respective websites.
The hardware for both is also open source, and you can
buy it from various online retailers, listed on the sites For an excellent introduction to Arduino, see Massimo
above. Or, if you’re a hardcore hardware geek and like to Banzi’s book Getting Started with Arduino (O’Reilly).
make your own printed circuit boards, you can download X
the plans to do so. I recommend purchasing them online,
2 3 4
1 5
7 8 9
10 11 12 13
Figure 1-8. Varieties of Arduino, as well as a Wiring board: 1. LilyPad Arduino 2. Arduino Uno SMD 3. Arduino Fio 4. Arduino
Pro Mini 5. Arduino Mini 6. Arduino Nano 7. Arduino Mega 2560 8. Arduino Uno 9. Wiring board 10. Arduino Pro 11. Arduino
Ethernet 12. Arduino Bluetooth 13. Arduino Duemilanove.
22 MAKING THINGS TALK
2 3 4
8 6
9
Figure 1-9. A sampling of shields for Arduino: 1. Arduino prototyping shield 2. Adafruit prototyp-
ing shield 3. Arduino Ethernet shield 4. TinkerKit DMX shield 5. Arduino wireless shield
6. Oomlout Arduino/breadboard mount, manufactured by Adafruit 7. Spark Fun microSD card
shield 8. Adafruit motor driver shield 9. Spark Fun musical instrument shield.
Arduino Shields
One of the features that makes Arduino easy to work with same footprint; and some prototyping shields, which make it
are the add-on modules called shields, which allow you to easy to design a custom circuit for your project.
add preassembled circuits to the main module. For most
applications you can think of, there's a third-party company The shield footprint, like the board designs, is available
or individual making a shield to do it. Need a MIDI synthe- online at www.arduino.cc. If you've got experience making
sizer? There's a shield for that. Need NTSC video output? printed circuit boards, try your hand at making your own
There's a shield for that. Need WiFi or Ethernet? There's a shield—it's fun.
shield for that, and you'll be using them extensively in this
book. Until recently, shields for Arduino weren't physically com-
patible with Wiring boards. However, Rogue Robotics (www.
The growth of shields has been a major factor in the spread roguerobotics.com) just started selling an adapter for the
of Arduino, and the well-designed and documented ones Wiring board that allows it to take shields for Arduino.
make it possible to build many projects with no electronic
experience whatsoever. You'll be using some shields in this Beware! Not every shield is compatible with every board.
book, and for other projects, building the actual circuit Some derivative boards do not operate on the same voltage
yourself. as the Arduino boards, so they may not be compatible with
shields designed to operate at 5 volts. If you're using a
The shields you'll see most commonly in this book are the different microcontroller board, check with the manufac-
Ethernet shield, which gives you the ability to connect your turer of your board to be sure it works with your shields.
controller to the Internet; the wireless shield, which lets you X
interface with Digi's XBee radios and other radios with the
THE TOOLS 23
Other Microcontrollers
Though the examples in this book focus on Arduino, of the Basic Stamps and PICAXEs. The Basic Stamp,
there are many other microcontroller platforms that PICAXE, Wiring, and Arduino environments are essen-
you can use to do the same work. Despite differences tially wrappers around these controllers, making them
among the platforms, there are some principles that easier to work with. To use PICs or AVRs on their own,
apply to them all. They're basically small computers. you need a hardware programmer that connects to your
They communicate with the world by turning on or off computer, and you need to install a programming envi-
the voltage on their output pins, or reading voltage ronment and a compiler.
changes on their input pins. Most microcontrollers can
read variable voltage changes on a subset of their I/O Though the microcontrollers themselves are cheap
pins. All microcontrollers can communicate with other (between $1 and $10 apiece), getting all the tools set
computers using one or more forms of digital communi- up for yourself can cost you some money. There’s also
cation. Listed below are a few other microcontrollers on a pretty significant time investment in getting set up,
the market today. as the tools for programming these controllers from
scratch assume a level of technical knowledge—both
8-bit controllers in software and hardware—that's higher than the other
The Atmel microcontrollers that are at the heart of both tools listed here.
Arduino and Wiring are 8-bit controllers, meaning that
they can process data and instructions in 8-bit chunks. 32-bit controllers
8-bit controllers are cheap and ubiquitous, and they can Your personal computer is likely using a 64-bit processor,
sense and control things in the physical world very effec- and your mobile phone is likely using a 32-bit processor.
tively. They can sense simple physical characteristics at These processors are capable of more complex tasks,
a resolution and speed that exceeds our senses. They such as multitasking and media control and playback.
show up in nearly every electronic device in your life,
from your clock radio to your car to your refrigerator. Initially, 32-bit processors were neither affordable nor
easy to program, but that has been changing rapidly in
There are many other 8-bit controllers that are great for the last couple of years, and there are now several 32-bit
building physical devices. Parallax (www.parallax.com) microcontroller platforms on the market. Texas Instru-
Basic Stamp and Basic Stamp 2 (BS-2) are probably ments' BeagleBoard (http://beagleboard.org) is a 32-bit
the most common microcontrollers in the hobbyist processor board with almost everything you need to
market. They are easy to use and include the same basic make a basic personal computer: HDMI video out, USB,
functions as Wiring and Arduino. However, the language SD card and connections for mass storage devices, and
they're programmed in, PBASIC, lacks the ability to pass more. It can run a minimal version of the Linux operating
parameters to functions, which makes programming system. Netduino (www.netduino.com) is a 32-bit
many of the examples shown in this book more difficult. processor designed to take Arduino shields, but it's pro-
Revolution Education's PICAXE environment (www. grammed using an open source version of Microsoft's
rev-ed.co.uk) is very similar to the PBASIC of the Basic .NET programming framework. LeafLabs' Maple (http://
Stamp, but it's a less expensive way to get started than leaflabs.com) is another 32-bit processor that uses the
the Basic Stamp. Both the PICAXE and the Stamp are same footprint as the Arduino Uno, and is programmed
capable of doing the things shown in this book, but their in C/C++ like the Arduino and Wiring boards. In addition
limited programming language makes the doing a bit to these, there are several others coming on the market
more tedious. in the near future.
changes and control outputs at resolutions that exceed These possibilities are just beginning to be realized and
human perception. However, complex-sensing features— will easily fill another book, or several. However, basic
such as gesture recognition, multitasking, simpler sensing and networked communications are still well
memory management, and the ability to interface within the capabilities of 8-bit controllers, so I've chosen
with devices using the same methods and libraries as to keep the focus of this book on them.
personal computers—will make a big difference. 32-bit
processors give physical interface makers the ability to
use or convert code libraries and frameworks developed
on servers and personal computers. There is where the
real excitement of these processors lies.
Transmit
Receive
Pins 0, 1:
Most microcontrollers have the Serial
same or similar parts: power
connections, digital and analog MADE
I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
inputs, and serial communications.
DIGITAL (PWM ~)
-
L
USB TX
+ UNO ON
Reset button
RX ARDUINO
RESET-EN
5V Voltage RESET ICSP
W W W. ARD U I NO. CC
regulator
Microcontroller
9-15V DC POWER ANALOG IN
RESET
voltage input
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
Pins A0 - A5:
Voltage Analog inputs
Reset outputs (can also function
(connect to ground as digital I/O)
to reset) Ground
Connected directly
to 9-15V DC
voltage input
Figure 1-11
Toolbars for Arduino version 0022, Arduino 1.0, and Wiring then open the Device Manager. Under Ports (COM & LPT),
1.0. you should see a port named Arduino UNO (COMxx).
Right-click on this port and choose the Update Driver
Software option. Click the "Browse my computer for Driver
software" option. Finally, navigate to and select the Uno's
Once you're installed, open the Arduino application and driver file, named ArduinoUNO.inf, located in the drivers
you're ready to go. directory. Windows will finish up the driver installation
from there.
Setup on Windows 7
Unzip the downloaded file. It can go anywhere on your Setup on Linux
system. The Program Files directory is a good place. Next, Arduino for Linux depends on the flavor of Linux you're
you'll need to install drivers, whether you have an Arduino using. See www.arduino.cc/playground/Learning/Linux
Uno board or an older board, or a Wiring board. for details on several Linux variants. For Ubuntu users, it's
available from the Ubuntu Software Update tool.
Plug in your Arduino and wait for Windows to begin its
driver installation process. If it's a Duemilanove or earlier, Now you’re ready to launch Arduino. Connect the module
it will need the FTDI drivers. These should install automati- to your USB port and double-click the Arduino icon to
cally over the Internet when you plug your Duemilanove launch the software. The editor looks like Figure 1-12.
in; if not, there is a copy in the drivers directory of the
Arduino application directory. If it's an Uno or newer, click The environment is based on Processing and has New,
on the Start Menu and open up the Control Panel. Open Open, and Save buttons on the main toolbar. In Arduino
the "System and Security" tab. Next, click on System, and Wiring, the Run function is called Verify, and there is
THE TOOLS 27
Figure 1-12
The Arduino programming environment.
The Wiring environment looks similar,
except the color is different.
Figure 1-13
LED connected to pin 13 of an
Arduino board. Add 220-ohm cur-
rent-limiting resistor in series with
this if you plan to run it for more
than a few minutes.
28 MAKING THINGS TALK
Try It /* Blink
Context: Arduino
Here’s your first program.
Blinks an LED attached to pin 13 every half second.
Connections:
Pin 13: + leg of an LED (- leg goes to ground)
*/
void setup() {
pinMode(LEDPin, OUTPUT); // set pin 13 to be an output
}
void loop() {
digitalWrite(LEDPin, HIGH); // turn the LED on pin 13 on
delay(500); // wait half a second
digitalWrite(LEDPin, LOW); // turn the LED off
delay(500); // wait half a second
}
In order to see this run, you’ll need to connect an Binary sketch size: 1010 bytes (of a 32256 byte maximum)
LED from pin 13 of the board to ground (GND),
as shown in Figure 1-13. The positive (long) end Once the sketch is uploaded, the LED you wired to the
of the LED should go to 13, and the short end to ground. output pin will begin to blink. That’s the microcontroller
equivalent of “Hello World!”
Then type the code into the editor. Click on Tools→Board
to choose your Arduino model, and then Tools→Serial NOTE: If it doesn't work, you might want to seek out some external
Port to choose the serial port of the Arduino module. On help. The Arduino Learning section has many tutorials (www.arduino.
the Mac or Linux, the serial port will have a name like this: cc/en/Tutorial). The Arduino (www.arduino.cc/forum) and Wiring
/dev/tty.usbmodem241241. If it's an older board or a (http://forum.wiring.co) forums are full of helpful people who love
Wiring board, it will be more like this: /dev/tty.usbserial- to hack these sort of things.
1B1 (the letters and numbers after the dash will be slightly
different each time you connect it). On Windows, it should Serial communication
be COMx, where x is some number (for example, COM5). One of the most frequent tasks you’ll use a microcontroller
for in this book is to communicate serially with another
NOTE: On Windows, COM1–COM4 are generally reserved for device, either to send sensor readings over a network or
built-in serial ports, regardless of whether your computer has to receive commands to control motors, lights, or other
them. outputs from the microcontroller. Regardless of what
device you’re communicating with, the commands you’ll
Once you’ve selected the port and model, click Verify use in your microcontroller program will be the same. First,
to compile your code. When it’s compiled, you’ll get you’ll configure the serial connection for the right data
a message at the bottom of the window saying Done rate. Then, you’ll read bytes in, write bytes out, or both,
compiling. Then click Upload. This will take a few depending on what device you’re talking to and how the
seconds. Once it’s done, you’ll get a message saying conversation is structured.
Done uploading, and a confirmation message in the serial
monitor window that says:
THE TOOLS 29
Try It /*
Simple Serial
This next Arduino program listens for Context: Arduino
incoming serial data. It adds one to Listens for an incoming serial byte, adds one to the byte
whatever serial value it receives, and and sends the result back out serially.
then sends the result back out. It also Also blinks an LED on pin 13 every half second.
blinks an LED on pin regularly—on the */
same pin as the last example—to let
you know that it’s still working. int LEDPin = 13; // you can use any digital I/O pin you want
int inByte = 0; // variable to hold incoming serial data
long blinkTimer = 0; // keeps track of how long since the LED
// was last turned off
int blinkInterval = 1000; // a full second from on to off to on again
void setup() {
pinMode(LEDPin, OUTPUT); // set pin 13 to be an output
Serial.begin(9600); // configure the serial port for 9600 bps
// data rate.
}
void loop() {
// if there are any incoming serial bytes available to read:
if (Serial.available() > 0) {
// then read the first available byte:
inByte = Serial.read();
»
// and add one to it, then send the result out:
30 MAKING THINGS TALK
Serial.write(inByte+1);
}
I N I TA LY
MADE
Figure 1-14
The Serial monitor in Arduino, running the
previous sketch. The user typed BCDEFGH.
AREF
RX
TX
GND
13
RESET-EN
12
RESET
Figure 1-15
ARDUINO
11
-
3.3V
10
5V
9
Arduino connected to a breadboard. +5V and
+
POWER
GND
8
GND
6
A0 5 the board. This way, all sensors and actuators can
A1 4
RESET
A2 3
share the +5V and ground connections of the board.
ANALOG IN
A3 2
A4 TX 1
Control or signal connections from each sensor
ON
A5 RX 0
ICSP
W W W. A R D U I N O. CC
or actuator run to the appropriate I/O pins. In this
example, two pushbuttons are attached to digital
D
H
G
B
A
C
E
J
F
I
1
5
5
10
10
15
15
20
20
25
25
30
30
32 MAKING THINGS TALK
D
H
G
B
A
C
E
J
F
I
that follow, but these are the staples of all the projects in To ground
1
this book.
To Microcontroller
5
Specialty circuits and modules digital input
You'll see a number of specialty circuits and modules
throughout this book, like the Bluetooth Mate and the
10
10
XBee radios. These are devices that allow you to send
serial data wirelessly. You'll also build a few of your own
circuits for specific projects. All of the circuits will be
15
15
shown on a breadboard like these, but you can build them
any way you like. If you're familiar with working on printed
circuit boards and prefer to build your circuits that way,
20
20
feel free to do so.
X
25
25
30
30
! You will encounter variations on many of the
Input voltage
modules and components used in this book. For
example, the Arduino module has several variations, as
shown in Figure 1-8. The FTDI USB-to-Serial module used in
later chapters has at least three variations. Even the voltage
regulators used in this book have variations. Be sure to To microcontroller
check the data sheet on whatever component or module digital input
Figure 1-16
Digital input to a microcontroller.
Top: breadboard view.
Bottom: schematic view.
THE TOOLS 33
To +V To +V
D
H
G
B
A
H
G
B
A
C
C
E
E
J
F
I
I
To ground To ground
1
1
1
To Microcontroller
5
5
5
analog input
10
10
10
10
To Microcontroller
analog input
15
15
15
15
20
20
20
20
25
25
25
25
30
30
30
30
Input voltage
Input voltage
Variable resistor
(photocell, flex
To microcontroller
sensor, etc.)
To microcontroller Potentiometer analog input
analog input
Fixed resistor
Using an Oscilloscope
Most of what you'll be building in this book involves
computer circuits that read a changing voltage over time.
Whether your microcontroller is reading a digital or analog
input, controlling the speed of a motor, or sending data to
a personal computer, it's either reading a voltage or gener-
ating a voltage that changes over time. The time intervals
it works in are much faster than yours. For example, the
serial communication you just saw involved an electrical
pulse changing at about 10,000 times per second. You
can't see anything that fast on a multimeter. This is when
an oscilloscope is useful.
Even if you’re building it only for yourself, you don’t want By including the person’s behavior in your system planning,
to have to fix it all the time. All that matters to the person you solve some problems that are computationally difficult
using your system are the parts that she can see, hear, but easy for human intelligence. Ultimately, the best reason
and touch. All the inner details are irrelevant if the physical to make things talk to each other is to give people more
interface doesn’t work. So don’t spend all of your time reasons to talk to each other.
focusing on the communication between devices and X
leave out the communication with people. In fact, it’s best
to think about the specifics of what the person does and
sees first.
Find your own solution, but make sure you give some
physical indication as to the invisible activities of your
objects.
Figure 2-1. New parts for this chapter: 1. Project box 2. Bluetooth Mate 3. RGB LED 4. Pushbuttons 5. Flex sensors 6. Prototyping
shield, 7. 9V battery snap connector and female power plug. Don't forget plenty of male header pins for the breakout boards.
THE SIMPLEST NETWORK 39
Figure 2-2
FTDI USB-to-TTL cable. This cable comes in handy for connecting
to all sorts of serial devices. When plugged into a USB port, it can
even provide power for the device with which it's communicat-
ing. The adapter boards shown here also act as USB-to-Serial
adapters and can replace this cable. L to R: Arduino USB-to-Serial;
Spark Fun FTDI Basic Breakout; Adafruit FTDI Friend. They require
an additional USB-A-to-Mini-B cable (the kind that comes with
most digital cameras), but have built-in LEDs attached to the
transmit and receive lines. These LEDs flash when data's going
through those lines, and they can be handy for troubleshooting
serial problems.
The Arduino adapter, unlike the others, does not use the FTDI
drivers. On Mac OS X and Linux, it needs no drivers. On Windows,
it uses the same INF file as the Arduino Uno. Photos courtesy of
Spark Fun and Adafruit.
40 MAKING THINGS TALK
Layers of Agreement
Before you can get things to talk to each other, you have to lay some ground rules for
the communication between them. These agreements can be broken down into five
layers, each of which builds on the previous ones:
Ground Ground
Chip Select CS
5V
Clock pulses
0V
Figure 2-4
Physical connections: USB,
RS-232 serial.
9 8 7 6
2 1
1 2 3 4
3 4 5 4 3 2 1
First, there’s the protocol that the microcontroller speaks, • Electrical layer
called TTL serial: The signal on Data – is always the polar opposite of what’s
on Data+, so the sum of their voltages is always zero.
• Physical layer Because of this, a receiver can check for electrical errors
What pins is the controller using to communicate? The by adding the two data voltages together. If the sum isn’t
Arduino module receives data on digital I/O pin 0, and zero, the receiver can disregard the signal at that point.
sends it out on pin 1.
• Logical layer
• Electrical layer A +5-volt signal (on Data+) or -5-volt signal (on Data-)
It uses pulses of 5 volts or 0 volts to represent bits. Some represents the value 1, and a 0-volt signal represents the
microcontrollers use 3.3 volts instead of 5 volts. value 0.
Second, there's USB, the Universal Serial Bus protocol. All that control is transparent to you because the computer’s
It differs from TTL serial in many ways: USB controller only passes you the bytes you need. The
USB-to-Serial chip on your Arduino board presents itself
• Physical layer to the operating system as a serial port, and it sends data
USB sends data on two wires, Data+ and Data-. Every through the USB connection at the rate you choose (9600
USB connector also has a 5-volt power supply line and a bits per second in the example in Chapter 1).
ground line.
THE SIMPLEST NETWORK 43
If your microcontroller speaks USB, or if you’ve got a USB- FTDI makes a USB-to-TTL-Serial cable with a breadboard
to-Serial adapter for it, you can just plug it in and it will show connector that's handy for interfacing to TTL serial devices.
up in the operating system as another serial port. It's available from the Maker SHED, Spark Fun, Adafruit, and
many other vendors. It comes in 5-volt and 3.3-volt versions.
For example, if you plug three Arduino modules into the Arduino, Spark Fun, and Adafruit all make breakout boards
same computer through a USB hub, you’ll get three new with the same cable pin connections. Spark Fun's FTDI Basic
serial ports, named something like this on Mac OS X: Board has LEDs that flash when data is being transmitted.
Adafruit's version is called the FTDI Friend. The Arduino
/dev/tty.usbmodem241441 USB-to-Serial adapter is based on a different chip but has
/dev/tty.usbmodem241461 the same pin connections. Any of these can be used for
/dev/tty.usbmodem241471 USB-to-Serial connections throughout this book. You can
see them all at the beginning of this chapter. The pin con-
nections are shown in Figure 2-6.
One more protocol: if you use a BASIC Stamp or another • Data layer
microcontroller with a non-USB serial interface, you This is the same as TTL—8 bits per byte with a start and
probably have a 9-pin serial connector connecting your stop bit.
microcontroller to your PC or to a USB-to-Serial adapter.
You can see it in Figure 2-4. This connector, called a DB-9 So why is it possible to connect some microcontrollers,
or D-sub-9, is a standard connector for another serial like the BASIC Stamp or the BX-24, directly to RS-232
protocol, RS-232. RS-232 was the main serial protocol for serial ports? It is because the voltage levels of TTL serial,
computer serial connections before USB, and it’s still seen 0 to 5 volts, are just barely enough to register in the higher
on some older computer peripheral devices: RS-232 levels, and because you can invert the bits when
sending or receiving from the microcontroller. RS-232
• Physical layer doesn’t carry any of the addressing overhead of USB,
A computer with an RS-232 serial port receives data on so it’s an easier protocol to deal with. Unfortunately, it’s
pin 2, and sends it out on pin 3. Pin 5 is the ground pin. mostly obsolete, so USB-to-Serial converters are increas-
ingly common tools for microcontroller programmers.
• Electrical layer Because the Arduino boards have an integrated USB-to-
RS-232 sends data at two levels: 5 to 12 volts, and –5 to Serial converter, you can just plug them into a
–12 volts. USB port.
• Logical layer When you’re lucky, you never have to think about this kind
A 5- to 12- volt signal represents the value 0, and a –5 to of protocol mixing, and you can just use converters to do
–12 volt signal represents the value 1. This is inverted logic. the job for you. You’re not always lucky, though, so it’s
worth knowing a little about what’s happening behind the
44 MAKING THINGS TALK
TTL Rx
to get any 3.3- to 5-volt TTL
TTL Tx
Gnd
CTS
+5V
RTS
device to talk to a personal
computer with an RS-232 serial
port. This will also work for the
0.1µF MAX232.
C1+ Vcc
V+ Gnd
0.1µF
C1- T1Out
C2+ R1In
DB-9 0.1µF
Serial connector C2- R1Out
0.1µF
5
V- T1In
6 4 RS-232 Rx
T2in TTL Tx
T2out
7 3 RS-232 Tx R2out TTL Rx
R2in
8
2
9
1
MAX3232
B
A
C
E
J
F
I
10
serial output, and if you power it from 5V, you get 5V TTL
serial output. Figure 2-5 shows the typical schematic for a
15
15
MAX3232.
MAX232
DB-9
Serial
Connector
If you’ve done a lot of serial projects, you may know the
20
20
25
6 DSR
GND Maxim made them or not. The MAX232 worked only at
4 DTR TX
5 volts, but the MAX 3232 works at 3.3 to 5 volts. Because
RX 3.3 volts is beginning to replace 5 volts as a standard supply
30
30
Figure 2-6
FTDI USB-to-TTL cable. In addition to the transmit, receive,
voltage, and ground connections, it also has connections for
hardware flow control, labeled Request to Send (RTS) and Clear
to Send (CTS). Some devices use this to manage the flow of serial
data.
FTDI
USB-to-TTL Serial Cable
To microcontroller TX RX Yellow
Request-to-send RTS Green
Project 1
Type Brighter
For this project, you'll make a tiny colored lamp. You'll
In this example, you’ll control the be able to control the brightness and color of the lamp
by sending it commands from your computer. The
output of a microcontroller with key-
RGB LED at the heart of the lamp is actually three
strokes from your computer. It's a very LEDs in one package: one red, one green, and one blue.
simple example with minimal parts, so They share a common cathode, or negative terminal.
Connect the cathode, which is the longest leg, to the
you can focus on the communication. ground of your Arduino module, and connect the three
other legs (called the anodes, one for each color) to
pins 9, 10, and 11, as shown in Figure 2-7. Bend the
cathode leg so it will fit, but make sure it's not touching
the last leg, or it will create a short circuit.
MATERIALS
When you've got the LED on the board, drill a small
»» 1 RGB LED, common cathode hole in the pong-pong ball, slightly larger than the LED.
»» 1 Arduino microcontroller module Fit the ball over the LED, as shown in Figure 2-10. It will
»» 1 personal computer act as a nice lampshade. If the LEDs form too harsh
»» All necessary converters to communicate a spot on the ball, you can diffuse them slightly by
serially from microcontroller to computer sanding the top of the LED case.
»» 1 ping-pong ball
The Protocol
Now that you've got the circuit wired up, you need
to decide how you're going to communicate with the
microcontroller to control the LEDs. You need a com-
munications protocol. This one will be very simple:
Every application needs a communications protocol, no • To choose a color of LED to control, send the first
matter how simple it is. Even turning on a light requires letter of the color, in lower-case (r, g, b).
that both the sender and receiver agree on how to say • To set the brightness for that color, send a single
"turn on the light." digit, 0 through 9.
r5g3b7
THE SIMPLEST NETWORK 47
Figure 2-7
RGB LED attached to pins 9, 10, 11, and ground. The ground leg is
bent back so that it doesn't touch the leg connected to pin 11, which
it crosses. In theory, this LED should have a resistor on each of the
anodes to limit the current going through the LEDs. In practice,
however, I've run this for several hours without the resistor with no
damage to the Arduino or LED. When in doubt, be safe and add a
MADE 220-ohm resistor to each anode.
I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
DIGITAL (PWM ~)
-
L
TX
+ UNO ON
AREF
RX ARDUINO Reset GND
+3.3V D13
RESET-EN
+5V D12
RESET ICSP
W W W.ARDUI NO.CC
Gnd D11/PWM
Gnd D10/PWM
Vin D9/PWM
POWER ANALOG IN
D8
RESET
A0
A1
A2
A3
A4
A5
3.3V
GND
GND
Vin
5V
Arduino
Module
D7
D6/PWM
Analog0 D5/PWM
That's about as simple a protocol as you could imagine.
A1 D4
However, you still need to write a program for the micro-
A2 D3/PWM
controller to read the data one byte at a time, and then
decide what to do based on the value of each byte. A3 D2
A4 Digital1/TX
The program flow is shown in Figure 2-8. A5 Digital0/RX
Check for
serial data
Try It /*
Serial RGB LED controller
Context: Arduino
8 To start, you need to set up the // constants to hold the output pin numbers:
constants to hold the pin numbers. const int greenPin = 9;
You'll also need a variable to hold the const int bluePin = 10;
number of the current pin to be faded, const int redPin = 11;
and one for the brightness.
int currentPin = 0; // current pin to be faded
int brightness = 0; // current brightness level
8 Finally, set the current pin to the if (inByte >= '0' && inByte <= '9') {
current brightness level using the // map the incoming byte value to the range of
analogWrite() command. // the analogRead() command:
brightness = map(inByte, '0', '9', 0, 255);
// set the current pin to the current brightness:
analogWrite(currentPin, brightness);
}
}
}
THE SIMPLEST NETWORK 49
r9
Then click send. You should see the ball light up red. Now
try:
Figure 2-9
r2g7 Arduino toolbar, highlighting the Serial Monitor.
The red will fade and the green will come up. Now try:
You don't have to control the lamp from the Serial Monitor.
Any program that can control the serial port can send your
protocol to the Arduino to control the lamp. Once you've
finished the next project, try writing your own lamp con-
troller in Processing.
X
Notice in the program how the characters you type are in single quotes? That's because you're using the
ASCII values for those characters. ASCII is a protocol that assigns numeric values to letters and numbers.
For example, the ASCII value for the letter 'r' is 114. The ASCII value for '0' is 48. By putting the characters
in single quotes, you're programming the Arduino to use the ASCII value for that character, not the character itself. For
example, this line:
because in ASCII, the character '0' is represented by the value 48, and the character '9' is represented by the value 57.
Using the character value in single quotes instead of the actual values isn't essential to make your program run, but it
makes it easier to read. In the first version of the line above, you're using the ASCII characters to represent the values
to map; in the second version, you're using the raw values themselves. You'll see examples in this book that use both
approaches. For more on ASCII, see "What's ASCII?" on page 54.
50 MAKING THINGS TALK
Complex Conversations
In the previous project, you controlled the microcontroller from the computer using
a very simple protocol. This time, the microcontroller will control an animation on the
computer. The communications protocol is more complex as well.
Project 2
»» 2 flex sensor resistors Connect long wires to the buttons as well, and mount
»» 2 momentary switches them in a piece of scrap foam-core or cardboard until
»» 4 10-kilohm resistors you’ve decided on a final housing for the electronics. Label
»» 1 solderless breadboard the buttons “Reset” and “Serve.” Wire the sensors to the
»» 1 Arduino microcontroller module microcontroller, as shown in Figure 2-12.
»» 1 personal computer
»» All necessary converters to communicate
serially from microcontroller to computer
»» 1 small pink monkey Output – 4 values:
– x coordinate, 10 bits
– y coordinate, 10 bits
– button 1, 1 bit
– button 2, 1 bit
1 2
Input: Input buttons
x movement
Input: y movement
Figure 2-11
The mouse as a
data object.
THE SIMPLEST NETWORK 51
Figure 2-12
The Monski Pong circuit. Sensors are
shown here with short wires so that
the image is clear. You should attach
MADE
I N I TA LY
longer wires to your sensors, though.
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
DIGITAL (PWM ~)
-
L
1 5 10 15 20 25 30
TX
+ UNO ON
A
B
RX ARDUINO C
D
E
RESET-EN
RESET ICSP
W W W. ARDUI NO. CC
F
G
H
I
J
POWER ANALOG IN 1 5 10 15 20 25 30
RESET
A0
A1
A2
A3
A4
A5
3.3V
GND
GND
Vin
5V
AREF
To breadboard +5V +5V GND
To breadboard Ground Gnd D13
To Battery Ground Gnd D12
To Battery +9V +9V D11/PWM
D10/PWM
D9/PWM +5V
+5V D8
15KΩ flex Arduino
Module
D7 reset serve
D6/PWM
A2 D3/PWM
A3 D2
A4 Digital1/TX 10KΩ
10KΩ A5 Digital0/RX
52 MAKING THINGS TALK
284,284,1,1,
285,283,1,1, */
286,284,1,1,
289,283,1,1, const int leftSensor = 0; // analog input for the left arm
const int rightSensor = 1; // analog input for tht right arm
Just as you programmed it, each value const int resetButton = 2; // digital input for the reset button
is separated by a comma, and each set const int serveButton = 3; // digital input for the serve button
of readings is on a line by itself.
int leftValue = 0; // reading from the left arm
int rightValue = 0; // reading from the right arm
int reset = 0; // reading from the reset button
int serve = 0; // reading from the serve button
void setup() {
// configure the serial connection:
Serial.begin(9600);
// configure the digital inputs:
pinMode(resetButton, INPUT);
pinMode(serveButton, INPUT);
}
void loop() {
// read the analog sensors:
leftValue = analogRead(leftSensor);
rightValue = analogRead(rightSensor);
What’s going on? The original example uses variables (leftValue, rightValue, reset, and serve) are the
the Serial.print() command, which displays source of the mystery characters. In the third line of the
the values of the sensors as their ASCII code output, when the second sensor’s value is 65, you see the
values: this modification sends out the raw binary values character 'A' because the ASCII character 'A' has the value
using Serial.write(). The Serial Monitor and serial terminal 65. For a complete list of the ASCII values corresponding
applications assume that every byte they receive is an to each character, see www.asciitable.com.
ASCII character, so they display the ASCII characters
corresponding to the raw binary values in the second Which way should you format your sensor values: as
example. For example, the values 13 and 10 correspond raw binary or as ASCII? It depends on the capabilities of
to the ASCII return and newline characters, respec- the system that’s receiving the data, and of those that
tively. The value 44 corresponds to the ASCII comma are passing it through. When you’re writing software on
character. Those are the bytes you’re sending in between a personal computer, it’s often easier for your software
the sensor readings in the second example. The sensor to interpret raw values. However, many of the network
What’s ASCII?
ASCII is the American Symbolic Code for Information Inter- format of the message could be transmitted along with the
change. The scheme was created in 1967 by the American text. These are referred to as control characters, and they
Standards Association (now ANSI) as a means for all take up the first 32 values in the ASCII set (ASCII 0 31).
computers, regardless of their operating systems, to be All of the numbers, letters, punctuation, and control char-
able to exchange text-based messages. In ASCII, each letter, acters are covered by 128 possible values. However, ASCII
numeral, or punctuation mark in the Roman alphabet is is too limited to display non-English characters, and its few
assigned a number. Anything an end user types is converted control characters don’t offer enough control in the age of
to a string of numbers, transmitted, and then reconverted graphic user interfaces. Unicode—a more comprehensive
on the other end. In addition to letters, numbers, and punc- code that’s a superset of ASCII—has replaced ASCII as the
tuation marks, certain page-formatting characters—like the standard for text interchange, and markup languages like
linefeed and carriage return (ASCII 10 and 13, respectively)— PostScript and HTML have replaced ASCII’s page formatting,
have ASCII values. That way, not only the text of a the display but the original ASCII code still lingers on.
THE SIMPLEST NETWORK 55
protocols you’ll use in this book are ASCII-based. In If you haven't already done so, undo the changes you
addition, ASCII is readable by humans, so you may find it made on page 54 to the Sensor Reader program and make
easier to send the data as ASCII. For Monski Pong, use the sure that it’s working as it did originally. Once you’ve got
ASCII-formatted version (the first example); later in this the microcontroller sending the sensor values consistently
chapter you’ll see why it’s the right choice. to the terminal, it’s time to send them to a program where
you can use them to display a pong game. This program
needs to run on a host computer that’s connected to your
Arduino board. Processing will do this well.
*/
import processing.serial.*; // import the Processing serial library
void setup() {
size(480, 130); // set the size of the applet window
println(Serial.list()); // List all the available serial ports
// read bytes into a buffer until you get a linefeed (ASCII 10):
myPort.bufferUntil('\n');
}
void draw() {
// set the background and fill color for the applet window:
background(#044f6f);
fill(#ffffff);
// show a string in the window:
if (resultString != null) {
text(resultString, 10, height/2);
}
}
»
String inputString = myPort.readStringUntil('\n');
56 MAKING THINGS TALK
Left-arm sensor Right-arm sensor Reset button Serve button Return character,
(0–1023) (0–1023) (0 or 1) (0 or 1) linefeed character
Each section of the sequence is separated by a single the message. In this example, where there is no header,
byte whose value is ASCII 44 (a comma). You’ve just the tail performs a similar function, separating one
made another data protocol. The bytes representing message from the next.
your sensor values and the commas that separate them
are the payload, and the return and newline characters On a network, many messages like this are sent out all
are the tail. The commas are the delimiters. This data the time. Each discrete group of bytes is called a packet
protocol doesn’t have a header, but many do. and includes a header, a payload, and usually a tail. Any
given network has a maximum packet length. In this
A header is a sequence of bytes identifying what’s example, the packet length is determined by the size
to follow. It might also contain a description of the of the serial buffer on the personal computer. Process-
sequence to follow. On a network, where many possible ing can handle a buffer of a few thousand bytes, so
devices could receive the same message, the header this 16-byte packet is easy for it to handle. If you had a
might contain the address of the sender, the receiver, much longer message, you’d have to divide the message
or both. That way, any device can just read the header into several packets and reassemble them once they
to decide whether it needs to read the rest of the all arrived. In that case, the header might contain the
message. Sometimes a header is as simple as a single packet number so the receiver knows the order in which
byte of a constant value, identifying the beginning of the packets should be reassembled.
THE SIMPLEST NETWORK 57
play pong. First, add a few variables at float leftPaddle, rightPaddle; // variables for the flex sensor values
the beginning of the Processing sketch int resetButton, serveButton; // variables for the button values
before the setup() method, and change int leftPaddleX, rightPaddleX; // horizontal positions of the paddles
the setup() to set the window size and int paddleHeight = 50; // vertical dimension of the paddles
initialize some of the variables (the new int paddleWidth = 10; // horizontal dimension of the paddles
lines are shown in blue).
float leftMinimum = 120; // minimum value of the left flex sensor
float rightMinimum = 100; // minimum value of the right flex sensor
float leftMaximum = 530; // maximum value of the left flex sensor
float rightMaximum = 500; // maximum value of the right flex sensor
NOTE: The variables relating to the paddle
range in this example are floating-point void setup() {
numbers (floats), because when you divide size(640, 480); // set the size of the applet window
integers, you get integer results only. For
example, 480/400, gives 1, not 1.2, when String portName = Serial.list()[0];
both are integers. Likewise, 400/480 // open the serial port:
returns 0, not 0.8333. Using integers when myPort = new Serial(this, portName, 9600);
you’re dividing two numbers that are in the
same order of magnitude produces useless // read bytes into a buffer until you get a linefeed (ASCII 10):
results. Beware of this when using scaling myPort.bufferUntil('\n');
functions like map().
// initialize the sensor values:
leftPaddle = height/2;
rightPaddle = height/2;
resetButton = 0;
serveButton = 0;
You may not see the paddles until you flex Once you’ve set the sensors’ positions in the monkey,
the sensors. The range of your sensors will be run the Processing program again and watch the left and
different, depending on how they're physically right sensor numbers as you flex the monkey’s arms.
attached to the monkey, and how far you can flex his arms. Write down the maximum and minimum values on each
The map() function maps the sensors' ranges to the range arm. Then, fill them into the four variables, leftMinimum,
of the paddle movement, but you need to determine what leftMaximum, rightMinimum, and leftMaximum, in the
the sensors' range is. For this part, it’s important that setup() method. Once you've adjusted these variables, the
you have the sensors embedded in the monkey’s arms, paddles' movement should cover the screen height when
as you’ll be fine-tuning the system, and you want the you move the monkey's arms.
sensors in the locations where they’ll actually get used.
8 Finally, it’s time to add the ball. int ballSize = 10; // the size of the ball
The ball will move from left to right int xDirection = 1; // the ball's horizontal direction.
diagonally. When it hits the top or // left is –1, right is 1.
bottom of the screen, it will bounce off int yDirection = 1; // the ball's vertical direction.
and change vertical direction. When it // up is –1, down is 1.
reaches the left or right, it will reset to int xPos, yPos; // the ball's horizontal and vertical positions
the center. If it touches either of the
paddles, it will bounce off and change
horizontal direction. To make all that
happen, you’ll need five new variables
at the top of the program, just before
the setup() method.
8 At the end of the setup() method, // initialize the ball in the center of the screen:
you need to give the ball an initial xPos = width/2;
position in the middle of the window. yPos = height/2;
8
Now, add two methods at the end of void animateBall() {
the program, one called animateBall() // if the ball is moving left:
and another called resetBall(). You’ll if (xDirection < 0) {
call these from the draw() method // if the ball is to the left of the left paddle:
shortly. if ((xPos <= leftPaddleX)) {
// if the ball is in between the top and bottom
// of the left paddle:
if((leftPaddle - (paddleHeight/2) <= yPos) &&
(yPos <= leftPaddle + (paddleHeight /2))) {
// reverse the horizontal direction:
xDirection =-xDirection;
}
}
}
// if the ball is moving right:
else {
// if the ball is to the right of the right paddle:
if ((xPos >= ( rightPaddleX + ballSize/2))) {
// if the ball is in between the top and bottom
// of the right paddle:
»
if((rightPaddle - (paddleHeight/2) <=yPos) &&
60 MAKING THINGS TALK
// stop the ball going off the top or the bottom of the screen:
if ((yPos - ballSize/2 <= 0) || (yPos +ballSize/2 >=height)) {
// reverse the y direction of the ball:
yDirection = -yDirection;
}
// update the ball position:
xPos = xPos + xDirection;
yPos = yPos + yDirection;
void resetBall() {
// put the ball back in the center
xPos = width/2;
yPos = height/2;
}
8
You’re almost ready to set the boolean ballInMotion = false; // whether the ball should be moving
ball in motion. But first, it’s time to do int leftScore = 0;
something with the reset and serve int rightScore = 0;
buttons. Add another variable at the
beginning of the code (just before
the setup() method with all the other
variable declarations) to keep track of
whether the ball is in motion. Add two
more variables to keep score.
THE SIMPLEST NETWORK 61
8 Now you’re ready to animate the // calculate the ball's position and draw it:
ball. It should move only if it’s been if (ballInMotion == true) {
served. This code goes at the end animateBall();
of the draw() method. The first if() }
statement starts the ball in motion
when the serve button is pressed. The // if the serve button is pressed, start the ball moving:
second moves it if it’s in service. The if (serveButton == 1) {
third resets the ball to the center, and ballInMotion = true;
resets the score when the reset button }
is pressed.
// if the reset button is pressed, reset the scores
// and start the ball moving:
if (resetButton == 1) {
leftScore = 0;
rightScore = 0;
ballInMotion = true;
}
so that when the ball goes off the // if the ball goes off the screen left:
screen left or right, the appropriate if (xPos < 0) {
score is incremented (added lines are rightScore++;
shown in blue). resetBall();
}
// if the ball goes off the screen right:
if (xPos > width) {
leftScore++;
resetBall();
}
8 To include the scoring display, add int fontSize = 36; // point size of the scoring font
a new global variable before the
setup() method.
8 Then add two lines before the // create a font with the third font available to the system:
end of the setup() method to initial- PFont myFont = createFont(PFont.list()[2], fontSize);
ize the font. textFont(myFont);
Figure 2-14
The completed Monski Pong Pro-
cessing sketch.
Flow Control
You may notice that the paddles don’t always move as smoothly onscreen as Monski’s
arms move. Sometimes the paddles don't seem to move for a fraction of a second,
and sometimes they seem to lag behind the actions you’re taking. This is because
the communication between the two devices is asynchronous.
Although the devices agree on the rate at which data is and sharing processor time with other programs through
exchanged, it doesn’t mean that the receiving computer’s the operating system. It may get bytes from the buffer less
program has to use the bits as they’re sent. Monitoring the than a hundred times a second—even though the bytes
incoming bits is actually handled by a dedicated hardware are coming in much faster.
circuit, and the incoming bits are stored in a memory
buffer, called the serial buffer, until the current program There’s another way to handle the communication
is ready to use them. Most personal computers allocate a between the two devices that can alleviate this problem.
buffer for each serial port that can hold a couple thousand If Processing asks for data only when it needs it, and if
bytes. The program using the bits (Processing, in the the microcontroller only sends one packet of data when
previous example) is juggling a number of other tasks, like it gets a request for data, the two will be in tighter sync.
redrawing the screen, handling the math that goes with it,
8
Add the following lines at the void serialEvent(Serial myPort) {
end of serialEvent() in the Processing // rest of the serialEvent goes here
sketch (new lines are shown in blue). myPort.write('\r'); // send a carriage return
}
Now, the paddles should move much more The change in the Processing sketch is at the end of the
smoothly. Here's what’s happening: the serialEvent(). There, it sends a byte back to the micro-
microcontroller is programmed to send controller, which, seeing a new byte coming in, sends out
out a "hello" string until it receives any serial data. another packet of data, and the whole cycle repeats itself.
When it does, it goes into the main loop. There, it reads This way, the serial buffer on Processing's side never fills
the byte just to clear the serial buffer, then sends up, and it's always got the freshest sensor readings.
out its data once, then waits for more data to arrive.
Whenever it gets no bytes, it sends no bytes. The value of the byte that the microcontroller receives is
irrelevant. It’s used only as a signal from the Processing
Processing, meanwhile, starts its program by waiting sketch to let the microcontroller know when it’s ready for
for incoming data. When it gets any string ending in a new data. Likewise, the "hello" that the controller sends
newline, serialEvent() is called, just as before. It reads is irrelevant—it's only there to trigger Processing to send
the string, and if there are commas in it, it splits the an intial byte—so Processing discards it. This method of
string up and extracts the sensor values, like before. If handling data flow control is sometimes referred to as a
there are no commas in the string (for example, if the handshake method, or call-and-response. Whenever you’re
string is "hello"), Processing doesn't do anything with sending packets of data, call-and-response flow control
it. can be a useful way to ensure consistent exchange.
X
64 MAKING THINGS TALK
Project 3
If you're using Mac OS X, choose the Apple menu→System Ubuntu Linux's Bluetooth manager for version 1.0 is a bit
Preferences, then click Bluetooth. Make sure Bluetooth limited, so it's easier to install BlueMan instead. Go to the
is turned on and Discoverable, and click "Show Bluetooth Ubuntu Software center, search for BlueMan, and install
status in the menu bar." At the bottom of the list of it. When it's installed, open the System control panel and
devices, click the + sign to launch the Bluetooth Setup you'll see Bluetooth Manager, in addition to the default
Assistant. The computer will search for devices and Bluetooth control panel. Open Bluetooth Manager, and it
find one called FireFly-XXX (Bluetooth Mate Gold) or will scan for available devices and show them, including
RN42-XXX (Silver), where XXX is the Bluetooth module’s one called FireFly-XXX or RN42-XXX, where XXX is the
serial number. If you have no other Bluetooth devices on, serial number of your Bluetooth module. When prompted
it will be the only one. Choose this device, and on the next for the device's pairing code, enter 1234. Once it's added,
screen, click Passkey Options. Choose "Use a Specific click Setup, and you'll get a dialog asking you if you want
Passcode," and enter 1234. Click Continue. A connection to connect to a serial port. Click Forward, and it will tell you
will be established, as will a serial port. When you look for the name of the serial port for the Bluetooth module, /dev/
the serial port in CoolTerm, the Arduino serial port menu, rfcomm0.
or the Processing serial port list, it will be FireFly-XXX-SPP
or RN42-XXX-SPP.
Adjusting the Monski Pong Program
For Windows 7 users, there are different Bluetooth radios Once your computer has made contact with the Bluetooth
in different Windows-based PCs. If your PC doesn't have module, you can connect to it like a serial port. Run the
a built-in Bluetooth radio, any Bluetooth adapter that Monski Pong Processing sketch and check the list of serial
supports the Windows Bluetooth Stack will do. Most ports. You should see the new port listed along with the
Bluetooth USB dongles on the market support it. Install others. Take note of which number it is, and change these
the drivers according to your radio's instructions, and lines in the setup() method:
when it's done, click on the Show Hidden Icons icon in the
taskbar (the small triangle in the lower-right-hand corner). String portName = Serial.list()[0];
When you do, you'll see the Bluetooth Devices icon, as // open the serial port:
shown in Figure 2-15. Click on this to add a new Bluetooth myPort = new Serial(this, portName, 9600);
Device.
For example, if the Bluetooth port is the ninth port in your list,
change the first line to open Serial.list[8]. Then change the
data rate in the second line as follows:
Figure 2-15
Where to find the Windows Bluetooth Devices icon (it's well hidden!). Likewise, you'll need to change your Arduino sketch so that
Click Customize... if you want to add it to your taskbar. the Serial.begin() line reads as follows:
The system will search for new devices and present you Serial.begin(115200);
with a list, which should include one called FireFly-XXX,
where XXX is the serial number of your Bluetooth module. Disconnect the Bluetooth module from the Arduino before
If you have no other Bluetooth devices nearby, it will be the you upload the modified sketch, as it will interfere with the
only one. When prompted for the device's pairing code, upload. You can re-connect it once you've uploaded the new
enter 1234. This step will add a new serial port to your code. With no other changes in code, you should now be
list of serial ports. Make note of the port name (mine is able to connect wirelessly. Monski is free to roam around
COM14) so you can use it later. the room as you play pong. When the Processing program
makes a connection to the Bluetooth module, the green
LED on the module will turn on.
66 MAKING THINGS TALK
If you haven’t modified your Arduino and Processing code to match the call-and-response version of the Monski Pong
program shown in the “Flow Control” section earlier, you might have a problem making a connection through the radio. If
so, make the changes from that section first. Once you do, Monski Pong should operate as before, only now it's wireless.
X
Figure 2-16
Monski pong board, with Bluetooth
module added. Once you’ve built the
circuit for this, drill holes in the project
RN-42
MADE
I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
TX
+ UNO ON
A
B leading to the flex sensors. Mount
ARDUINO
Connect
RX C
Stat
D
E
the breadboard, Arduino module, and
RESET-EN
RESET ICSP
GND
VCC
CTS
RTS
W W W.ARD UINO.CC
RX
TX
F
G
H
I
J
POWER ANALOG IN 1 5 10 15 20 25 30
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
AREF
To breadboard +5V +5V GND
To breadboard Ground Gnd D13
To Battery Ground Gnd D12
To Battery +9V +9V D11/PWM
D10/PWM
D9/PWM +5V
+5V D8
15KΩ flex Arduino
Module
D7 reset serve
D6/PWM
A2 D3/PWM
Figure 2-17 A3 D2
If you didn't buy a battery snap with DC A4 Digital1/TX 10KΩ
power adapter like the Spark Fun one, 10KΩ A5 Digital0/RX
you'll need to solder the connector onto
your battery snap, as shown here. +5V
CTS
+5V
BlueSMiRF GND
Module
TX
RX
RTS
THE SIMPLEST NETWORK 67
Figure 2-18.
You might want to shrink
Monski Pong so it's more
compact. This figure shows the
Monski Pong circuit on a bread-
board shield. This is the same
circuit as the one in Figure
2-16, it's just on a different
breadboard so it can fit in a
project box.
Figure 2-19.
Kitchen storage containers
make excellent project boxes.
Here’s the Monski Pong con-
troller with Monski attached.
68 MAKING THINGS TALK
Project 4
The steps you went through to pair your »» 1 Bluetooth Mate module
»» 1 FTDI USB-to-Serial converter
Bluetooth module with your computer
negotiated a series of exchanges that
included discovering other radios, learning
The Bluetooth module is essentially a modem in that it
the services offered by those radios, and converts from one communications medium (TTL serial
pairing to open a connection. It’s very carried over wires) to another (Bluetooth serial carried
over radio). Modems are designed to open a connection
convenient to be able to do this from the to another modem, negotiate the terms of data exchange,
graphical user interface, but it would be carry on an exchange, and then disconnect. To do this,
they must have two operating modes, usually referred
even better if the devices could negotiate to as command mode, in which you talk to the modem,
this exchange themselves. In the section and data mode, in which you talk through the modem.
Bluetooth modems are no different in this respect.
that follows, you’ll negotiate some parts of
that exchange directly, in order to under- Most Bluetooth modems (and many other communica-
tions devices) use a set of commands based on the those
stand how to program devices to handle
designed originally for telephone modems, known as the
that negotiation. Hayes AT command protocol. All commands in the Hayes
command protocol (and therefore in Bluetooth command
protocols as well) are sent using ASCII characters. Devices
Bluetooth FTDI
Mate USB-to-Serial
Cable
Connect
RN-42 RX RX
TX TX
Vcc Vcc
Stat
Gnd Gnd
Figure 2-20
Bluetooth Mate module connected to an FT232RL USB-to-Serial converter. The Mate is designed to be a drop-in replacement for the FTDI
cable, so it has the same pin configuration. As a result, you have to cross the transmit and receive connections to make the connection work.
using this protocol all have a command mode and a data command, separated by commas. The command ends
mode. To switch from data mode to command mode in the with an ASCII carriage return. The modem then responds
Hayes protocol, send the string +++. There’s a common to the command with the message OK, followed by any
structure to all the commands. Each command sent from information it's expected to return.
the controlling device (like a microcontroller or personal
computer) to the modem begins with the ASCII string AT, The Bluetooth Mate doesn't use AT commands, but its
followed by a short string of letters and numbers repre- protocol is similar. The commands are all ASCII-based.
senting the command, followed by any parameters of the
THE SIMPLEST NETWORK 69
There is a command mode and a data mode. In data Networks RN-41 radio, if you're searching their site, and
mode, you send the string $$$ to switch to command the Bluetooth Mate Silver uses the RN-42 radio). A few of
mode. the commands are covered here. Each Bluetooth modem
manufacturer has its own set of commands; unfortunately,
The commands are all short strings, and the modem they’re all different. But they all have the same basic
responds with the response AOK. To exit command mode, structure as the one you see here.
send the string ---\r (the \r is a carriage return, ASCII 13),
and the Bluetooth modem switches back to data mode. In Currently, the module is in command mode. One of the
data mode, any bytes you send the modem are sent out first things you’d like is to see its settings. Type D and hit
over the radio, and any bytes received over the radio get return or enter. You'll get a list of the radio's settings, which
sent out the serial connection. looks like this:
***Settings***
Controlling the Bluetooth Module
Wire the Bluetooth module to the USB-to-Serial converter, BTA=000666112233
as shown in Figure 2-20. Since the converter and the cable BTName=FireFly-7256
have identical pin configurations, you'll need to cross Baudrt(SW4)=115K
the TX and RX lines to make them connect. Connect the Parity=None
converter to a USB port on your computer. Mode=Slav
Authen=0
For this project, you'll need a serial terminal program that Encryp=0
can open two serial ports at the same time, so the Arduino PinCod=1234
Serial Monitor won't do. One serial port will be the wired Bonded=0
connection to the Bluetooth module through the USB-to- Rem=NONE SET
serial adapter. The other will be the wireless connection
via Bluetooth.
The first setting is the Bluetooth address. That’s the part
For Mac OS X and Windows users, CoolTerm will work well. you need in order to make a connection to it. Manufactur-
For Ubuntu Linux users, GNU screen or PuTTY will do. ers of Bluetooth devices agree on a standard addressing
Open a connection to the USB-to-Serial adapter at 115200 scheme so no two devices get the same address. The
bits per second. settings that follow give you information about the radio's
configuration, such as the serial data rate (or baudrate),
When you first power the Bluetooth Mate, it will be in data whether authentication's turned on, and what the
mode. To switch to command mode, send the string: passcode or PIN code is.
$$$ You may have noticed that you can't see what you type.
That's because the keystrokes in a serial terminal program
The module will respond like so: aren't echoed back to the screen—they're sent straight
to the serial port. However, the Bluetooth Mate will echo
CMD your characters back to you if you type +\r. This turns
Echo Mode on or off. It's useful to have on while issuing
You're now in command mode. Any time you want to commands.
check that the module is working and in command mode,
type enter or return, and send it. It will respond with ?. Now that you know something about your own module,
To see a list of all possible commands, type H and then you want it to give you a list of other Bluetooth-enabled
enter. There’s a list of all the commands available for this devices in the area. Type I for inquiry. After several
module at www.SparkFun.com or www.rovingnetworks. seconds, it will come back with a list like this:
com (the Bluetooth Mate Gold module uses the Roving
70 MAKING THINGS TALK
?
Inquiry, COD=0
Found 9
0010C694AFBD,,1C010C
0023125C2DBE,tigoebook,3A010C ! You can’t initiate a connection from the Bluetooth
0017F29F7A67,screen1,102104 Mate to the computer unless you’ve previously paired
002241CE2E79,residents,380104 with the Mate from the computer. This is because Bluetooth
002241D70127,admints Mac mini,380104 radios can’t initiate a serial connection unless they’ve already
0014519266B8,ERMac,102104 made a pairing with the other device. You’ll see more on these
002241CE7839,VideoMac05,380104 radios in Chapter 6.
E806889B12DD,,A041C
00236CBAC2F0,Fred Mac mini,302104
Inquiry Done
This is a list of all the other Bluetooth devices it found. The first part of every string is the device’s unique address.
The second, when there is one, is the device’s name; the third is the device class, or what type of device it is (you can
probably pick out the device class number for Mac minis from the list above). Names don’t have to be unique, but
addresses do, which is why you always use the address to connect.
hi there
C, 002241CE3F79
Computer's
USB-to-serial connector Serial Bluetooth RF Bluetooth Radio
Bluetooth Mate's
Bluetooth Radio
Figure 2-21
How the Bluetooth Mate is talking to your computer's
Bluetooth serial port.
THE SIMPLEST NETWORK 71
Now that you’ve got a list of connections, you're going to where address is the Bluetooth address of your
try to connect to the one that represents your computer. computer that you discovered earlier. When you
You must already be paired with the Bluetooth module get a good connection, the LED on the Mate will
for this to work, so if you aren't, go back to the previous turn on, and you can type back and forth between
project and do that now. Then, you need to open the serial the windows. This is more exciting if you have two
port on your computer that’s connected to its Bluetooth computers and connect them via Bluetooth, but it
radio. works on one computer nonetheless.
In Mac OS X, it’s the Bluetooth PDA-Sync port. Open a You’re now out of command mode and into data
second window in your terminal program, and connect to mode. You should be able to type directly from one
that serial port at 115200 bps. window to the other.
For Windows 7 users, click on the Show Hidden Icons To get out of data mode (to check the modem’s
icon in the taskbar to get to the Bluetooth Devices. Click status, for example), type (\r indicates that you
the Bluetooth Devices Icon and, from the menu, choose should hit Enter or Return; don't type the \ or the r):
Open Settings. In the Settings window, choose the Options
pane—and make sure that you've allowed other devices $$$\r
to find this computer, and that you've allowed them to
connect as well. Then click the COM ports pane. If you've This will give you a CMD prompt again. You can now
paired with your Bluetooth module before, there will be type any of the commands you want and get replies.
two ports indicated for it, one outgoing and one incoming. To return to data mode, type:
You're not using those, though, because Windows tries
to initiate contact when you do. You want the Bluetooth ---\r
modem to initiate contact. Add a new incoming port.
Note the port number, then open that port in your serial Finally, when you’re in command mode, you can type
terminal program at 115200 bps. K,\r to disconnect. If you want to connect to another
device, go into command mode and start over again.
For Ubuntu Linux users, the Bluetooth Manager doesn't
support binding a serial port to a discoverable Bluetooth Because these commands are just text strings, you
serial port protocol (SPP) connection, so you'll need to can easily use them in microcontroller programs to
make the connection outbound from Ubuntu, as described control the module, make and break connections,
in the earlier section, "Pairing Your Computer with the and exchange data. Because all the commands are
Bluetooth Module." Once you're paired, however, the in ASCII, it’s a good idea to exchange data in ASCII
procedure to send and receive data, or to switch from mode, too. So, the data string you set up earlier to
command mode to data mode on the Bluetooth Mate, will send Monski’s sensor readings in ASCII would work
be the same as for other platforms. well over this modem.
X
Once you've opened the serial port on your computer,
go back to the window with the serial connection to the
Bluetooth module, and send the following command:
C, address\r
72 MAKING THINGS TALK
Conclusion
The projects in this chapter have covered a number of ideas that are central to all
networked data communication. First, remember that data communication is based on
a layered series of agreements, starting with the physical layer; then the electrical, the
logical, the data layers; and finally, the application layer. Keep these layers in mind as
you design and troubleshoot your projects, and you’ll find it's easier to isolate problems.
Second, remember that serial data can be sent either as Fourth, consider the flow of data, and look for ways to
ASCII or as raw binary values, and which you choose to ensure a smooth flow with as little overflowing of buffers
use depends both on the capabilities and limitations of all or waiting for data as possible. A simple call-and-response
the connected devices. It might not be wise to send raw approach can make data flow much smoother.
binary data, for example, if the modems or the software
environments you program in are optimized for ASCII data Finally, get to know the modems and other devices that
transfer. link the objects at the end of your connection. Understand
their addressing schemes and any command protocols
Third, when you think about your project, think about the they use so that you can factor their strengths and limita-
messages that need to be exchanged, and come up with tions into your planning, and eliminate those parts that
a data protocol that adequately describes all the informa- make your life more difficult. Whether you’re connecting
tion you need to send. This is your data packet. You might two objects or two hundred, these same principles will
want to add header bytes, separators, or tail bytes to make apply.
reading the sequence easier. X
A More Complex
Network
Now that you’ve got the basics of network communications, it’s time
to tackle something more complex. The best place to start is with
the most familiar data network: the Internet. It’s not actually a single
network, but a collection of networks owned by different network
service providers and linked using some common protocols. This
chapter describes the structure of the Internet, the devices that hold
it together, and the shared protocols that make it possible. You’ll get
hands-on experience with what’s going on behind the scenes when your
web browser or email client is doing its job, and you’ll use the same
messages those tools use to connect your own objects to the Net.
4
3
Figure 3-1. New parts for this chapter: 1. Interlink Series 402 force-sensing resistors (FSRs) 2. 30AWG wire-wrapping wire
3. Wire-wrapping pins (or long female headers) 4. New tool: wire-wrapping tool. The wire stripper to the left of the tool lives inside
the handle. Don’t forget plenty of male header pins for the breakout boards.
A MORE COMPLEX NETWORK 77
Figure 3-4
Network settings panels for Mac OS X and Windows.
For Ubuntu Linux, click the System menu, then encoded in its subnet mask. You may have encountered a
Preferences→Network Connections. You’ll see a list of subnet mask when configuring your personal computer.
network interfaces. Click Edit to see their details. A typical subnet mask looks like this: 255.255.255.0.
Figure 3-4 shows the network connection settings for Mac You can read the number of machines in the subnet
OS X and Windows. No matter what platform you’re on, by reading the value of the last octets of the subnet
the hardware address and the Internet address will take mask. It’s easiest if you think of the subnet in terms of
these forms: bits. Four bytes is 32 bits. Each bit you subtract from
the subnet increases the number of machines it can
• The hardware address is made up of six numbers support. Basically, you “subtract” the subnet mask
written in hexadecimal notation, like this: from its maximum value of 255.255.255.255 to get the
00:11:24:9b:f3:70 number of machines. For example, if the subnet were
• The IP address is made up of four numbers written in 255.255.255.255, there could be only one machine in the
decimal notation, like this: 192.168.1.20 subnet: the router itself. If the last octet is 0, as it is above,
there can be up to 255 machines in the subnet in addition
You’ll need to know the IP address to send and receive to the router. A subnet of 255.255.255.192 would support
messages, and you’ll need to know the hardware address 63 machines and the router (255 – 192 = 64), and so
in order to get an IP address on some networks. So, forth. There are a few other reserved addresses, so the real
whenever you begin working on a new project, note both numbers are a bit lower. Table 3-1 shows a few other repre-
addresses for every device you’re using. sentative values to give you an idea.
Street, City, State, Country: How Table 3-1. The relationship between subnet mask and maximum
number of machines on a network.
IP Addresses Are Structured
Maximum number of machines on
Geographic addresses can be broken down into layers of Subnet mask the subnet, including the router
detail, starting with the most specific (the street address) (accounting for reserved addresses)
and moving to the most general (the country). Internet 255.255.255.255 1 (just the router)
Protocol (IP) addresses are also multilayered. The most
specific part is the final number, which tells you the 255.255.255.192 62
address of the computer itself. The numbers that precede
255.255.255.0 254
this tell you the subnet that the computer is on. Your
router shares the same subnet as your computer, and its 255.255.252.0 1022
number is usually identical except for the last number. The
numbers of an IP address are called octets, and each octet 255.255.0.0 65,534
separate protocol, the Domain Name System (DNS), to its best capacity. On the Internet, this happens at the
for assigning names to the numbers. Machines on the transport layer. This is the layer of the network responsible
network called nameservers keep track of which names for making sure packets get to their destination. There are
are assigned to which numbers. In your computer’s two main protocols used to handle transport of packets
network configuration, you’ll notice a slot where you can on the Internet: Transmission Control Protocol (TCP), and
enter the DNS address. Most computers are configured User Datagram Protocol (UDP). You’ll learn more about
to obtain this address from a router using the Dynamic these later. The main difference is that TCP provides more
Host Control Protocol (DHCP) , which also provides their error-checking from origin to destination, but is slower
IP address, so you don’t have to worry about configuring than UDP. On the other hand, UDP trades off error-checking
DNS. In this chapter’s project, you won’t be going out to in favor of speed.
the Internet at large, so your devices won’t have names,
just numbers. When that happens, you’ll need to know Each router sends off the packets one at a time to the
their numerical addresses. routers to which it’s connected. If it’s attached to more
than one other router, it sends the packets to whichever
router is least busy. The packets may each take a different
Packet Switching: How Messages route to the receiver, and they may take several hops
across several routers to get there. Once the packets
Travel the Net reach their destination, the receiver strips off the headers
So how does a message get from one machine to another? and reassembles the message. This method of sending
Imagine the process as akin to mailing a bicycle. The messages in chunks across multiple paths is called
bike’s too big to mail in one box, so first you break it into packet switching. It ensures that every path through the
box-sized pieces. On the network, this is initially done at network is used most efficiently, but sometimes packets
the Ethernet layer—also called the datalink layer—where are dropped or lost. On the whole, though, the network
each message is broken into chunks of more or less the is reliable enough that you can forget about dropped
same size, and given a header containing the packet packets.
number. Next, you’d put the address (and the return
address) on the bike’s boxes. This step is handled at the There’s a command-line tool, ping, that can be useful in
IP layer, where the sending and receiving addresses are determining whether your messages are getting through.It
attached to the message in another header. Finally, you sends a message to another object on the Net to say “Are
send it. Your courier might want to break up the shipment you there?”, and then waits for a reply.
among several trucks to make sure each truck is used
82 MAKING THINGS TALK
To use it, open up the command-line application on your --- 127.0.0.1 ping statistics ---
computer (Terminal on Mac OS X, the command prompt 10 packets transmitted, 10 packets received, 0% packet loss
on Windows, and xterm or similar on Linux/Unix). On Mac round-trip min/avg/max/stddev = 0.143/0.164/0.206/0.015 ms
OS X or Linux, type the following:
It gives you a good picture of not only how many packets
ping -c 10 127.0.0.1 got through, but also how long they took. It’s a useful way
to learn quickly whether a given device on the Internet
On Windows, type this: is reachable or not, as well as how reliable the network
is between you and that device. Later on, you’ll be using
ping -n 10 127.0.0.1 devices that have no physical interface on which you can
see activity, so ping is a handy way to check whether
This sends a message to address 127.0.0.1 and waits for a they’re working.
reply. Every time it gets a reply, it tells you how long it took,
like this: NOTE: 127.0.0.1 is a special address called the loopback address
or localhost address. Whenever you use it, the computer you’re
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.166 ms sending it from loops back and sends the message to itself. You
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.157 ms can also use the name localhost in its place. You can test many
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.182 ms network applications using this address, even when you don’t have
a network connection.
After counting 10 packets (that’s what the -c 10 on Mac X
and -n 10 on Windows means), it stops and gives you a
summary, like this:
How Web Browsing Works online and available at all times so that the service is not
Figure 3-5 is a map of the routes web pages take to reach disrupted. In the case of a web server, the server provides
your computer. Your browser sends out a request for a access to a number of HTML files, images, sound files, and
page to a web server, and the server sends the page back. other elements of a website to clients from all over the
Which route the request and the reply take is irrelevant, Net. Clients are programs that take advantage of services.
as long as there is a route. The web server itself is just a Your browser, a client, makes a connection to the server
program running on a computer somewhere else on the to request a page. The browser makes a connection to the
Internet. A server is a program that provides a service to server computer, the server program accepts the connec-
other programs on the Net. The computer that a server tion and delivers the files representing the page, and the
runs on, also referred to as a server, is expected to be exchange is made.
A MORE COMPLEX NETWORK 83
Figure 3-5
The path from a website to your
browser. Although the physical
computers are in many different
locations, that doesn’t matter as
Website's
server long as you know the websites’
addresses.
Website's
network
provider
Internet
The server computer shares its IP address with every 4. The browser program asks for a specific file name,
server program running on it by assigning each program index.html.
a port number. For example, every connection request 5. The server program looks up that file on its local file
for port 80 is passed to the web server program. Every system, and prints the file out via the connection to the
request for port 25 is passed to the email server program. browser. Then, it closes the connection.
Any program can take control of an unused port, but only 6. The browser reads the file, looks up any other files it
one program at a time can control a given port. In this way, needs (like images, movies, style sheets, and so forth),
network ports work much like serial ports. Many of the and repeats the connection request process, getting all
lower port numbers are assigned to common applications, the files it needs to display the page. When it has all the
such as mail, file transfer, telnet, and web browsing. Higher files, it strips out any header information and displays
port numbers are either disabled or left open for custom the page.
applications (you’ll write one of those soon). A specific
request goes like this: All the requests from browser to server, and all the
responses from server to browser (except the images and
1. Type http://www.makezine.com/index.html into your movie files), are just strings of text. To see this process
browser. in action, you can duplicate the request process in the
2. The browser program contacts www.makezine.com on terminal window. Open up your terminal program again,
port 80. just as you did for the ping example shown earlier (on
3. The server program accepts the connection. Windows 7, use PuTTY).
84 MAKING THINGS TALK
After the header, the next thing you’ll see is a the files are encoded, and more. The end user never needs
lot of HTML that looks nowhere near as simple this information, but it’s very useful in managing the flow of
as the normal Google web interface. This is the data between client and server.
HTML of the index page of Google. This is how browsers
and web servers talk to each other, using a text-based Remember the PHP time example from Chapter 1?
protocol called the Hypertext Transport Protocol (HTTP). It should still be sitting on your own web server, at
The http:// at the beginning of every web address tells www.example.com/time.php (replace www.example.com
the browser to communicate using this protocol. The stuff with the address of your server). Try getting this
that precedes the HTML is the HTTP header information. file from the command line.
Browsers use it to learn the types of files that follow, how
Now, telnet into your web server on // get the date, and format it:
port 80 and request the file from the $date = date("Y-m-d h:i:s\t");
command line. Don’t forget to specify // include the date:
the HOST in your request, as shown echo "< $date >\n";
earlier in the request to Google.
?>
You should get a much more abbrevi-
ated response.
A MORE COMPLEX NETWORK 85
Even though the results of this approach aren’t In this case, you’re sending two parameters, name and
as pretty in a browser, it’s very simple to extract age. Their values are “tom” and “14”, respectively. You can
the date from within a Processing program— add as many parameters as you want, separating them
or even a microcontroller program. Just look for the < with the ampersand (&).
character in the text received from the server, read every-
thing until you get to the > character, and you’ve got it. There are predefined variables in PHP that give you access
to these parameters and other aspects of the exchange
HTTP requests don’t just request files. You can add param- between client and server. The variable $_REQUEST, used
eters to your request. If the URL you’re requesting is below, is an example that returns the parameters after
actually a program (like a PHP script), it can do something the question mark in an HTTP request. Other predefined
with those parameters. To add parameters to a request, variables give you information about the client’s browser
add a question mark at the end of the request and param- and operating system, the server’s operating system, any
eters after that. Here’s an example: files the client’s trying to upload, and much more.
http://www.example.com/get-parameters.php?name=tom&age=14
Try requesting this script with the same Expects two parameters from the HTTP request:
parameter string as the last script, name (a text string)
?name=tom&age=14, and see what age (an integer)
happens. Then change the age to a Prints a personalized greeting based on the name and age.
number greater than 21. */
NOTE: One great thing about PHP is that // read all the parameters and assign them to local variables:
it automatically converts ASCII strings of foreach ($_REQUEST as $key => $value)
numbers like “14” to their numerical values. {
Because all HTTP requests are ASCII-based, if ($key == "name") {
PHP is optimized for ASCII-based exchanges $name = $value;
like this. }
if ($key == "age") {
$age = $value;
}
}
Figure 3-6
The PHP age-checker form.
88 MAKING THINGS TALK
How Email Works The transport protocol for sending mail is called SMTP,
Transferring mail also uses a client-server model. It the Simple Mail Transport Protocol. It’s paired with two
involves four applications: your email program and your retrieval protocols: POP (Post Office Protocol) and IMAP
friend’s, and your email server (also called the mail host) (Internet Message Access Protocol). Just like HTTP, it’s
and your friend’s email server. Your email program adds a text-based. PHP has excellent functionality for sending
header to your message to say that this is a mail message, and retrieving mail, and you can use it as an intermediary
who the message is to and from, and what the subject between any local application, like the Processing sketch
is. Next, it contacts your mail server, which then sends that will follow, or some microcontroller applications you’ll
the mail on to your friend’s mail server. When your friend see later on.
checks her mail, her mail program connects to her mail
server and downloads any waiting messages. The mail
servers are online all the time, waiting for new messages
for all of their users.
I mailed [email protected] // set up your variables for mailing. Change to and from
From: [email protected] // to your mail address:
Hello world! $to = "[email protected]";
$subject = "Hello world!";
Hi there, how are you? $from = "From: [email protected]";
$message = "Hi there, how are you?";
In your mail client, you’ll get a
message like this: // send the mail:
mail($to, $subject, $message, $from);
From: You <[email protected]>
Subject: Hello world! // give notification in the browser:
Date: May 8, 2013 2:57:42 PM EDT echo "I mailed " . $to . "<br>";
To: you <[email protected]> echo $from . "<br>";
echo $subject. "<br><br>";
Hi there, how are you? echo $message;
?>
Make sure your server is properly configured to send mail here. If you're using a web hosting service, the settings for mail
will be part of your account settings. Also, make sure your from: address is one for which the mail server will relay mail.
That typically means you can only send mail from your own domain. For example, if your domain name is example.com,
then you can't send mail from [email protected].
As you can see, sending mail from PHP is very simple. So in addition to using it to serve web pages, you can use it to send
messages via mail. As long as you have a device or program that can make a GET or POST, you can use PHP or other
server-side programming languages to start a sequence of messages in many different applications across the Net. Now
that you’ve got the basics of HTTP requests and mail sending, it’s time to put them into action in a project.
A MORE COMPLEX NETWORK 89
Project 5
Networked Cat
Web browsing and email are all very simple
MATERIALS
for humans because we’ve developed
computer interfaces that work well with »» Between 2 and 4 force-sensing resistors,
our bodies. Keyboards work great with our Interlink 400 series
»» 1 1-kilohm resistor
fingers, and mice glide smoothly under »» 1 solderless breadboard
our hands. It’s not so easy for a cat to »» 1 Arduino microcontroller module
»» 1 personal computer
send email, though. This project attempts »» 1 web camera
to remedy that while showing you how to »» 1 cat mat
»» 1 cat
build your first physical interface for the »» 2 thin pieces of wood or thick cardboard,
Internet. about the size of the cat mat
»» Wire-wrapping wire
»» Male header pins
If you’re a cat lover, you know how cute they can be when
they curl up in their favorite spot for a nap. You might find
it useful during stressful times at work to think of your cat,
curled up and purring away. Wouldn’t it be nice if the cat Putting Sensors in the Cat Mat
sent you an email when he lays down for a nap? It would First, you need a way to sense when the cat is on the mat.
be even better if you could then check in on the cat’s The simplest way to do this is to put force sensors under
website to see him at his cutest. This project makes that the mat and sense the difference in weight when he sits on
possible. it. How you do this depends on what kinds of force-sensing
resistors you use. Interlink’s 400 series FSRs work well for
The system works like this: force-sensing resistors are this project. Mount the sensors on something with a firm
mounted under the cat mat and attached to a micro- backing, like masonite, or another type of wood or firm
controller. The microcontroller is attached to a personal cardboard.
computer, as is a camera. When the cat lies down on the
mat, his weight will cause a change in the sensor readings. There are some FSRs that are long and thin, like Interlink’s
The microcontroller then sends a signal to a program on 408 series. Long sensors aren’t all that common, though,
the personal computer, which takes a picture with the so you’re more likely to have small round sensors like the
camera and uploads it to a web server via a PHP script. 400 or 402 series. If you’re using those or other smaller
Then the program calls another PHP script that sends you FSRs from another company like CUI or FlexiForce, you’ll
an email, letting you know that your cat is being particu- need to make a larger sensing pad. First, cut two pieces of
larly cute. Figure 3-7 shows the whole system. wood or firm cardboard slightly smaller than the cat’s mat.
Don’t use a really thick or hard piece of wood. You just need
You’ll do this project in several parts: something firm enough to provide a relatively inflexible
surface for the sensors. Attach the sensors to the corners
1. Write an Arduino sketch to read sensors in the cat’s mat of one of the pieces of wood or cardboard. Sandwich the
and send the results serially to Processing. sensors between the two boards. Tape the two boards
2. Write a Processing sketch to read the serial data and together at the edges loosely, so that the weight of the
when appropriate, call a PHP script that sends mail. cat can press down to affect the sensors. If you tape too
3. Write a PHP script to send mail. tightly, the sensors will always be under force; too loose,
4. Make a web page for the cat cam. and the boards will slide around too much and make the
5. Write a second PHP script to accept new image uploads cat uncomfortable. If the sensors don’t give enough of
for the web page. a reaction, get some little rubber feet—available at any
6. Modify the Processing sketch to take new images and electronics or hardware store—and position them on the
upload them via the second PHP script.
90 MAKING THINGS TALK
Figure 3-7
The networked cat system.
panel opposite the sensors so that they press down on the You’re using multiple sensors so you can sense a
sensors. If the wood or cardboard panels have some flex large area under the mat, but it doesn’t matter much
in them, position an extra rubber foot or two at the center which one gets triggered. Connect the sensors to an
of the panel to reduce the flex. Figures 3-8, 3-9, and 3-10 analog input of the microcontroller in parallel with
show a working version of the sensor board. each other, using the voltage divider circuit shown in
Figure 3-10. This circuit combines the input from all
Next, attach long wires to the force-sensing resistors to four into one input.
reach from the mat to the nearest possible place to put the X
microcontroller module.
A MORE COMPLEX NETWORK 91
Figure 3-8
Because the force-sensing resistors melt easily, I used 30AWG wire
wrap instead of solder. Wire-wrapping tools are inexpensive and
easy to use, but make a secure connection. After wire wrapping,
I insulated the connections with heat shrink. (Heat shrink not
shown.)
Figure 3-9
The cat-sensing panel. The four FSRs are wired in parallel. Note the
rubber feet that press down more precisely on the sensors. Make
sure to insulate the connections before taping the panels together.
The connector is just a pair of female wire-wrap headers.
92 MAKING THINGS TALK
A MORE COMPLEX NETWORK 93
AREF
Figure 3-10
Reset GND The cat-sensing circuit.
+3.3V D13 Because all of the force-
sensing resistors are wired
+5V D12
in parallel, there are only
Gnd D11/PWM two connections for all
Gnd D10/PWM of them. This circuit is
simple enough that you
Vin D9/PWM
can just solder a resistor to
D8 a header pin to make the
Arduino
Module connection to ground.
4 force-sensing D7
resistors
D6/PWM
Analog0 D5/PWM
A1 D4
A2 D3/PWM
A3 D2
! You may need a
1KΩ higher value depending on the
A4 Digital1/TX
resistance range of your force-
A5 Digital0/RX
sensing resistors and the weight
of your cat. If a 1K resistor
doesn’t give you good values,
try a 4.7K or a 10K resistor. The
photo here shows a 10K resistor.
94 MAKING THINGS TALK
void setup() {
size(400,300);
// list all the available serial ports
println(Serial.list());
// I know that the first port in the serial list on my Mac is always my
// Arduino, so I open Serial.list()[0]. Open whatever port you're using
// (the output of Serial.list() can help; they are listed in order
// starting with the one that corresponds to [0]).
myPort = new Serial(this, Serial.list()[0], 9600);
»
// read bytes into a buffer until you get a newline (ASCII 10):
A MORE COMPLEX NETWORK 95
Refine It If your system is float prevSensorValue = 0; // previous value from the sensor
working correctly, float lastXPos = 0; // previous horizontal position
you should notice a difference of several
points in the sensor readings when the
cat gets on the mat. It helps to graph
the results so you can see clearly what
the difference looks like. To do that, add
a few extra variables to the variable list
at the beginning of your Processing
program.
8 Next, add a new method called void drawGraph(float prevValue, float currentValue) {
drawGraph(). // subtract the values from the window height
// so that higher numbers get drawn higher
// on the screen:
float yPos = height - currentValue;
float lastYPos = height - prevValue;
»
96 MAKING THINGS TALK
8
NOTE: Once you’ve got the serial con- xPos = 0;
nection between the microcontroller and the lastXPos = 0;
computer working, you might want to add in background(#543174);
the Bluetooth radio from the Monski Pong }
project in Chapter 2. It will make your life else {
easier if your computer doesn’t have to be // increment the horizontal position:
tethered to the cat mat in order to program. xPos++;
// save the current graph position
// for next time:
lastXPos = xPos;
}
}
Figure 3-11
Output of the sensor-graphing program.
A MORE COMPLEX NETWORK 97
You don’t just want to respond to events, though. You back on. Decide on an appropriate interval, wait that long,
might have a fickle cat who jumps on and off the mat a and don’t respond to any input during that time. Once the
lot. Once you’ve sent a message, you don’t want to send interval’s over, start looking for input again.
another one right away, even if the cat gets off the mat and
8 Add the following new variable int threshold = 250; // above this number, the cat is on the mat.
to the beginning of your program.
Determine the threshold value by
watching the sensor value without the
cat on the mat, and picking a number
that’s higher.
8
Finally, add a method that sends void sendMail() {
mail. For now, it will just print a place- println("This is where you'd send a mail.");
holder to the message window. After }
the next section, you'll write code to
make it send mail for real. Add this
method to the end of your program.
When you run the program, you should see messages sketch so that once it sends a message, it doesn’t send
in the console area saying when the cat jumps on or any others for an acceptable period. You can do this by
off the mat, and when a mail would be sent. Your cat modifying the sendMail() method to keep track of when
may be fickle or may take his time settling on the mat, the last message was sent. Here’s how to do it.
which can result in several mail messages as he gets
comfortable. To avoid this, you want to change the
98 MAKING THINGS TALK
Tame It Every time the int currentTime = 0; // the current time as a single number
program sends a mail int lastMailTime = 0; // last time you sent a mail
message, it should take note of the int mailInterval = 60; // minimum seconds between mails
time. Add a few new variables at the String mailUrl = "http://www.example.com/cat-script.php";
beginning of the program.
8
Add one line at the beginning of void draw() {
the draw() method to update current- currentTime = hour() * 3600 + minute() * 60 + second();
Time continuously.
When you run the sketch this time, you’ll see an error message like this when you cross the threshold:
cat on mat
results from mail script:The file “http://www.example.com/cat-script.php” is missing or inaccessible, make sure the URL is
valid or that the file has been added to your sketch and is readable.
The sketch is now making an HTTP GET request to call a PHP script that’s not there. In the next section, you’ll write that
script.
8 <?php
/*
Mail sender
Context: PHP
Figure 3-12
Regardless of which option you use, the Cat
Cam page will look like this.
A MORE COMPLEX NETWORK 101
Uploading Files to a Server you saw earlier, $_FILES is an array, and each of the array
elements is a property of the file. You can get the name of
Using PHP the file, the size of the file, and the file type, which will be
Next, you’re going to write a script that uploads images useful when you write a script that takes only JPEG files
to the server. PHP has a predefined variable, $_FILES, below a certain size.
that allows you to get information about any files the user
attempts to upload via HTTP. Like $_REQUEST, which
8
Replace the PHP part of this script <?php
(the part between <?php and ?>) with if (isset($_FILES)) {
the following. This script checks to see // put the file parameters in variables:
that the uploaded file is a JPEG file with $fileName = $_FILES['file']['name'];
fewer than 100 kilobytes, and it saves it $fileTempName = $_FILES['file']['tmp_name'];
in the same directory as the script. $fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
»
}
102 MAKING THINGS TALK
8 Now when you load this script in a Continued from previous page.
browser and upload a file, you’ll be able // if there's no file error, print some HTML about the file:
to see the file in the directory after- else {
wards. Try uploading a new JPEG of the echo "Upload: " . $fileName . "<br />";
cat, then reload the browser window of echo "Type: " . $fileType . "<br />";
the index.html page you made earlier. echo "Size: " . ($fileSize / 1024) . " Kb<br />";
You should see the same page with the echo "Temp file: " . $fileTempName . "<br />";
new image.
// if the file already exists,
// delete the previous version:
if (file_exists($fileName)) {
unlink($fileName);
}
// move the file from the temp location to
// this directory:
move_uploaded_file($fileTempName, $fileName);
echo "Uploaded file stored as: ".$fileName;
}
}
// if the file's not a JPEG or too big, say so:
else {
echo "File is not a JPEG or too big.";
}
}
?>
void setup() {
size(640, 480); // set the size of the window
void draw() {
// if there's data from the camera:
if (myCam.available()) {
myCam.read(); // read the camera image
set(0, 0, myCam); // draw the camera image to the screen
}
}
8
Add these lines after the set() void draw() {
command in the draw() method to // if there's data from the camera:
draw a timestamp on the screen (new if (myCam.available()) {
lines are shown in blue). myCam.read(); // read the camera image
set(0, 0, myCam); // draw the camera image to the screen
8 Now add a global variable at the import processing.video.*; // import the video library
top of your sketch for a filename, and Capture myCam; // the camera
add a method at the end of the sketch String fileName = "catcam.jpg";
to save the window image to a JPEG
file when you hit any key (new lines are // setup and draw methods go here
shown in blue).
void keyReleased() {
Save this sketch before you run it. PImage img = get();
When you run it, hit any key. Then img.save(fileName);
check the sketch folder, and you should }
see a JPEG image generated by the
sketch, like Figure 3-13.
Figure 3-13
The output of the Cat Cam Pro-
cessing sketch.
8
Once you’ve got the three pieces of // calculate and send the length of the total request,
the request, calculate the total number // including the head of the request, the file, and the tail:
of bytes by adding the length of the two int contentLength = requestHead.length() + thisFile.length + tail.length();
strings and the byte array. Next, send thisClient.write("Content-Length: " + contentLength + "\n\n");
the content length, and then the content
itself. Finally, you close the connection // send the header of the request, the file, and the tail:
by stopping the client. thisClient.write(requestHead);
thisClient.write(thisFile);
thisClient.write(tail);
Save the sketch and run it. Now when you type any key, the sketch will not only save the image locally, but also upload it
to the catcam directory on your sever, via the save2web.php script.
106 MAKING THINGS TALK
HTML forms that use HTTP to enable file uploading are done with the POST request, as well as a special content type,
multipart/form-data, so the server knows how to interpret what comes through. Each element from the form is sent in a
separate part by a unique string. Here’s what the server might see from the uploader script you wrote earlier:
Upload
------H4rkNrF 88Content-Disposition: says what
Content-Disposition: form-data; name="file"; filename="catcam.jpg" this part is. For files, also includes
Content-Type: image/jpeg the local path to the file.
Figure 3-14
The flowchart of the Cat Cam sketch.
A MORE COMPLEX NETWORK 107
8
Now combine the setup() methods void setup() {
like so. size(400,300);
// list all the available serial ports
println(Serial.list());
// I know that the first port in the serial list on my Mac is always my
// Arduino, so I open Serial.list()[0]. Open whatever port you're using
// (the output of Serial.list() can help; they are listed in order
// starting with the one that corresponds to [0]).
myPort = new Serial(this, Serial.list()[0], 9600);
// read bytes into a buffer until you get a newline (ASCII 10):
»
myPort.bufferUntil('\n');
108 MAKING THINGS TALK
8
The draw() method paints the void draw () {
camera image to the screen and adds a // make a single number from the current hour, minute, and second:
timestamp. currentTime = hour() * 3600 + minute() * 60 + second();
if (myCam.available() == true) {
// draw the camera image to the screen:
myCam.read();
set(0, 0, myCam);
»
if (currentTime - lastPictureTime > pictureInterval) {
A MORE COMPLEX NETWORK 109
8
The sendMail() method checks to void sendMail() {
see whether enough time has passed // how long has passed since the last mail:
since the last mail before it sends. int timeDifference = currentTime - lastMailTime;
Then it calls the cat-mail.php script
using the loadStrings() function to if ( timeDifference > mailInterval) {
make an HTTP GET request. String[] mailScript = loadStrings(mailUrl);
println("results from mail script:");
println(mailScript);
// send the header of the request, the file, and the tail:
thisClient.write(requestHead);
thisClient.write(thisFile);
thisClient.write(tail);
}
cat from the mat. You should get another message in the
One Final Test console from the call to the mailer script. See whether the
To test this code, open the browser to the Cat Cam page, image changes once the cat is off the mat. It shouldn’t; the
and then run the sketch. On startup, it should take a image that remains should be the last one of the cat—that
picture and upload it. A few seconds later, the Cat Cam is, until the cat jumps on the mat again. The timestamp in
page will refresh itself, and you’ll see that image. Then get that image will give you an idea when the cat was last on
the cat to jump on the mat. The sketch will take another the mat.
image and upload it, and will then send you an email.
Check your mail to see whether there's a new message When all that works, take a breath and admire your work.
from the cat. Figure 3-15 shows the finished cat bed. Congratulations!
You’ve just made your first Internet-connected project. You
As long as the cat stays on the mat, the sketch will upload and your cat can now be in constant contact.
a new image every five seconds. Watch for a minute or so X
to see the image change a few times, and then remove the
A MORE COMPLEX NETWORK 111
Figure 3-15
The finished cat bed (at right) and a
detail of the sensor pad, which sits
under the cat bed itself. A bamboo
jewelry box houses the electronics—and
matches the furniture. The USB cable
runs to the computer. Make sure to
secure the wires thoroughly, or the cat
may try to chew on them.
112 MAKING THINGS TALK
Conclusion
Now you have an understanding of the structure of the Internet, and how
networked applications do their business.
The Internet is actually a network of networks, built up in messages. Likewise, it’s possible to write programs for a
multiple layers. Successful network transactions rely on personal computer or microcontroller to send those same
there being at least one dependable route through the messages, as you saw in the cat bed project. Now that
Internet from client to server. Client and server applica- you understand how simple those messages can be, you’ll
tions swap strings of text messages about the files they soon get the chance to do it without a personal computer.
want to exchange, transferring their files and messages In the next chapter, you'll connect a microcontroller to the
over network ports. To communicate with any given server, Internet directly using an Ethernet interface for the micro-
you need to know its message protocols. When you do, controller itself.
it’s often possible to test the exchange between client and X
server using a telnet session and typing in the appropriate
114 MAKING THINGS TALK
4
MAKE: PROJECTS
In the past few years, a wide array of commer- hosting machine. Home alarm systems are made up of
cial appliances has come on the market that networks of microcontrollers that talk among themselves,
can connect directly to the Internet without the with one that can communicate with a central server,
aid of a personal computer. Companies like D-Link, Sony, usually over phone lines using a modem.
Axis, and others make security cameras with network
interfaces, both Ethernet and WiFi. Ceiva, eStarling, and All of these appliances engage in networked communica-
others make picture frames with WiFi connections to tion. The simplest handle only one transaction at a time,
which you can upload images from the Net. Ambient requesting information from a server and then waiting
Devices makes lamps and displays of various sorts that for a response, or sending a single message in response
connect to the Net and change their appearance based to some physical event. Others manage multiple streams
on changes in information, such as stock market data, of communication at once, allowing you to surf the Web
weather, and other scalar quantities. Cable television while watching television. The more processing power a
set-top boxes are computers in a small box, capable of given device has, the more it can handle. For many applica-
routing streams of audio, video, and data all at the same tions, however, you don’t need a lot of processing power,
time. In fact, the operating system in your set-top box because the device you’re making has only one or two
might even be a variation of the same Linux operating functions.
system that’s running on your network provider’s web X
1
2
Figure 4-1. New parts for this chapter: 1. Arduino Ethernet shield—this one has a Power over Ethernet module on board
2. Photocells 3. Red, green, and blue lighting filter gels 4. Voltmeter. You can use an off-the-shelf one, but it's better if you can find
one that's antique. Don't forget plenty of male header pins for the breakout boards.
LOOK, MA, NO COMPUTER! 117
Figure 4-2
The Arduino Ethernet (left),
an Arduino Ethernet shield
(center), and an Ethernet shield
with power-over-Ethernet
module attached (right). You
can use any of these for the
Ethernet projects in this book.
LOOK, MA, NO COMPUTER! 119
an asynchronous serial port on your microcontroller. It uses an Ethernet chip from WizNet, the W5100. This shield
means you can still use the serial port for debugging or has a built-in SD memory card slot as well, like the Arduino
communicating with other devices. Ethernet board. The Adafruit Ethernet shield also uses the
W5100 chip, or it can use the Lantronix serial-to-Ethernet
There are two options for Ethernet connections to an modules mentioned earlier. The projects in this chapter
Arduino. One is the Arduino Ethernet board, which is an will work with the Arduino Ethernet, with the Arduino
Arduino board that has an Ethernet module on the board Ethernet shield, or with the Adafruit Ethernet shield with
itself. The Ethernet connector replaces the USB connector the W5100 module, which are shown in Figure 4-2. They
found on the standard Arduinos. To program this board, will not work with the Lantronix module, however.
you also need an FTDI-style USB-to-Serial adapter. The X
other option is an add-on board for regular Arduino
modules, called an Ethernet shield. There are a few
versions of it on the market. The Arduino Ethernet shield
Project 6
Hello Internet!
To use any network module, you first need LINK
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
to connect it to the network. That’s the
L ETHERNET
SHIELD - +
goal here. In this project, you'll make a RX
RESET
very simple web server on your Arduino
ON
100M
ICSP
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
MATERIALS
MADE
I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
»» 1 Arduino Ethernet or DIGITAL (PWM ~)
microcontroller module TX
+ UNO ON
RX ARDUINO
»» 1 Ethernet connection to the Internet
»» 3 10-kilohm resistors
RESET-EN
»» 3 photocells (light-dependent resistors) RESET ICSP
W W W.ARDUINO.CC
»» 1 solderless breadboard
»» 3 lighting filters
POWER ANALOG IN
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
clients. A server waits for connections from remote an available() command, as in the Serial library, to see
devices on the Internet and allows them to connect to whether there's any new data available from the server or
the Ethernet module, just like regular servers. A client client in question. The client object also has a connected()
initiates a connection to remote devices, makes requests, command that tells you whether it's connected to a
and delivers the replies, just like a regular client. Both remote server. This will be useful later, when you're trying
servers and clients can be read from and written to, using to connect to a remote server to get data. Here, you'll get
the read(), write(), print(), and println() commands that started with a simple server sketch.
you've already seen with the Serial library. There's also
LINK
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
RX
ETHERNET
SHIELD - + A
1 5 10 15 20 25 30
B
RESET
ON C
D
100M
M A D E I N I TA LY E
WWW.ARDUINO.CC
ICSP
F
G
H
I
J
1 5 10 15 20 25 30
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
10KΩ
122 MAKING THINGS TALK
Before you can write your program, you need to Ethernet module—as long as no other device connected to
establish some basic information about how your the router is using the same address.
Ethernet module will connect to the Internet. Just as you
did in Chapter 3, you'll need the device's Media Access When a router assigns addresses to its connected devices,
Control (MAC) address. That's the hardware address of it masks part of the address space so that those devices
your Ethernet controller. The Arduino Ethernet modules can use only addresses in the same subnet as the router
have a six-byte address on the back, written in hexadeci- itself. For example, if the router is going to assign only
mal notation, that you can use. If the sticker's missing addresses in the range 192.168.1.2 through 192.168.1.254,
for any reason, you can make up your own MAC address, it masks out the top three numbers (octets). This is
or use the generic one you find in the examples below. called the netmask, or subnet mask. In your PC’s network
You'll also need to know the router's address (aka the settings, you’ll see it written as a full network address, like
gateway address because your router is the gateway to so: 255.255.255.0. With the Ethernet module, you'll assign
the rest of the Internet), as well as the address that your it similarly.
device will use on the router's subnet.
Once you know your MAC address, your router's address,
Your device's IP address will be similar to your router's your IP address, and your subnet mask, you're ready to go.
address, probably using the same three numbers for the X
start of the address, but a different number for the last.
For example, if your router's local address is 192.168.1.1,
you can use an address like 192.168.1.20 for your
/*
Try It To get started, you Web Server
need to include Context: Arduino
the SPI library and the Ethernet library
to control the module. You also need */
to initialize a variable to hold a server
instance. The server will run on port 80, #include <SPI.h>
just as most web servers do. #include <Ethernet.h>
88Change these to match your own device
and network.
You also need four variables for the Server server(80);
MAC address, IP address, gateway
address, and subnet mask. These last byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 };
four will be arrays of bytes, one byte for IPAddress gateway(192,168,1,1);
each byte in the respective addresses. IPAddress subnet(255,255,255,0);
IPAddress ip(192,168,1,20);
Run this sketch with the Ethernet module For now, you can keep it simple and just look for the end
attached to your router and the Serial Monitor of the request, which will be a linefeed (\n or ASCII 10),
open. Then open a browser window and go to followed by a carriage return (\r or ASCII 13), followed by
the Arduino's address. Using the example as shown, you'd another linefeed. Figure 4-5 shows what happens in the
go to http://192.168.1.20. You won't see anything in the code that follows.
browser, but you will see the HTTP request come through X
in the Serial Monitor. Now you're seeing what the server
saw when you made HTTP requests in Chapter 3. A typical Client
request will look like this: connects
GET / HTTP/1.1
Host: 192.168.1.1 Check for
Connection: keep-alive incoming
bytes
Accept: application/xml,application/xhtml+xml,text/
html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
increment
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X carriage line length
10_6_5; en-US) AppleWebKit/534.10 (KHTML, like Gecko) return
while (client.connected()) {
if (client.available()) {
char thisChar = client.read();
// if you get a linefeed and the request line is blank,
// then the request is over:
if (thisChar == '\n' && lineLength < 1) {
// send a standard http response header
makeResponse(client);
break;
}
//if you get a newline or carriage return,
// you're at the end of a line:
if (thisChar == '\n' || thisChar == '\r') {
lineLength = 0;
}
else {
// for any other character, increment the line length:
lineLength++;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}
}
8 Before you can run this, you'll need void makeResponse(Client thisClient) {
to add a method , makeResponse(), at thisClient.print("HTTP/1.1 200 OK\n");
the end of your sketch to make a String thisClient.print("Content-Type: text/html\n\n");
to send the client. Here's a start. thisClient.print("Hello from Arduino</head><body>\n");
thisClient.println("</body></html>\n");
}
When you enter the Arduino's address in your the user to see, whether it's physical data from sensors or
browser now, you'll get a web page. There's other web-based data. The complexity is really up to you.
not much there, but it's legitimate enough that Once you start thinking creatively with the capabilities of
your browser doesn't know the difference between your the print() and println() statements, you get a wide range
Arduino and any other web server. You can add anything of ways to dynamically generate a web interface to your
you want in the HTML in the makeResponse() method— Arduino through the Ethernet shield.
even links to images and content on other servers. Think X
of the Arduino as a portal to any other content you want
LOOK, MA, NO COMPUTER! 125
Up until now, the Internet-related projects in this book you set. Note that the router reserves some ports for special
either worked only on a local subnet, or have only sent data purposes. For example, you may not be able to port forward
outbound and waited for a reply. This is the first project port 80, because the router uses it for its own interface.
in which your device needs to be visible to the Internet at That's why you might need to use a high number, like 8080.
large. You can view it while you're on the same local network,
but if it’s connected to your home router and has a private Web browsers default to making their requests on port 80,
IP address, it won't be visible to anyone outside your home. but you can make a request on any port by adding the port
To get around this, you need to arrange for one of your number at the end of the server, address like so:
router’s ports to forward incoming messages and connec-
tion requests to your Ethernet shield. http://www.myserver.com:8080/
To do this, open your router’s administrator interface and The new public address of your Ethernet module will follow
look for controls for “port forwarding” or “port mapping.” this pattern, too. For example, if your home router's public
The interface will vary depending on the make and model address is 203.48.192.56, you'd access your new Arduino
of your router, but the settings generally go by one of these server at http://203.48.192.56:8080.
names. It’s easiest if the forwarded port on the router is
the same as the open port on the Ethernet module, so Figures 4-6 and 4-7 show the settings on an Apple AirPort
configure it so that port 80 on your router connects to port Express router and a Linksys wireless router. On the Linksys
80 on the Ethernet shield (if your router allows it). Once router, you can find port forwarding under the Advanced tab.
you’ve done this, any incoming requests to connect to your
router’s public IP address on that port will be forwarded to
the Ethernet module's private IP address on the port that
Project 7
Networked Air-
Quality Meter MATERIALS
Figure 4-8
Microcontroller sets
The networked air-quality meter.
meter voltage using PWM
Micro-
controller Meter
Internet
LINK
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
RX
ETHERNET
SHIELD - + A
1 5 10 15 20 25 30
B
RESET
ON C
D
100M
M A D E I N I TA LY E
WWW.ARDUINO.CC
ICSP
F
G
H
I
J
1 5 10 15 20 25 30
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
Reset GND
+3.3V CLK
Figure 4-9
+5V Ethernet MOSI
Shield The circuit for a networked meter.
Gnd MISO
The Ethernet controller shown in
Gnd Eth, SS
Vin
the schematic is on the shield or the
SD card SS
Arduino Ethernet board.
AREF
Reset GND
+3.3V D13
+5V D12
Gnd D11/PWM
Gnd D10/PWM
Vin D9/PWM V
D8
Arduino Voltmeter
Module
D7
D6/PWM
Analog0 D5/PWM
A1 D4
A2 D3/PWM
A3 D2
A4 Digital1/TX
A5 Digital0/RX
130 MAKING THINGS TALK
Write a PHP Script to Read Figure 4-10 shows AIRNow’s page for New York
the Web Page City (http://airnow.gov/?action=airnow.local_
city&zipcode=10003&submit=Go). AIRNow’s page is
Next, you need to get the data from AIRNow’s site in a formatted well for extracting the data. The AQI number
form the microcontroller can read. The microcontroller is clearly shown in text, and if you remove all the HTML
can read in short strings serially, and converting those tags, it appears on a line by itself, always following the line
ASCII strings to a binary number is fairly simple. Using a Current Conditions.
microcontroller to parse through all the text of a web page
is possible, but a bit complicated. However, it’s the kind of NOTE: One of the most difficult things about maintaining applica-
task for which PHP was made. The program that follows tions like this, which scrape data from an existing website, is the
reads the AIRNow page, extracts the current air-quality probability that the designers of the website could change the
index (AQI) reading, and makes a simpler summary page format of their page. If that happens, your application could stop
that's easy to read with the microcontroller. The Ethernet working, and you’ll need to rewrite your code. In fact, it happened
controller is the microcontroller’s gateway to the Internet, between the first and second editions of this book. This is a case
allowing it to open a TCP connection to your web host, where it’s useful to have the PHP script do the scraping of the
where you will install this PHP script. remote site. It’s more convenient to rewrite the PHP than it is to
reprogram the microcontroller once it’s in place.
NOTE: You could also run this script on one of the computers on X
your local network. As long as the microcontroller is connected
to the same network, you’ll be able to connect to it and request
the PHP page. For information on installing PHP or finding a web-
hosting provider that supports PHP, see www.php.net/manual/en/
tutorial.php#tutorial.requirements.
LOOK, MA, NO COMPUTER! 131
Figure 4-10
AIRNow’s page is nicely laid out
for scraping. The PHP program
used in this project ignores the
ozone level.
Scrape It To extract the data // whether you should check for a value
you need from // on the line you're reading:
those lines, you’ll need a couple more $checkForValue = false;
variables. Add this code before the
fopen() command. // value of the Air Quality reading:
$airQuality = -1;
8 Replace the command echo $line; // if the current line contains the substring "Current Conditions"
in the program with the block of code // then the next line with an integer is the air quality:
at right. if (preg_match('/Current Conditions/', $line)) {
$checkForValue = true;
This block uses the preg_match() }
command to look for a string of text
matching a pattern you give it. In this
case, it looks for the pattern Current
Conditions. When you see that line, you
know the next line is the number you
want. When the PHP script finds that
line, it sets the variable $checkForValue
to true.
8 Now, add the following block of if ($checkForValue == true && (int)$line > 0){
code after the one you just added. This $airQuality = (int)$line;
code checks to see whether $check- $checkForValue = false;
ForValue is true, and whether the line }
contains an integer and nothing else.
If so, the program reads the next line
of text and converts it from a string to
an integer value. It will only get a valid
integer when it reaches the line with
the AQI value.
Air Quality: 43
Read the PHP Script Using you’re writing that program in Processing, in Arduino, or in
the Microcontroller another language on another microcontroller, the steps are
still the same:
Next, it's time to connect to the PHP script through the
Net using the Ethernet module. This time, you'll use the 1. Open a connection to the web server.
shield as a client, not a server. Before you start program- 2. Send an HTTP GET request.
ming, plan the sequence of messages. Using the Ethernet 3. Wait for a response.
module as a network client is very similar to using Pro- 4. Process the response.
cessing as a network client. In both cases, you have to 5. Wait an appropriate interval and do it all again.
know the correct sequence of messages to send and how
the responses will be formatted. You also have to write a
program to manage the exchange of messages. Whether
Attempt to connect
to server
Figure 4-11
A flowchart of the Arduino program
for making and processing an HTTP
GET request. Connected to
yes no
server?
Make HTTP
request
Map result to
meter's range
Set meter
Figure 4-11 is a flowchart of what happens in the microcon- This program will check the PHP script every two minutes.
troller program. The major decisions (if statements in your If there's a new value for the air quality, it'll read it and set
code) are marked by diamonds; the methods are marked the meter. If it can't get a connection, it will try again two
by rectangles. Laying out the whole program in a flowchart minutes later. Because it's a client and not a server, there's
like this will help you keep track of what’s going on at any no web interface to the project, only the meter.
given point. It also helps you to see what methods depend
on a particular condition being true or not. TextFinder Library
For this sketch, you're going to need Michael Margolis'
The circuit for this project also uses LEDs to keep track TextFinder library for Arduino. Download it from www.
of the state of the program. LEDs attached to I/O pins arduino.cc/playground/Code/TextFinder, unzip it, and save
will indicate the state. There's an LED to indicate that it's the TextFinder folder to the libraries folder of your Arduino
connected, another to indicate that it's disconnected, a sketches directory (the default location is Documents/
third to indicate if it got a valid reading, and a fourth to Arduino/libraries/ on OS X, My Documents\Arduino\libraries\
indicate that the microcontroller is resetting. on Windows 7, and ~/Documents/Arduino/libraries/ on
Ubuntu Linux. If the libraries directory doesn't exist, create
134 MAKING THINGS TALK
it and put TextFinder inside. Restart Arduino, and the TextFinder is under consideration for inclusion in version
TextFinder library should show up in the Sketch→Import 1.0 of Arduino, in which case you would not need to install
Library menu. TextFinder lets you find a substring of text it. So check the Reference section of www.arduino.cc for
from the incoming stream of bytes. It's useful for both the latest updates.
Ethernet and serial applications, as you'll see.
If you can't use ping (some service providers block it, since it can be used for nefarious purposes), you can also use nslookup.
For example, nslookup google.com will return the following:
Server: 8.8.8.8
Address: 8.8.8.8#53
88nslookup returns the Domain Name
Server it used to do the lookup as well.
Non-authoritative answer:
Name: google.com
Address: 173.194.33.104
Any one of the addresses listed will point to it's associated name, so you can use any of them.
LOOK, MA, NO COMPUTER! 135
8 Next, initialize a few array variables byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 };
with the network configuration for the IPAddress ip(192,168,1,20);
module. IPAddress server(208,201,239,101 );
88Change these to
match your own device
and server.
8 The last global variables you need // Initialize the Ethernet client library
to add are for the Client class, and Client client;
a few variables relating to the transac-
tion with the server. boolean requested; // whether you've made a request
long lastAttemptTime = 0; // last time you connected to the server
int airQuality = 0; // AQI value
boolean meterIsSet = false; // whether the meter is set
8
setup() starts the serial and void setup() {
Ethernet connections, sets all the LED // start the Ethernet connection:
pins to be outputs, blinks the reset Ethernet.begin(mac, ip);
LED, and makes an initial attempt to // start the serial library:
connect to the server. Serial.begin(9600);
// set all status LED pins:
pinMode(connectedLED, OUTPUT);
pinMode(successLED, OUTPUT);
pinMode(resetLED, OUTPUT);
pinMode(disconnectedLED, OUTPUT);
pinMode(meterPin, OUTPUT);
8
The blink() method called in the void blink(int thisPin, int howManyTimes) {
setup blinks the reset LED so you know // Blink the reset LED:
the microcontroller’s main loop is for (int blinks=0; blinks< howManyTimes; blinks++) {
about to begin. digitalWrite(thisPin, HIGH);
delay(200);
digitalWrite(thisPin, LOW);
delay(200);
}
}
136 MAKING THINGS TALK
8
The loop() contains all the logic void loop()
laid out in Figure 4-11. If the client {
is connected to the server, it makes // if you're connected, save any incoming bytes
an HTTP GET request. If it's made a // to the input string:
request, it uses TextFinder to search if (client.connected()) {
the response for the air-quality string if (!requested) {
and then sets the meter. If the client requested = makeRequest();
isn't connected to the server, it waits }
another two minutes until the request else {
interval's passed, and tries to connect // make an instance of TextFinder to search the response:
again. TextFinder response(client);
// see if the response from the server contains the AQI value:
if(response.find("Air Quality:")) {
// convert the remaining part into an integer:
airQuality = response.getValue();
// set the meter:
meterIsSet = setMeter(airQuality);
}
}
}
else if (millis() - lastAttemptTime > requestInterval) {
// if you're not connected, and two minutes have passed since
// your last connection, then attempt to connect again:
client.stop();
connectToServer();
}
8
Both setup() and loop() attempt void connectToServer() {
to connect to the server using the // clear the state of the meter:
connectToServer() method. If it gets meterIsSet = false;
a connection, it resets the requested
variable so the main loop knows it can // attempt to connect, and wait a millisecond:
make a request. Serial.println("connecting...");
if (client.connect(server, 80)) {
requested = false;
}
// note the time of this connect attempt:
lastAttemptTime = millis();
}
LOOK, MA, NO COMPUTER! 137
HTTP/1.1 200 OK
Date: Fri, 14 Nov 2010 21:31:37 GMT
Server: Apache/2.0.52 (Red Hat)
Content-Length: 10
Connection: close
Content-Type: text/html; charset=UTF-8
Air Quality: 65
8
Once the client's found the air- boolean setMeter(int thisLevel) {
quality string and converted the bytes Serial.println("setting meter...");
that follow into an integer, it calls boolean result = false;
setMeter() to set the meter with the // map the result to a range the meter can use:
result it obtained. You might want to int meterSetting = map(thisLevel, 0, AQIMax, meterMin, meterMax);
adjust the AQIMax value to reflect the // set the meter:
typical maximum for your geographic analogWrite(meterPin, meterSetting);
area. if (meterSetting > 0) {
result = true;
}
return result;
}
Figure 4-12
The completed networked air-quality meter.
If the server grants an IP address, it returns true. If not, it returns false. The returned address is stored in Ethernet.localIP().
You may want a few other variables to use DHCP as well, including Ethernet.subnetMask(), Ethernet.gatewayIP(), and Ethernet.
dnsServerIP().
Using DNS is just as simple. Instead of passing a numeric server to the client.connect() command, give it a text string, like
so:
client.connect("www.example.com", 80);
The disadvantage of using DHCP and DNS is that they take a lot of RAM, so you may prefer to use the relevant numerical
addresses (once you know them).
LOOK, MA, NO COMPUTER! 139
/* DHCP
Context: Arduino
*/
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01};
IPAddress ip(192,168,1,20); // an address to use if DHCP fails
void setup() {
// start the serial library:
Serial.begin(9600);
// start the Ethernet connection:
Serial.println("Asking for an IP address using DHCP...");
if (!Ethernet.begin(mac)) {
// if DHCP fails, set your own address:
Ethernet.begin(mac, ip);
}
// print the bytes of the IP address, separated by dots:
Serial.print("I got an IP address. It's ");
Serial.println(Ethernet.localIP());
}
void loop() {
}
The begin() technique is useful in any Ethernet sketch because it uses DHCP if available, and sets an IP address manually if
not. If you know you're going to set the address manually and want to save program memory, just comment out the if() line
and the corresponding bracket, and leave the command inside it, like so:
//if (!Ethernet.begin(mac)) {
// if DHCP fails, set your own address:
Ethernet.begin(mac, ip);
// }
140 MAKING THINGS TALK
communication to talk to the Ethernet controller means code, they slow it down. The microcontroller has to save
you can still use the serial port to get messages about each bit of information received, which takes time away
what's going on—as you saw in the previous example. from your program. Even though the time is miniscule
Following are a few tips for effective serial debugging of for each bit, it can add up. After a few hundred bytes, you
networking code using serial messages. might start to notice it. So, make sure to take out your
serial transmission statements when you're done with
It's important to keep in mind that serial communication them.
takes time. When you have serial statements in your
8
Here's the less efficient code that client.connect(); // connect
solved the problem. Checking the con- delay(1); // wait a millisecond
nection immediately after connecting if (client.connected()) {
was apparently too soon. The delay // if you get a connection, report back via serial:
stabilized the whole program. Serial.println("connected");
}
else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
Write a Test Client Program program simply passes anything that comes in the serial
It’s easiest to work through the steps of the program if you port to the Ethernet port, and vice versa. It turns your
can step through the sequence of events. More complex Arduino into a serial-to-Ethernet gateway. Using this code,
development environments allow you to step through a you can connect to a serial terminal or to Processing—or
program one line at a time. Arduino doesn't give you that to any other development environment that can communi-
ability, but it can link to other environments. The following cate serially—to test the Ethernet connection.
void setup() {
// start the serial library:
Serial.begin(9600);
// start the Ethernet connection:
if (!Ethernet.begin(mac)) {
Serial.println("DHCP failed, configuring manually.");
// configure manually with your own IP address:
Ethernet.begin(mac, ip);
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("Ready to go.");
}
void loop() {
if (client.connected()) {
//if you're connected, pass bytes from client to serial:
if (client.available()) {
char netChar = client.read();
Serial.write(netChar);
}
//pass bytes from serial to client:
if (Serial.available()) {
»
char serialChar = Serial.read();
144 MAKING THINGS TALK
void connectToServer() {
// attempt to connect, and wait a millisecond:
Serial.println("connecting...");
if (client.connect(server, 80)) {
// if you get a connection, report back via serial:
Serial.println("connected");
}
else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
client.stop();
}
}
»
char linefeed = 10; // ASCII linefeed character
LOOK, MA, NO COMPUTER! 145
void draw()
{
//no action in the draw loop
}
void keyReleased() {
// if any key is pressed, take the next step:
switch (step) {
case 0:
// open a connection to the server in question:
myPort.write("C");
// add one to step so that the next keystroke causes the next step:
step++;
break; 88Change these to
case 1: match your own server.
// send an HTTP GET request
myPort.write("GET /~myaccount/index.html HTTP/1.1\n");
myPort.write("HOST:myserver.com\n\n");
step++;
break;
}
}
Starting with this sketch as a base, you could Don't get too caught up in the technical details of your
work out the whole logic of the HTTP exchange program when working this way. You're still going to have to
in Processing, then convert your sketch into an deal with the details of the microcontroller program even-
Arduino sketch. tually. However, it often helps to see the similarities and
differences between two languages when you're working
This approach allows you to work out the logical flow of on a problem. It helps you concentrate on the logic that
an application in an environment with which you might be underlies them.
more familiar. It removes the complications of the micro- X
controller environment, allowing you to concentrate on the
sequence of messages and the actions that trigger them.
146 MAKING THINGS TALK
Write a Test Server Program for sure that the server ever received your messages. If
The previous program allowed you to connect to a remote you never made a connection, you have no way of knowing
server and test the exchange of messages. The remote whether the module can connect to any server. To test this,
server was beyond your control, however, so you can’t say write your own server program to which it can connect.
Conclusion
The activities in this chapter show a model for networked objects that’s very flexible
and useful. The object is basically a browser or a server, requesting information from
the Web and extracting the information it needs, or delivering information to a client.
You can use these models in many different projects.
The advantage of these models is that they don’t require The model has its limits, though, and in Chapter 5, you’ll
a lot of work to repurpose existing web applications. At see some ways to get around those limits with a different
most, you need to write a variation of the PHP web scraper model. Even if you’re not using this model, don’t forget
from earlier in this chapter to summarize the relevant the troubleshooting tools mentioned here. Making simple
information from an existing website. This flexibility makes mock-ups of the programs on either end of a transac-
it easier for microcontroller enthusiasts who aren’t expe- tion can make your life much easier. This is because they
rienced in web development to collaborate with web pro- let you see what should happen, and then modify what
grammers, and vice versa. It also makes it easy to reuse actually is happening to match that.
others’ work if you can’t find a willing collaborator. X
148 MAKING THINGS TALK
5
MAKE: PROJECTS
Communicating in
(Near) Real Time
So far, most of the networked communications you’ve seen worked
through a web browser. Your object made a request to a remote server,
the server ran a program, and then it sent a response. This transaction
worked by making a connection to the web server, exchanging some
information, and then breaking the connection. In this chapter, you’ll
learn more about that connection, and you’ll write a server program
that allows you to maintain the connection in order to facilitate a faster
and more consistent exchange between the server and client.
3
2
1 5
Figure 5-1. New parts for this chapter: 1. Triple-wall cardboard 2. 3-axis accelerometer 3. 2-axis joystick 4. Pushbutton 5. Velcro
6. Project enclosure, made from mat board 7. 1/16" mat board template for project enclosure 8. Perforated circuit board. Don't
forget plenty of male header pins for the breakout boards.
COMMUNICATING IN (NEAR) REAL TIME 151
For example, in the cat bed application in Chapter 3, connections between all the objects will be configured. Will
there’s no need for the system to respond in more than it be a star network, with all the participants connected
a few seconds, because your reaction is not very time- through a central server? Will it be a ring network? Will
sensitive. As long as you get to see the cat while he’s on it be a many-to-many network, where every object has
the bed (which may be true for several minutes or hours), a direct connection to every other object? Each of these
you’re happy. Monski Pong in Chapter 2 relies on a rea- configurations has different effects on the feedback loop
sonably tight feedback loop in order to be fun. If it took a timing. In a star network, the objects on the edge of the
half-second or longer for the paddles to move when you network aren’t very busy, but the central one is. In a ring
move Monski’s arms, it would be no fun. The timing of the network, every object shares the load more or less equally,
feedback loop depends on the shortest time that matters but it can take a long time for a message to reach objects
to the participant. on opposite sides of the ring. In a direct many-to-many
network, the load is distributed equally, but each object
Any system that requires coordination between action and needs to maintain a lot of connections.
reaction needs a tight feedback loop. Consider remote
control systems, for example. Perhaps you’re building a In most cases where you have a limited number of objects
robot that’s operated over a network. In that case, you’d in conversation, it’s easiest to manage the exchange using
need not only a fast network for the control system, but a central server. The most common program example of
also a fast response from the camera or sensors on the this is a text-based chat server like IRC (Internet Relay
robot (or in its environment) that are giving you informa- Chat), or AOL’s instant messenger servers (AIM). Server
tion about what’s happening. You need to be able to both programs that accept incoming clients and manage text
control it quickly and see the results quickly. Networked messages between them in real time are often referred to
action games also need a fast network. It’s no fun if your as chat servers. The Processing program you’ll write in this
game console reacts slowly, allowing other players with chapter is a variation on a chat server. The server will listen
a faster network connection to get the jump on you. For for new connections and exchange messages with all the
applications like this, an exchange protocol that’s con- clients that connect to it. Because there’s no guarantee
stantly opening and closing connections (like HTTP does) how long messages take to pass through the Internet, the
wouldn’t be very effective. exchange of messages can’t be instantaneous. But as long
as you’ve got a fast network connection for both clients
When there’s a one-to-one connection between two and server, the feedback loop will be faster than human
objects, it’s easy to establish a tight feedback loop. When reaction time.
there are multiple objects involved, though, it gets harder. X
To begin with, you have to consider how the network of
152 MAKING THINGS TALK
For example, think about the exchanges between a The complexity of TCP is worthwhile when you’re exchang-
web client and server that you saw in the previous two ing critical data. For example, in an email, every byte is a
chapters. The pipe is opened when the server acknowledg- character in the message. If you drop a couple of bytes,
es the client’s contact, and it remains open until the server you could lose crucial information. The error-checking of
has finished sending the file. If there are multiple files TCP does slow things down a little, though, and if you want
needed for a web page, such as images and style sheets, to send messages to multiple receivers, you have to open a
then multiple socket connections are opened and closed. separate socket connection to each one.
There’s a lot going on behind the scenes of a socket con- There’s a simpler type of transmission protocol that’s
nection. The exchange of data over a TCP connection can also common on the Net: User Datagram Protocol (UDP).
range in size anywhere from a few bytes to a few terabytes Where TCP communication is based on sockets and
or more. All that data is sent in discrete packets, and the sessions, UDP is based only on the exchange of packets.
packets are sent by the best route from one end to the You’ll learn more about it in Chapter 7.
other. X
Project 8
Networked Pong
Networked games are a great way to learn about real-time connections. This project is a
networked variation on Pong. In honor of everyone’s favorite network status command,
let’s call it ping pong. The server will be a Processing program, and the clients will be
physical interfaces that connect through Ethernet-enabled Arduinos. The clients and
the server’s screen have to be physically close so that everyone can see the screen. In
this case, you’re using a network for its flexibility in handling multiple connections, not
for its ability to connect remote places.
From the Monski Pong project in Chapter 2, you’re already A Test Chat Server
aware of the methods needed to move the paddles and You need a server to get started. There’s a lot of code to
the ball, so some of the code will be familiar to you. As this control the pong display that you don’t need right now
is a more complex variation, it’s important to start with (you just want to confirm that the clients can connect), so
a good description of the whole system. The system will the following is a simple server with all the basic elements
work like this: to handle network communications. It will let you listen
for new clients, and then send them messages by typing
• The game has two teams of multiple players. in the applet window that appears when you run the
• Each player can move a paddle back and forth. The program. Run the server and open a telnet connection to
paddles are at the top and bottom of the screen, and it. Remember, it’s listening on port 8080, so if your com-
the ball moves from top to bottom. puter’s IP address is, say, 192.168.1.45, you’d connect like
• Players connect to the game server through a TCP so: telnet 192.168.1.45 8080. If you’re telnetting in from
connection. Every time a player connects, another the same machine, you can use: telnet localhost 8080 or
paddle is added to the screen. New connections telnet 127.0.0.1 8080.
alternate between the top and bottom teams. When
a player connects, the server replies with the following Whatever you type in the telnet window will show up in
string: hi, followed by a carriage return and a line feed the server’s debugger pane, and whatever you type in
(shown as \r\n). the server’s applet window will show up at the client’s
• The client can send the following commands: command line. However, you’ll have to press Return after
• l (ASCII value 108): move left each character in order for the server to see it—unless you
• r (ASCII value 114): move right make a change after you connect.
• x (ASCII value 120): disconnect
• When the client sends x, the server replies with the On Mac OS X or Linux, press the telnet escape key combi-
following string, and then ends the socket connection: nation (Ctrl-]), type the following, and then press Return:
That’s the communications protocol for the whole game. On Windows, telnet should not require any special con-
Keep in mind that it doesn’t define anything about the figuration, but if you find otherwise, press Ctrl-], type the
physical form of the client object. As long as the client can following, and press Return twice:
make a TCP connection to the server and can send and
receive the appropriate ASCII messages, it can work with set mode stream
the server. You can attach any type of physical inputs to
the client, or you can write a client that sends all these Now every character you type will be sent to the server as
messages automatically, with no physical input from the soon as you type it.
world at all (though that would be boring). Later in this X
chapter, you’ll see a few different clients, each of which
can connect to the server and play the game.
154 MAKING THINGS TALK
88This program uses a data type you may not have seen before: ArrayList. Think of it as a super-
duper array. ArrayLists don’t have a fixed number of elements to begin with, so you can add new
elements as the program continues. It’s useful when you don’t know how many elements you’ll have.
In this case, you don’t know how many clients you’ll have, so you’ll store them in an ArrayList, and
add each new client to the list as it connects. ArrayLists include some other useful methods. There
is an introduction to ArrayLists on the Processing website at www.processing.org.
if (message.equals("exit")) {
myServer.disconnect(speakingClient);
clients.remove(speakingClient);
}
}
}
COMMUNICATING IN (NEAR) REAL TIME 155
8
Finally, the keyReleased() method void keyReleased() {
sends any keystrokes typed on the myServer.write(key);
server to all connected clients. }
The Clients
The pong client listens to local input and remote input. The local input is from you,
the user. The remote input is from the server. The client is constantly listening to
you, but it only listens to the server when it's connected.
the server.
• An output to indicate when the connect/disconnect
button is pressed.
no connected?
• An output to indicate when it’s sending a left message.
• An output to indicate when it’s sending a right message. yes
It’s always a good idea to put outputs on the client to give send interval
yes
local feedback when it receives input from the user. Even passed?
Use outputs to indicate the client's status.In the following can build either, or both, or use the principles from them
code, you can see that in addition to indicating when the to build your own. Building both and comparing them will
sensors are triggered, you’ll also indicate whether the client give you an idea of how the same protocol can result in
is connected or disconnected. If this client had a more very different behavior. One of these clients is much more
complex set of states, you’d need more status indicators. responsive than the other, but the responsiveness has
nothing to do with the communications protocol. It’s all in
For this project, I built two clients. They have different the sensing and in the player’s action. Both of the clients
methods of physical interaction and different input use logic shown in Figure 5-2.
sensors, but they behave the same way to the server. You X
You'll notice that the connection switch is wired differently You'll need an enclosure for the circuit. You can buy a project
from a normal switch. Instead of a 10-kilohm pulldown case from your favorite electronics retailer, but you can also
resistor, it's got a 100-ohm resistor and an LED connecting get creative. For example, a pencil box from your friendly
it to ground. This way, when you push the button, the LED neighborhood stationery store will work well. Drill holes
lights up. There's no need to add any code to make this in the lid for the switch and the LEDs, cut a hole for the
happen—the pushbutton will send current through the joystick, cut holes in the side for the Arduino and Ethernet
LED automatically, and you'll get local feedback on when jacks, and you’re all set. If you're skilled with a mat knife, you
the button is being pressed. can also make your own box from cardboard or mat board.
Figure 5-7 shows the box I made, and Figure 5-9 shows the
These two clients are laid out on printed circuit proto- template from which I made it. If you're lucky enough to
typing boards (commonly known as perf boards). The have access to a laser cutter, use it; if not, a mat knife and a
perfboards make it possible for the circuits to be a little steady hand can do the job.
smaller and more physically robust. They're a bit harder X
to assemble than a solderless breadboard circuit, though.
COMMUNICATING IN (NEAR) REAL TIME 157
Figure 5-3
The joystick client, breadboard
layout. Note the red and green LEDs
to indicate left and right tilts. This
client follows nautical tradition: port
LINK
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
(left) is red and starboard (right) is
AREF
RX
ETHERNET
SHIELD - + A
1 5 10 15 20 25 30 green. Feel free to be less jaunty in
B
your own choices, as long as they’re
RESET
ON C
100M
M A D E I N I TA LY
D
E
clear.
WWW.ARDUINO.CC
ICSP
F
G
H
I Figure 5-4
J
1 5 10 15 20 25 30 The joystick client schematic. The
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
Reset GND
+3.3V CLK
+5V Ethernet MOSI
Shield
Gnd MISO
Gnd Eth, SS
Vin
SD card SS
AREF
Reset GND
+3.3V D13
+5V D12
Gnd D11/PWM
Gnd D10/PWM
Vin D9/PWM
+5V D8 +5V
Arduino
Module
L/R D7 Connect/Disconnect switch
Joystick
D6/PWM
Analog0 D5/PWM
U/D A1 D4
A2 D3/PWM
A3 D2
A4 Digital1/TX
100Ω 220Ω 220Ω 220Ω
A5 Digital0/RX
158 MAKING THINGS TALK
25
LINK
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
- +
20
L ETHERNET
RX
SHIELD
RESET
ON
15
100M
M A D E I N I TA LY
W W W. A R D U I N O.CC
ICSP
10
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
5
Figure 5-7
The assembled joystick controller. The joystick circuit
N M K L J I F G H E B C D
1
inside the housing was designed to be just tall enough
so that the LEDs and joystick would stick through the
top. Assemble the circuit first so you know how much
space you need for the housing. A cable made from
scrap stranded wire and male headers to connect
the pushbutton makes it easier to open and close the
Figure 5-5 box with the button mounted. The inner wires from a
The circuit as laid out on a perforated circuit board telephone cable work nicely for this.
(perfboard). Note that male headers are only attached to
the Arduino's analog input pins, power and ground pins,
and digital pins 2 through 5. The rest aren't needed.
Figure 5-8
Detail of the Arduino, Ethernet shield, and circuit board.
Figure 5-6 Use female headers to mount the LEDs and the switch.
The circuit board layout showing where the solder joints For the LEDs, it makes the job of getting them to the
are connected underneath the board. right height much easier. You can trim them bit by bit
until they are the right height, then stick them in the
headers.
25
20
15
10
1
N M K L J I F G H E B C D
COMMUNICATING IN (NEAR) REAL TIME 159
0.7”
Ethernet
USB
Jack
Jack
0.6” x 0.7”
0.45” x 0.5”
3-1/4” 3-1/4”
power
Jack
0.43” x 0.36”
2-1/4”
Hole centers:
2.64”
2.04”
1.79”
1.54”
0.94”
0.2” holes
for LEDs
1.1” diameter
for joystick 1.25” diameter
for button 3-3/16”
1/4”
6”
1.6”
2.5”
3.8”
Figure 5-9
Template for the joystick housing. This template can be cut out The first two prototypes were drawn by hand and cut out of paper,
of poster board or mat board and then folded to make a housing then scrap cardboard. I didn't move to a final version cut out of mat
for the joystick controller. The dimensions will depend on how you board until I had tested the fit of the sides with a paper version.
assemble your circuit, so modify them as needed. Although they Score the folds on the opposite side of the board so they fold better.
look precise here, they were measured with a caliper after the fact.
160 MAKING THINGS TALK
8
You need a number of constants to const int connectButton = 2; // the pushbutton for connecting/disconnecting
keep track of the input and output pin const int connectionLED = 3; // this LED indicates whether you're connected
numbers, the joystick's thresholds for const int leftLED = 4; // this LED indicates that you're moving left
left and right, and the minimum time const int rightLED = 5; // this LED indicates that you're moving right
between messages to the server. You'll const int left = 200; // threshold for the joystick to go left
need global variables for the connec- const int right = 800; // threshold for the joystick to go right
tion Client, the previous state of the const int sendInterval = 20; // minimum time between messages to the server
connect button, and the timestamp of const int debounceInterval = 15; // used to smooth out pushbutton readings
the last message sent to the server.
Client client; // instance of the Client class for connecting
You should update the left and right int lastButtonState = 0; // previous state of the pushbutton
thresholds with the values you discov- long lastTimeSent = 0; // timestamp of the last server message
ered earlier while testing the joystick.
8 Next, check whether the client's // if the client's connected, and the send interval has elapsed:
connected to the server, and whether if (client.connected() && (currentTime - lastTimeSent > sendInterval)) {
enough time has elapsed since the last // read the joystick and send messages as appropriate:
time you sent to the server. If so, read int sensorValue = analogRead(A0);
the joystick and, if it's at one extreme if (sensorValue < left) { // moving left
or the other, send the message to the client.print("l");
server and turn on the appropriate digitalWrite(leftLED, HIGH);
LED. If the joystick's in the middle, turn }
off the LEDs. Then save the current
time as the most recent time you sent if (sensorValue > right) { // moving right
a message. client.print("r");
digitalWrite(rightLED, HIGH);
You may have to adjust your sendInter- }
val value, depending on the responsive- // if you're in the middle, turn off the LEDs:
ness of your server and the sensitivity if (left < sensorValue && sensorValue < right) {
of your sensors. 20 milliseconds is a digitalWrite(rightLED, LOW);
good place to start, but if you find the digitalWrite(leftLED, LOW);
server slowing down with lots of clients, }
make it higher. //save this moment as last time you sent a message:
lastTimeSent = currentTime;
Finally, set the state of the connection }
LED using the state of the client itself.
// set the connection LED based on the connection state:
digitalWrite(connectionLED, client.connected());
}
162 MAKING THINGS TALK
8
Finally, you can’t just connect or // this method reads the button to see if it's just changed
disconnect every time the connect // from low to high, and debounces the button in case of
button is high. You want to send // electrical noise:
a message only when the button
changes from low to high, indicat- boolean buttonRead(int thisButton) {
ing that the player just pressed it. boolean result = false;
This method checks for a low-to-high // temporary state of the button:
transition by comparing the state of int currentState = digitalRead(thisButton);
the button with its previous state. It's // final state of the button:
called from the main loop. int buttonState = lastButtonState;
// get the current time to time the debounce interval:
This method also debounces the long lastDebounceTime = millis();
button, which means that it listens for
a few extra milliseconds to see whether while ((millis() - lastDebounceTime) < debounceInterval) {
the button changes after the initial // read the state of the switch into a local variable:
read. Sometimes a pushbutton can currentState = digitalRead(thisButton);
give several false readings for a few
milliseconds, as the electrical contacts // If the pushbutton changed due to noise:
settle against one another. The cheaper if (currentState != buttonState) {
the switch, the more common this is. // reset the debouncing timer
If you find that your pushbutton gives lastDebounceTime = millis();
multiple readings each time you push }
it, increase debounceInterval by a few
milliseconds. // whatever the reading is at, it's been there for longer
// than the debounce delay, so take it as the actual current state:
buttonState = currentState;
}
// if the button's changed and it's high:
if(buttonState != lastButtonState && buttonState == HIGH) {
result = true;
}
Client #2: A Balance Board Client thick. Each one is two inches from the center diameter
Client #2 is a balance board. To control it, you stand on of the circle, as shown in Figure 5-11. Glue the two circles
the board and tilt left or right. To stay in the middle, you together with their grains opposing each other.
have to balance the board. An accelerometer at the center
of the board senses it tilt from side to side. The physical Next, cut two arcs 12 inches across, as shown in Figure
interaction for this controller is very different than the 5-10. Glue the arcs into the slots and let them dry. Make
last. It requires more action from you, and it takes more sure it's very solid before you try to balance on it.
physical agility to operate. However, the behavior of this
client is identical to the previous one—from the server's The case for the balance board was adapted from the
point of view. joystick client. The differences are that the connect/
disconnect button took the place of the joystick, so the
The balance board itself is based on a design by the second large hole could be removed and the whole box
Adaptive Design Association (http://adaptivedesign.org), made shorter. Mount the control box at the center of your
a New York City-based organization that gets people balance board, as shown in Figure 5-12.
involved—families and community volunteers—in making
safe and affordable furniture and equipment for children The code for the balance board client is also very similar to
with disabilities. A balance board is great for helping to the joystick client. All you have to change is the values for
strengthen your balance, and it's fun as well. the left and right thresholds. To discover them, do as you
did with the joystick: put the accelerometer on the balance
The physical construction for the balance board client board, program the Arduino to print out the value of the
case is similar to the joystick client—you can use the analog input, and tilt it both ways to learn its extreme.
same template with the same LED setup. Just make the Then fill those values in for left and right. Everything else
joystick hole smaller to hold the pushbutton, and don't cut stays the same. That’s the beauty of using a clear, simple
a second hole. protocol: it doesn’t matter what the physical input is, as
long as you can map changes recorded by the sensors to
To construct the board, you'll need heavy-duty triple-wall a left-right movement, and program the microcontroller to
cardboard. Many packaging supply houses carry it. If you send the appropriate messages.
can't get triple-wall cardboard, you can laminate three
sheets of regular cardboard together using white glue. It’s worthwhile to try building both these clients, or one of
When you're gluing layers together, make sure the grain of your own, to look at how different physical affordances can
the corrugations for adjacent layers runs perpendicular to affect the performance of different clients, even though it
each other, for added stability. appears the same to the server.
X
Cut two circles approximately 15 inches in diameter from
a sheet of triple-wall cardboard. In one of them, cut two
slots, 12 inches long and as thick as your cardboard. In the Figure 5-10
board shown in Figure 5-12, the slots are roughly an inch The balance board rocker. Make two of these.
Design courtesy of the Adaptive Design Association.
2.5”
12”
164 MAKING THINGS TALK
Figure 5-11
The balance board base. Cut
two circles this size, and cut
the slots for the rockers in only
one of them. Then, laminate
the two circles together. Design
courtesy of the Adaptive Design
12”
Association.
1”
2”
15” diameter
2”
Figure 5-12
The balance board in action. The
two layers of triple-wall cardboard
are laminated with the grain of
their corrugations perpendicular
to each other. This gives the board
added stability. A couple of tabs
of Velcro hold the controller box
in place.
COMMUNICATING IN (NEAR) REAL TIME 165
Figure 5-13
The balance board client circuit,
breadboard version. You can see it's
identical to the joystick client, except
for the accelerometer in place of the
LINK
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND joystick.
AREF
RX
ETHERNET
SHIELD - + A
1 5 10 15 20 25 30
RESET
ON C
D
100M
M A D E I N I TA LY E
W W W. A R D U I N O.CC
ICSP
F
G
H
I
Figure 5-14
J
1 5 10 15 20 25 30 The balance board client schematic.
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
Reset GND
+3.3V CLK
+5V Ethernet MOSI
Shield
Gnd MISO
Gnd Eth, SS
Vin
SD card SS
AREF
Reset GND
+3.3V D13
+5V D12
Gnd D11/PWM
Gnd D10/PWM
Vin D9/PWM
ADXL330
Accelerometer D8 +5V
Arduino
ST Module
Z D7 Connect/Disconnect switch
Y D6/PWM
X Analog0 D5/PWM
GND A1 D4
3.3V A2 D3/PWM
A3 D2
A4 Digital1/TX
100Ω 220Ω 220Ω 220Ω
A5 Digital0/RX
166 MAKING THINGS TALK
25
20
15
25
LINK 10
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
- +
20
L ETHERNET
RX
SHIELD
RESET
ON 5
15
100M
M A D E I N I TA LY
W W W. A R D U I N O.CC
ICSP
1
10 N M K L J I F G H E B C D
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
5
Figure 5-15 Figure 5-16
The balance board client The circuit board
N M K L
1
circuit laid out on a per- layout showing where
J I F G H E B C D
forated circuit board. the solder joints are
connected underneath
the board.
The Server and height, and it has a location, which you can express in
The server's tasks can be divided into two groups: those terms of its horizontal and vertical positions. In your game,
related to the game play, like animating the paddles and the paddles will have another important property: each
the ball and scoring; and those related to tracking new paddle will be associated with a client. Of course, clients
clients. To manage it all most effectively, you’re going to have properties as well, so each paddle will inherit an IP
use an object-oriented programming approach. If you’ve address from its client. You’ll see all of these in the code
never done this before, there are a few basics you need to that defines a paddle as an object.
know in advance.
A paddle also has a characteristic behavior: it moves left
Anatomy of a Player Object or right. That behavior will be encoded into the paddle as a
The most important thing to know is that all objects have method called movePaddle(). This behavior will update the
properties and behaviors. You can think about an object’s properties of the paddle that define its location. A second
properties in much the same way as you think about behavior called showPaddle() will actually draw the paddle
physical properties. For example, a pong paddle has width in its current location. You’ll see later why these are kept
separate.
0.7”
Ethernet
USB
Jack
Jack
0.6” x 0.7”
0.45” x 0.5”
3-1/4” 3-1/4”
power
Jack
0.43” x 0.36”
2-1/4”
Hole centers:
2.64”
2.04”
1.79”
1.54”
0.94”
0.2” holes
for LEDs
0.6” diameter
for button 3-3/16”
1/4”
4”
1.6”
2.5”
Figure 5-17
Template for the balance board housing. As with the joystick client,
the template can be cut from 1/16" mat board. The dimensions
were changed to meet the needs of the smaller circuit.
168 MAKING THINGS TALK
As shown in the example, the variables declared at the already used constructors. When you made a new Serial
beginning of the class are called instance variables. Every port in Processing, you called the constructor method
new instance of the class created makes its own copies for the Serial class with something like, myPort = new
of these variables. Every class has a constructor method, Serial(this, portNum, dataRate).
which gets called to bring the object into existence. You’ve
8 Here’s the constructor for the public Player (int hpos, int vpos, Client someClient) {
Player class. It comes right after the // initialize the local instance variables:
instance variables in your code. As you paddleH = hpos;
can see, it just takes the values you paddleV = vpos;
give it when you call for a new Player, client = someClient;
and assigns them to variables that }
belong to an instance (an individual
player) of the class.
8 Next come the two other methods public void movePaddle(float howMuch) {
mentioned earlier, movePaddle() float newPosition = paddleH + howMuch;
and showPaddle(). As you can see, // constrain the paddle's position to the width of the window:
they use the object's instance variables paddleH = constrain(newPosition, 0, width);
(paddleH, paddleV, and client) to store }
the location of the paddle and to draw
it. public void showPaddle() {
rect(paddleH, paddleV, paddleWidth, paddleHeight);
// display the address of this player near its paddle
textSize(12);
text(client.ip(), paddleH, paddleV - paddleWidth/8 );
}
}
88This bracket closes the class.
That’s all the code to define a Player. Put this The Main Pong Server Program
code at the end of your program (shown next), Before you write the code for the server as a whole, it’s
just as if it were another method. To make a useful to make a flowchart of what happens. Figure 5-18
new Player object, write something like, Player newPlayer shows the main tasks and functions. A few details are
= new Player(xPosition, yPosition, thisClient). left out for clarity’s sake, but what’s clear are the main
relationships between the methods that run the program
When you do this, the new Player and all its instance (setup(), draw(), and serverEvent()) and the Player
variables and methods are accessible through the variable objects. As with any program, the setup() method kicks
called newPlayer (the new Player is not actually stored things off, and then the draw() method takes over. The
in this variable; it’s stuffed away in a portion of memory latter sees to it that the screen is updated and listens to
somewhere that you can get at through the newPlayer any existing clients. If a new client connects, a server-
variable). Keep an eye out for this in the program. Event() message is generated, which causes the method of
that name to run. That method creates new Player objects.
The draw() method takes advantage of the behaviors
inside the Player objects to move and draw their paddles.
COMMUNICATING IN (NEAR) REAL TIME 169
Figure 5-18
What happens in the
pong server program.
new client connects
setup() from the internet
set up graphics
serverEvent()
initialize
server
makeNew
draw() Player()
drawGame ()
Player Properties
draw each client
player’s paddle paddleH
paddleV
moveBall()
showPaddle() movePaddle()
01 showScore()
if
? GameOver true display winner
false
dispose of
listenToClients() x player
r
l
170 MAKING THINGS TALK
int topScore, bottomScore; // scores for the top team and the bottom teams
int paddleHeight = 10; // vertical dimension of the paddles
int paddleWidth = 80; // horizontal dimension of the paddles
int nextTopPaddleV; // paddle positions for the next player
// to be created
int nextBottomPaddleV;
8
The setup() method sets all the void setup() {
initial conditions for the game, and // set the window size:
then starts the server. size(480, 640);
// set the frame rate:
frameRate(90);
// set the default font alignment:
textAlign(CENTER);
// set no borders on drawn shapes:
noStroke();
// set the rectMode so that all rectangle dimensions
// are from the center of the rectangle (see Processing reference):
rectMode(CENTER);
8
The draw() method updates void draw() {
the screen using a method called drawGame();
drawGame(), and it listens for any listenToClients();
messages from existing clients using }
the listenToClients() method.
172 MAKING THINGS TALK
8 When new clients connect to the // The ServerEvent message is generated when a new client
server, the net library’s server- // connects to the server.
Event() method is called automatically; void serverEvent(Server thisServer, Client thisClient) {
your Processing sketch has to have if (thisClient != null) {
this method in order to respond to the // iterate over the playerList:
event. It uses the new client to create for (int p = 0; p < playerList.size(); p++) {
a new Player object using a method // get the next object in the ArrayList and convert it
called makeNewPlayer(). At right is the // to a Player:
serverEvent() method. Player newPlayer = (Player)playerList.get(p);
8
Now that you’ve seen the draw() void makeNewPlayer(Client thisClient) {
and the serverEvent() methods, // paddle position for the new Player:
it’s time to look at the methods int x = width/2;
they call. It’s best to start with the // if there are no players, add to the top:
creation of a new Player, so here’s the int y = nextTopPaddleV;
makeNewPlayer() method.
/*
A new Player is added to the bottom Get the paddle position of the last player on the list.
team if the last player is on the top, and If it's on top, add the new player on the bottom, and vice versa.
vice versa. If there are no other players, add the new player on the top.
*/
The variables nextTopPaddleV and // get the size of the list:
nextBottomPaddleV keep track of int listSize = playerList.size() - 1;
the positions for the next players on // if there are any other players:
each team. if (listSize >= 0) {
// get the last player on the list:
Player lastPlayerAdded = (Player)playerList.get(listSize);
// is the last player's on the top, add to the bottom:
if (lastPlayerAdded.paddleV == nextTopPaddleV) {
nextBottomPaddleV = nextBottomPaddleV - paddleHeight * 2;
y = nextBottomPaddleV;
}
// is the last player's on the bottom, add to the top:
»
else if (lastPlayerAdded.paddleV == nextBottomPaddleV) {
COMMUNICATING IN (NEAR) REAL TIME 173
// make a new Player object with the position you just calculated
// and using the Client that generated the serverEvent:
Player newPlayer = new Player(x, y, thisClient);
// add the new Player to the playerList:
playerList.add(newPlayer);
// Announce the new Player:
println("We have a new player: " + newPlayer.client.ip());
newPlayer.client.write("hi\r\n");
}
8
Once a new Player has been void listenToClients() {
created, you need to listen continuously // get the next client that sends a message:
for that Player’s client to send any Client speakingClient = myServer.available();
messages. The more often you check Player speakingPlayer = null;
for messages, the tighter the interac-
tive loop between sensor and action. // iterate over the playerList to figure out whose
// client sent the message:
The listenToClients() method, called for (int p = 0; p < playerList.size(); p++) {
continuously from the draw() method, // get the next object in the ArrayList and convert it
listens for messages from clients. If // to a Player:
there’s data available from any client, Player thisPlayer = (Player)playerList.get(p);
this method takes action. First, it // compare the client of thisPlayer to the client that sent a message.
iterates over the list of Players to see // If they're the same, then this is the Player we want:
whether each one’s client is speaking. if (thisPlayer.client == speakingClient) {
Then, it checks to see whether the speakingPlayer = thisPlayer;
client sent any of the game messages break;
(that is, l for left, r for right, or x for }
exit). If any of those messages was }
received, the program acts on the
message appropriately. // read what the client sent:
if (speakingPlayer != null) {
int whatClientSaid = speakingPlayer.client.read();
/*
There are a number of things it might have said that we care about:
x = exit
l = move left
r = move right
*/
switch (whatClientSaid) {
// If the client says "exit", disconnect it
case 'x':
// say goodbye to the client:
»
speakingPlayer.client.write("bye\r\n");
174 MAKING THINGS TALK
So far you’ve seen how the server receives new drawGame(), called from the draw() method, is the main
connections (using serverEvent()), creates method for this. This method has four tasks:
new Players from the new clients (using make-
NewPlayer()), and listens for messages (using listenTo- • Iterate over the playerList and draw all the paddles
Clients()). That covers the interaction between the server at their most current positions.
and the clients. In addition, you’ve seen how the Player • Draw the ball and the score.
class defines all the properties and methods that are • If the game is over, show a “Game Over” message
associated with each new player. Finally, it’s time to look and pause.
at the methods for controlling the drawing of the game. • Pause after each volley, then serve the ball again.
8
Likewise, the moveBall() method, // calculate ball's position:
called here, checks to see whether the ball if (ballInMotion) {
hit a paddle or a wall. It then calculates its moveBall();
new position from there, but it doesn’t }
draw the ball itself because the ball needs // draw the ball:
to be drawn even if it’s not in motion. rect(ballPosH, ballPosV, ballSize, ballSize);
»
showScore();
COMMUNICATING IN (NEAR) REAL TIME 175
»
if ((ballPosH >= paddleLeft) && (ballPosH <= paddleRight)) {
176 MAKING THINGS TALK
8 If the ball goes above the top of the // if the ball goes off the screen top:
screen or below the bottom, then one if (ballPosV < 0) {
team has scored. If any team goes over bottomScore++;
five points, the game is over. ballDirectionV = int(random(2) + 1) * -1;
resetBall();
}
// if the ball goes off the screen bottom:
if (ballPosV > height) {
topScore++;
ballDirectionV = int(random(2) + 1);
resetBall();
}
8 Finally, moveBall() checks to see // stop the ball going off the left or right of the screen:
whether the ball hits one of the sides if ((ballPosH - ballSize/2 <= 0) || (ballPosH +ballSize/2 >=width)) {
of the screen. If so, the horizontal // reverse the y direction of the ball:
direction is reversed. ballDirectionH = -ballDirectionH;
}
// update the ball position:
ballPosV = ballPosV + ballDirectionV;
ballPosH = ballPosH + ballDirectionH;
}
Figure 5-19
The output of the ping pong server sketch.
178 MAKING THINGS TALK
Conclusion
The basic structure of the clients and server in this chapter can be used any time
you want to make a system that manages synchronous connections between several
objects on the network. The server’s main jobs are to listen for new clients, keep track
of the existing clients, and make sure that the right messages reach the right clients. It
must place a priority on listening at all times.
The client should also place a priority on listening, but Finally, make sure you’ve got a reliable way to test the
it has to juggle listening to the server with listening to system. Simple tools like a telnet client and test server will
the physical inputs. It should always give a clear and save you much time in building every multiplayer server,
immediate response to local input, and it should indicate and help you get to the fun sooner.
the state of the network connection at all times.
Now you’ve seen examples of both asynchronous client-
The protocol that the objects in this system speak to each server exchanges (the HTTP system in Chapter 4) and
other should be as simple and as flexible as possible. synchronous exchanges (the chat server on page 153). With
Leave room for more commands, because you never those two tools, you can build almost any application in
know when you might decide to add something. Make which there’s a central server and a number of clients. For
sure to build in responses where appropriate, like the “hi” the next chapter, you’ll step away from the Internet and
and “bye” responses from the server. Keep the messages take a look at various forms of wireless communication.
unambiguous and, if possible, keep them short as well. X
At left
Jin-Yo Mok's original
sketches of the music
box.
At right
The music box composi-
tion interface.
COMMUNICATING IN (NEAR) REAL TIME 179
180 MAKING THINGS TALK
6
MAKE: PROJECTS
Wireless Communication
If you’re like most people interested in this area, you’ve been reading
through the early chapters thinking, “but what about wireless?” Perhaps
you’re so eager that you just skipped straight to this chapter. If you did,
go back and read the rest of the book! In particular, if you’re not familiar
with serial communication between computers and microcontrollers,
you’ll want to read Chapter 2 before reading this chapter. This chapter
explains the basics of wireless communication between objects. In it,
you’ll learn about two types of wireless communication, and then build
some working examples.
Alex Beim's Zygotes (www.tangibleinteraction.com) are lightweight, inflatable rubber balls lit from within
by LED lights. The balls change color in reaction to pressure on their surface, and they use ZigBee radios to commu-
nicate with a central computer. A network of zygotes at a concert allows the audience to have a direct effect
not only on the balls themselves, but also on the music and video projections to which they are networked.
Photo courtesy of Alex Beim.
182 MAKING THINGS TALK
10
2
3
4
9 8
Figure 6-1. New parts for this chapter: 1. Arduino wireless shield 2. Spark Fun XBee breakout board 3. 2mm female header pins
4. Arduino WiFi shield 5. Digi XBee 802.15.4 OEM module 6. Adafruit XBee-to-USB adapter 7. Spark Fun XBee Explorer 8. Infrared
LED 9. Arduno Fio. Don't forget plenty of male header pins for the breakout boards.
WIRELESS COMMUNICATION 183
»» 2 Arduino modules Arduino Fio models are a nice »» 2 LEDs D 160-1144-ND or 160-1665-ND, J 34761 or
alternative designed to work with XBees, but any Uno- 94511, F 1015878, RS 247-1662 or 826-830, SF COM-
compatible board should work. 09592 or COM-09590
SF DEV-10116 »» 2 potentiometers Any analog sensor will work.
»» 2 Digi XBee 802.15.4 RF modules J 2113375, J 29082, SF COM-09939, F 350072, RS 522-0625
SF WRL-08664 , AF 128, F 1546394, SS WLS113A4M, »» 2 pushbuttons Any will do.
MS MKAD14 D GH1344-ND, J 315432, SF COM-10302, F 1634684,
»» 2 Arduino wireless shields You can opt to not use the RS 718-2213
shields and use the parts listed below instead. »» 2 220-ohm resistors D 220QBK-ND, J 690700, F
A A000064 or A000065. Alternative shields: 9337792, RS 707-8842
SF WRL-09976, AF 126, F 1848697, RS 696-1670, SS »» 2 10-kilohm resistors D 10KQBK-ND, J 29911,
WLS114A0P F 9337687, RS 707-8906
»» 2 potentiometers J 29082, SF COM-09939, F 350072, »» 1 FTDI USB-to-Serial adapter Both the 5V or 3.3V
RS 522-0625 versions will work; these come as cables or standalone
»» 1 USB-XBee adapter modules. SF DEV-09718 or DEV-09716, AF 70, A
The following parts are only necessary if you are not A000059, MS MKAD22, SS PRO101D2P, D TTL-232R-
using Wireless shields. 3V3 or TTL-232R-5V
J 32400, SF WRL-08687, AF 247 »» 2 Bluetooth Mate modules SF WRL-09358 or WRL-
»» 2 3.3V regulators J 242115, D 576-1134-ND, SF COM- 10393
00526, F 1703357, RS 534-3021
»» 2 1µF capacitors J 94161, D P10312-ND, F 8126933, PROJECT 12: Hello WiFi!
RS 475-9009 »» 1 Arduino WiFi shield A A000058
»» 2 10µF capacitors J 29891, D P11212-ND, F 1144605, »» 1 Arduino module Get something based on the Arduino
RS 715-1638 Uno, but the project should work on other Arduino and
»» 2 XBee breakout boards J 32403, SF BOB-08276, Arduino-compatible boards.
AF 127 D 1050-1019-ND, J 2121105, SF DEV-09950,
»» 4 rows of 0.1-inch header pins J 103377, D A26509- A A000046, AF 50, F 1848687, RS 715-4081,
20ND, SF PRT-00116, F 1593411 SS ARD132D2P, MS MKSP4
»» 4 2mm female header rows J 2037747, D 3M9406- »» 1 WiFi Ethernet connection to the Internet
ND, F 1776193 »» 3 10-kilohm resistors D 10KQBK-ND, J 29911,
»» 6 LEDs D 160-1144-ND or 160-1665-ND, J 34761 or F 9337687, RS 707-8906
94511, F 1015878, RS 247-1662 or 826-830, SF COM- »» 3 photocells (light-dependent resistors) D PDV-
09592 or COM-09590 P9200-ND, J 202403, SF SEN-09088, F 7482280,
RS 234-1050
PROJECT 11: Bluetooth Transceivers »» 1 solderless breadboard D 438-1045-ND, J
»» 2 Arduino modules Get something based on the 20723 or 20601, SF PRT-00137, F 4692810, AF 64,
Arduino Uno, but the project should work on other SS STR101C2M or STR102C2M, MS MKKN2
Arduino and Arduino-compatible boards. »» 3 lighting filters One primary red, one primary green,
D 1050-1019-ND, J 2121105, SF DEV-09950, and one primary blue. Available from your local lighting-
A A000046, AF 50, F 1848687, RS 715-4081, SS or photo-equipment supplier.
ARD132D2P, MS MKSP4
»» 2 solderless breadboards D 438-1045-ND, J 20723
or 20601, SF PRT-00137, F 4692810, AF 64, SS
STR101C2M or STR102C2M
184 MAKING THINGS TALK
The early part of this chapter covers how wireless works covers the tip of the iceberg. For that reason, the exercises
and what makes it stop working, giving you some back- in this chapter will be less fully developed applications than
ground and starting places for troubleshooting. The the previous ones. Instead, you’ll just get the basic “Hello
second half of the chapter contains examples. The topic World!” example for several forms of wireless device.
is so broad, even a survey of several different devices only X
Wireless communication is never as reliable radios consume extra power when they’re transmitting.
as wired communication This causes a slight dip in the voltage of the power source.
You have less control over the sources of interference. If the radio isn’t properly decoupled with a capacitor
You can insulate and shield a wire carrying data com- across its power and ground leads, the voltage can dip
munications, but you can never totally isolate a radio or low enough to make the radio reset itself. The radio may
infrared wireless link. There will always be some form of appear to function normally when you’re sending it serial
interference, so you must make sure that all the devices messages, but it will never transmit, and you won’t know
in your system know what to do if they get a garbled why. When you start to develop wireless projects, it’s
message, or no message at all, from their counterparts. good practice to first make sure that you have the com-
munication working using a regulated, plugged-in power
Wireless communication is never just supply, and then create a stable battery supply.
one-to-one communication
The radio and infrared devices mentioned here Wireless communication generates
broadcast their signals for all to hear. Sometimes that electromagnetic radiation
means they interfere with the communication between This is easy to forget about, but every radio you use
other devices. For example, Bluetooth, most WiFi radios emits electromagnetic energy. The same energy that
(802.11b, g, and n), and ZigBee (802.15.4) radios all work cooks your food in a microwave sends your mp3 files
in the same frequency range: 2.4 gigahertz (802.11n will across the Internet. And while there are many studies
also work at 5GHz). They’re designed to not cause each indicating that it’s safe at the low operating levels of the
other undue interference, but if you have a large number radios used here, why add to the general noise if you
of ZigBee radios working in the same space as a busy don’t have to?
WiFi network, for example, you’ll get interference.
Make the wired version first
Wireless communication does not mean wireless power The radio and IR transceivers discussed here are
You still have to provide power to your devices, and if replacements for the communications wires used in
they’re moving, this means using battery power. Batteries previous chapters. Before you decide to add wireless
add weight, and they don’t last forever. The failure of a to any application, it’s important to make sure you’ve
battery when you’re testing a project can cause all kinds got the basic exchange of messages between devices
of errors that you might attribute to other causes. A working over wires first.
classic example of this is the “mystery radio error.” Many X
WIRELESS COMMUNICATION 185
receiver picks up all IR light but filters out anything that’s usually done at a low data rate, typically between 500 and
not vibrating at the carrier frequency. Then it filters out the 2,000 bits per second. It’s not great for high-bandwidth
carrier frequency, so all that’s left is the data signal. This data transmission, but if you’re only sending the values
method allows you to transmit data using infrared light of a few pushbuttons on a remote, it’s acceptable. Unlike
without getting interference from other IR light sources— the serial protocols you’ve seen so far in this book, IR
unless they happen to be oscillating at the same frequency protocols do not all use an 8-bit data format. For example,
as your carrier wave. Sony’s Control-S protocol has three formats: 12 bit, 15 bit,
and 20 bit. Philips’ RC5 format, common to many remotes,
The directional nature of infrared makes it more limited, uses a 14-bit format.
but cheaper than radio, and requires less power. As radios
get cheaper, more power-efficient, and more robust, it’s If you have to send or receive remote control signals,
less common to see an IR port on a computer. However, you’ll save a lot of time by looking for a specialty IR
it’s still both cost-effective and power-efficient for line-of- modulator chip to do the job, rather than trying to recreate
sight remote control applications. the protocol yourself. Fortunately, there are many good
sites on the Web that explain the various protocols.
Data protocols for the IR remote controls of most home Reynolds Electronics (www.rentron.com) has many helpful
electronics vary from manufacturer to manufacturer. To tutorials, and sells a number of useful IR modulators
decode them, you need to know both the carrier frequency and demodulators. EPanorama has a number of useful
and the message structure. Most commercial IR remote links describing many of the more common IR protocols
control devices operate using a carrier wave between 38 at www.epanorama.net/links/irremote.html. There are
and 40 kHz. The carrier wave’s frequency limits the rate at also a number of libraries written for Arduino to help you
which you can send data on that wave, so IR transmission is send and receive IR signals for different protocols. Many
Even though you can’t see infrared light, cameras can. If you’re not sure whether your IR LED is working, one quick way to check
is to point the LED at a camera and look at the resulting image. If it’s working, you’ll see the LED light up. Figure 6-3 shows the
IR LED in a home remote control, viewed through a webcam attached to a personal computer. You can even see this in the LCD
viewfinder of a digital camera. If you try this with your IR LED, you may need to turn the lights down or close the curtains to see
this effect. Some webcams have a built-in IR filter, so it’s good to first check with an IR device that you know works, like a remote
control, before you use it to detect whether your project is working.
of them are listed on the Arduino playground at http:// LED, and a receiver that listens for the carrier wave and
arduino.cc/playground/Main/InterfacingWithHardware. demodulates the data signal. It’s possible to build your
You’ll see one in action in the next project. own IR modulator using a 555 timer IC, but there are a
number of inexpensive modules you can buy to modulate
If you’re building both the transmitter and receiver, your or demodulate an IR signal as well.
job is fairly straightforward. You just need an oscillator X
through which you can pass your serial data to an infrared
MATERIALS
1 5 10 15 20
»» 1 solderless breadboard
A
B »» 1 220-ohm resistor
C
D
E
»» 1 phototransistor Digi-Key part no. 365-1068-ND.
»» 1 LED
F
G »» 1 battery or power source 5V or less.
H
I »» 1 oscilloscope DSO nano shown here.
J
1 5 10 15 20
the scope until you see readable activity. Most scopes will
220Ω tell you the frequency of the signal automatically. Putting
your scope in single-shot trigger mode will help you capture
the actual signal. Once you can see the timing of each
signal’s pulse, you can work out how to duplicate it by gen-
erating your own pulses on an IR LED. For more on this, see
many of the excellent blog posts on IR remote control using
an Arduino. For example, read Ken Shirriff’s very good expla-
Figure 6-5. An IR phototransistor and LED in series work nation on his blog, at www.arcfn.com.
well to test IR reception.
188 MAKING THINGS TALK
Project 9
The circuit for this project is simple. Connect the push- +5V D12
Gnd D11/PWM
button to pin 4 of the microcontoller (with a 10-kilohm
Gnd D10/PWM
pulldown resistor), and connect the infrared LED to pin 3
Vin D9/PWM
of the microcontroller, as shown in Figure 6-6.
D8
Arduino
Module
Download the Multi Camera IR Control library from http:// D7 +5V
sebastian.setz.name/arduino/my-libraries/multi-camera- D6/PWM
ir-control and copy it to the libraries directory of your Analog0 D5/PWM pushbutton
before, you’ll need to create this directory. One it’s there, A2 D3/PWM
A3 D2
restart the Arduino application, and you should see a new 220Ω 10kΩ
A4 Digital1/TX
library in the Sketch menu’s Import Library submenu
A5 Digital0/RX
called MultiCameraIrControl. Now you’re ready to get
IR LED
going.
X
Figure 6-6
The microcontroller with an IR LED and pushbutton attached.
MADE
I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
DIGITAL (PWM ~)
-
L 1 5 10 15 20 25 30
TX
+ UNO ON
A
B
RX ARDUINO C
D
E
RESET-EN
RESET ICSP
W W W.A RDUINO.CC
F
G
H
I
J
POWER ANALOG IN 1 5 10 15 20 25 30
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
WIRELESS COMMUNICATION 189
8
The setup method initializes the void setup(){
pushbutton as an input. // initialize the pushButton as input:
pinMode(pushButtonPin, INPUT);
}
8
The main loop listens for the
pushbutton’s state to change. Since void loop(){
you don’t want the camera firing all the // read the pushbutton input pin:
time, trigger the camera only when the buttonState = digitalRead(pushButtonPin);
pushbutton changes from OFF to ON.
To do that, compare the button’s state // compare the buttonState to its previous state
to its previous state by storing the // if it's changed, and it's high now, then the person
current state as the previous state at // just punched the button:
the end of each loop. if (buttonState != lastButtonState && buttonState == HIGH) {
// send the signal to open the shutter:
That’s the whole program. Now point camera.shutterNow();
the LED at your camera and start }
taking some pictures remotely. You // save the current state as the last state,
may have to set your camera to remote //for next time through the loop
control mode. Check the camera lastButtonState = buttonState;
manual for how to do this, as it’s }
different from camera to camera.
190 MAKING THINGS TALK
Figure 6-7
This intervalometer was built using
the same methods as shown above.
A An Arduino in the box senses a
change from the PIR sensor and
sends an IR signal to the camera to
take a picture.
A. PIR sensor
The distance that you can transmit a radio signal depends Antenna length = 5,616 in. / frequency in MHz =
on the signal strength, the sensitivity of the receiver, the 14,266.06 cm. / frequency in MHz
nature of the antennas, and any obstacles that block the
signal. The stronger the original current and the more
sensitive the receiver, the farther apart the sender and For more information, consult the technical specifications
receiver can be. The two wires act as antennas. Any for the specific radios you’re using. Instructions on making
conductor can be an antenna, but some work better than a good antenna are common in a radio’s documentation.
others. The length and shape of the antenna and the
frequency of the signal all affect transmission. Antenna Radio Transmission: Digital and Analog
design is a whole field of study on its own, so I can’t do it As with everything else in the microcontroller world, it’s
justice here, but a rough rule of thumb for a straight wire important to distinguish between digital and analog radio
antenna is as follows: transmission. Analog radios simply take an analog electri-
cal signal, such as an audio signal, and superimpose it
WIRELESS COMMUNICATION 191
on the radio frequency in order to transmit it. The radio those signals is very short compared to lower frequency
frequency acts as a carrier wave, carrying the audio signal. signals. To cook food, microwave ovens generate energy
Digital radios superimpose digital signals on the carrier in this range to excite (heat up) the water molecules in
wave, so there must be a digital device on either end to food. Some of that energy leaks from the oven at low
encode or decode those signals. In other words, digital power, which is why you get all kinds of radio noise in the
radios are basically modems, converting digital data to gigahertz range around a microwave.
radio signals, and radio signals back into digital data.
Motors and generators are especially insidious sources of
Radio Interference radio noise. A motor also operates by induction; specifi-
Though the antennas you’ll use in this chapter are omni- cally, by spinning a pair of magnets around a shaft in the
directional, radio can be blocked by obstacles, particularly center of a coil of wire. By putting a current in the wire,
metal ones. A large metal sheet, for example, will reflect a you generate a magnetic field, which attracts or repulses
radio signal rather than allowing it to pass through. This the magnets, causing them to spin. Likewise, by using
principle is used not only in designing antennas, but also in mechanical force to spin the magnets, you generate a
designing radio frequency (RF) shields. If you’ve ever cut current in the wire. So, a motor or a generator is essen-
open a computer cable and encountered a thin piece of tially a little radio, generating noise at whatever frequency
foil wrapped around the inside wires, you’ve encountered it’s rotating.
an RF shield. Shields are used to prevent random radio
signals from interfering with the data being transmitted Because there are so many sources of radio noise,
down a wire. A shield doesn’t have to be a solid sheet there are many ways to interfere with a radio signal. It’s
of metal, though. A mesh of conductive metal will block important to keep these possible sources of noise in mind
a radio signal as well—if the grid of the mesh is small when you begin to work with radio devices. Knowledge of
enough. The effectiveness of a given mesh depends on common interference sources, and knowing how to shield
the frequency it’s designed to block. It’s possible to block against them, is a valuable tool in radio troubleshooting.
radio signals from a whole space by surrounding the space
with an appropriate shield and grounding the shield. You’ll Multiplexing and Protocols
hear this referred to as making a Faraday cage. The effect When you’re transmitting via radio, anyone with a com-
is named after the physicist Michael Faraday, who first patible receiver can receive your signal. There’s no wire
demonstrated and documented it. to contain the signal, so if two transmitters are sending
at the same time, they will interfere with each other. This
Sometimes radio transmission is blocked by unintentional is the biggest weakness of radio: a given receiver has no
shields. If you’re having trouble getting radio signals way to know who sent the signal it’s receiving. In contrast,
through, look for metal that might be shielding the signal. consider a wired serial connection: you can be reasonably
Transmitting from inside a car can sometimes be tricky sure when you receive an electrical pulse on a serial cable
because the car body acts as a Faraday cage. Putting the that it came from the device on the other end of the wire.
antenna on the outside of the car improves reception. You have no such guarantee with radio. It’s as if you were
Bodies of water block RF effectively as well. This is true for blindfolded at a cocktail party and everyone else there had
just about every radio housing. the same voice. The only way you’d know who was talking
to you was if each person clearly identified himself at the
All kinds of electrical devices emit radio waves as side beginning and end of his conversation, and no one inter-
effects of their operation. Any alternating current can rupted him during this time. In other words, it’s all about
generate a radio signal, even the AC that powers your protocols.
home or office. This is why you hear a hum when you
lay speaker wires in parallel with a power cord. The AC The first thing everyone at that cocktail party would have
signal is inducing a current in the speaker wires, and to do is agree on who speaks when. That way they could
the speakers are reproducing the changes in current as each have your attention for awhile. Sharing in radio com-
sound. Likewise, it’s why you may have trouble operating munication is called multiplexing, and this form of sharing
a wireless data network near a microwave oven. WiFi is called time-division multiplexing. Each transmitter gets
operates at frequencies in the gigahertz range, commonly a given time slot in which to transmit.
called the microwave range, because the wavelength of
192 MAKING THINGS TALK
Of course, it depends on all the transmitters being in sync. Radio Transmitters, Receivers, and
When they’re not, time-division multiplexing can still work Transceivers
reasonably well if all the transmitters speak much less
than they listen (remember the first rule of love and net- How do you know whether to choose a radio transmitter-
working from Chapter 1: listen more than you speak). If a receiver pair, or a pair of transceivers? The simplest
given transmitter is sending for only a few milliseconds in answer is that if you need feedback from the device to
each second, and if there’s a limited number of transmit- which you’re transmitting, then you need a transceiver.
ters, the chance that any two messages will overlap, or Most of the time, it’s simplest to use transceivers. In
collide, is relatively low. This guideline, combined with a fact, as transceivers have become cheaper to make (and
request for clarification from the receiver (rule number therefore sell), transmit-receive pairs are getting harder to
three), can ensure reasonably good RF communication. find.
Back to the cocktail party. If every person spoke in a There are many different kinds of data transceivers
different tone, you could distinguish each individual by her available. The simplest digital radio transceivers on the
tone. In radio terms, this is called frequency-division multi- market connect directly to the serial transmit and receive
plexing. It means that the receiver has to be able to receive pins of your microcontroller. Any serial data you send
on several frequencies simultaneously. But if there’s a out the transmit line goes directly out as a radio signal.
coordinator handing out frequencies to each pair of trans- Any pulses received by the transceiver are sent into your
mitters and receivers, it’s reasonably effective. microcontroller’s receive line. They’re simple to connect,
but you have to manage the whole conversation yourself.
Various combinations of time- and frequency-division If the receiving transceiver misses a bit of data, you’ll get
multiplexing are used in every digital radio transmission a garbled message. Any nearby radio device in the same
system. The good news is that most of the time you never frequency range can affect the quality of reception. As
have to think about it becausetthe radios handle it for you. long as you’re working with just two radios and no interfer-
ence, transceivers like this do a decent job. However, this is
Multiplexing helps transmission by arranging for transmit- seldom the case.
ters to take turns and to distinguish themselves based on
frequency, but it doesn’t concern itself with the content of Nowadays, most transceivers on the market implement
what’s being said. This is where data protocols come in. networking protocols, handling the conversation manage-
Just as you saw how data protocols made wired network- ment for you. The Bluetooth modem in Chapter 2 ignored
ing possible, you’ll see them come into play here as well. signals from other radios that it wasn’t associated with,
To make sure the message is clear, it’s common to use a and handled error-checking for you. The XBee radios you’ll
data protocol on top of using multiplexing. For example, use in the next project will do the same, and much more,
Bluetooth, ZigBee, and WiFi are nothing more than data which you’ll see in Chapter 7. They require you to learn a
networking protocols layered on top of a radio signal. All bit more in terms of networking protocols, but the benefits
three of them could just as easily be implemented on a you gain make them well worth that minor cost.
wired network (and, in a sense, WiFi is: it uses the same
TCP/IP layer that Ethernet uses). The principles of these The biggest difference between networked radios and
protocols are no different than those of wired networks, simple transceivers is that every device on a network has
which makes it possible to understand wireless data trans- an address. That means you have to decide which other
mission even if you’re not a radio engineer. Remember the device you’re speaking to, or whether you’re speaking to all
principles and troubleshooting methods you used when the other devices on the network.
dealing with wired networks, because you’ll use them
again in wireless projects. The methods mentioned here Because of the complications of network management, all
are just new tools in your troubleshooting toolkit. You’ll networked radios generally have two modes of operation:
need them in the projects that follow. command and data modes (as described in Chapter
2). When looking at the communications protocol for a
networked radio, one of the first things you’ll learn is how
to switch from command mode to data mode and back.
X
WIRELESS COMMUNICATION 193
Project 10
Figure 6-8
XBee breakout board, in various stages.
Bottom: bare board with necessary
headers. Top right: finished board. Top
left: finished board with XBee mounted.
Once you get the OK response, set the XBee’s address. The module should respond:
The XBee protocol uses either 16-bit or 64-bit long
addresses, so there are two parts to the address: the high 1234
word and the low word (in computer memory, two or more
bytes used for a single value are sometimes referred to as Next, set the XBee’s destination address (the address
a word). For this project, you’ll use 16-bit addressing and, to which it will send messages). Make sure you’re in
therefore, get to choose your own address. You’ll need only command mode (+++), then type ATDL\r.
the low word of the address to do this. Type:
You’ll likely get this:
ATMY1234\r
0
(Remember that \r indicates you should press Enter or
Return.) To confirm that you set it, type: The default destination address on these modules is 0.
The destination address is two words long, so to see
ATMY\r the high word, type:
ATDH\r
196 MAKING THINGS TALK
Figure 6-10
CoolTerm options menu. To use
CoolTerm to configure Digi radios (XBee
and otherwise), set Enter Key Emulation
to CR.
ATDL5678\r
ATDH0\r
ATID1111\r
OK
XBee to computer via USB-to-XBee adapter. There are XBee standalone. For this, XBee breakout boards work well,
many of these available. Figure 6-12 shows two models, the as does the XBee LilyPad board. The XBee LilyPad, the XBee
SparkFun XBee Explorer in red, and the XBee USB adapter Explorer Regulated (Spark Fun part no. WRL-09132) and the
board—available from Adafruit and Parallax—in blue. Adafruit XBee adapter kit (Adafruit part no. 126) all feature
built-in voltage regulators, so you can use your XBee with a
wider range of power supplies.
Figure 6-12. XBee accessories. Clockwise from top left: XBee USB adapter, XBee
Explorer, Arduino Fio, Arduino wireless shield, XBee LilyPad.
198 MAKING THINGS TALK
Once you’ve configured one of your radios, disconnect You can combine commands on the same line by separat-
your serial terminal program and unplug the board from ing them with commas. For example, to get both words of
your computer. Next, remove the XBee from the circuit, a module’s source address, type:
insert the second one, and configure it using the same
procedure. Don’t set a radio’s destination address to ATDL, DH\r
the same value of its source address, or it will only talk
to itself! You can use any 16-bit address for your radios. The module will respond with both words at once.
Here’s a typical configuration for two radios that will talk Likewise, to set both destination words and then make
to each other (don’t forget to add the WR to the last the module write them to its memory—so that it saves
command): the address when it’s turned off—type:
Radio 1 1234 5678 0 1111 The module will respond to all three commands at once:
Figure 6-13
To keep track of the radios, label them
with a piece of tape. You’ll be switching
them between the USB-to-Serial
adapter and the microcontroller a few
times, and it’s easy to lose track of
which is which.
WIRELESS COMMUNICATION 199
USB TX/RX
Figure 6-15 shows an XBee module attached to a
regular Arduino using the Arduino wireless shield.
Figure 6-16 shows how you’d do it if you were
Personal
using just an XBee breakout board instead of a
computer
shield. Note that the XBee is attached to a 3.3V
regulator. The XBee’s serial I/O connections are
5-volt tolerant, meaning they can accept 5-volt
data signals, but the module operates at 3.3
volts. The Arduino Uno and newer models have
a more robust 3.3V regulator that can power the
XBee, but it doesn’t hurt to add a dedicated one,
as shown here.
At right, above
Figure 6-14
XBee #1 is connected to the microcontroller. XBee #2
is connected via USB or serial to the PC. This enables a
wireless link between the PC and the microcontroller.
At right, below
Figure 6-15
Arduino and wireless shield with potentiometer attached
to analog pin 0. This circuit is the same as the one shown
in Figure 6-16, but it’s without the LED on pin 9. The LEDs
attached to the XBee are built into the shield.
WIRELESS COMMUNICATION 201
MADE
I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
DIGITAL (PWM ~)
-
L 1 5 10 15 20 25 30
TX
+ UNO ON
A
B
RX ARDUINO C
D
E
RESET-EN
RESET ICSP
W W W. A R DU I N O. CC
F
G
H
I
J
POWER ANALOG IN 1 5 10 15 20 25 30
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
220Ω
Xbee Radio
LD1117-33V
Voltage Reg
In Out
Vcc AD0 / DIO0
TX AD1 / DIO1
RX AD2 / DIO2
10µF 1µF
DO8 AD3 / DIO3
PWM1 Vref
220Ω
NC SLP
Make It First, give the I/O pins const int sensorPin = A0; // input sensor
names, and set up const int analogLed = 3; // LED that changes brightness w/incoming value
some variables for tracking the change const int threshold = 10; // threshold for sensor's change
in the potentiometer.
int lastSensorReading = 0; // previous state of the sensor
8 The blink() method is just like ones void blink(int thisPin, int howManyTimes) {
you’ve seen previously in this book. // Blink the LED:
It blinks an LED to indicate that setup for (int blinks=0; blinks< howManyTimes; blinks++) {
is over. digitalWrite(thisPin, HIGH);
delay(200);
digitalWrite(thisPin, LOW);
delay(200);
}
}
8
Two other methods are called void handleSerial() {
from the loop: handleSerial(), which char inByte = Serial.read();
listens for strings of ASCII numerals
and converts them to bytes in order to // save only ASCII numeric characters (ASCII 0 - 9):
set the brightness of the LED on the if (isDigit(inByte)){
PWM output; and readSensor(), which inputString = inputString + inByte;
reads the potentiometer and checks }
to see whether the change on it is high
enough to send the new value out via // if you get an ASCII newline:
radio. Here are those methods. if (inByte == '\n') {
// convert the string to a number:
int brightness = inputString.toInt();
// set the analog output LED:
analogWrite(analogLed, brightness);
// clear the input string for the
// next value:
inputString = "";
Serial.print(brightness);
}
}
int readSensor() {
»
int result = analogRead(sensorPin);
204 MAKING THINGS TALK
NOTE: You should disconnect the XBee’s // look for a change from the last reading
receive and transmit connections to the // that's greater than the threshold:
microcontroller while programming (if if (abs(result - lastSensorReading) > threshold) {
you’re using the Arduino wireless shield, result = result/4;
use the serial select switch). The serial lastSensorReading = result;
communications with the XBee can } else {
interfere with the serial communications // if the change isn't significant, return 0:
with the programming computer. Once the result = 0;
microcontroller’s programmed, you can re- }
connect the transmit and receive lines. return result;
}
In the main loop, notice that you’re not using Once you’ve programmed the microcontroller, set the des-
any AT commands. That’s because the XBee tination address on the computer’s XBee to the address
goes back into data mode (called idle mode in of the microcontroller’s radio. (If you did this in the earlier
the XBee user’s guide) automatically when you issue the step, you shouldn’t need to do it again.) Then, turn the
ATCN command in the setDestination() method. potentiometer on the microcontroller. You should get a
message like this in your serial terminal window:
Remember, in data mode, any bytes sent to an AT-style
modem go through as-is. The only exception to this rule 120
is that if the string +++ is received, the modem switches
to command mode. This behavior is the same as that of The actual number will change as you turn the potenti-
the Bluetooth module from Chapter 2, as well as almost ometer. It might overwrite itself in the serial window—
any device that implements this kind of protocol. It’s depending on your serial terminal application—because
great because it means that once you’re in data mode, you’re not sending a newline character. Congratulations!
you can send data with no extra commands, letting the You’ve made your first wireless transceiver link. Keep
radio itself handle all the error corrections for you. turning the potentiometer until you’re bored, then move on
to Step 3.
X
Figure 6-17
Arduino module powered by a 9V battery.
Figure 6-18
Detail of the Fio, showing battery connector and USB-to-Serial
adapter connected for programming.
Figure 6-19
LilyPad Arduino Simple, with the LiPo battery connector. Photo
courtesy of Spark Fun.
206 MAKING THINGS TALK
Project 11
Bluetooth Transceivers
In Chapter 2, you learned how to connect MATERIALS
RN-42
RN-42
Arduino #2: Bluetooth
Arduino #1: Bluetooth
module is communi-
module is communi-
cating with Arduino’s
cating with the PC
processor
Connect
Connect
Stat
Stat
through the USB-to-
serial processor
GND
GND
VCC
VCC
CTS
RTS
CTS
RTS
RX
RX
TX
TX
MADE MADE
I N I TA LY I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
9
8
7
6
5
4
3
2
TX 1
RX 0
AREF
13
12
11
10
GND
AREF
DIGITAL (PWM ~) DIGITAL (PWM ~)
- -
L L
TX
+ UNO ON TX
+ UNO ON
RX ARDUINO RX ARDUINO
RESET-EN
RESET-EN
RESET ICSP RESET ICSP
W W W. A R D U I N O. CC
W W W. A R D U I N O. CC
POWER ANALOG IN POWER ANALOG IN
RESET
RESET
3.3V
A0
A1
A2
A3
A4
A5
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
GND
GND
Vin
5V
5V
Figure 6-20
The Arduino module on the left is used as a USB-to-Serial adapter for a Bluetooth Mate module. Notice
how RX is attached to RX and TX to TX. That’s because the Bluetooth Mate is actually talking to the
PC through the USB-to-Serial adapter, not the Arduino’s main processor, so the serial connections are
reversed. When you want the Bluetooth module to talk to the Arduino’s main processor, you’ll swap
these two connections, as shown at right.
Program Arduino #2 using a basic serial sketch, as follows: • Step 2: Getting to Know the
void setup() {
Commands
Serial.begin(115200); The Bluetooth Mate radios use a serial command set for
} command and configuration, which has two modes—
command mode and data mode—just like the XBee radios.
void loop() { When you first power up a Bluetooth Mate and connect
Serial.println("Hello Bluetooth!"); to its serial interface (using Arduino #1 in Figure 6-20, for
} example), it’s in data mode. To see that it’s alive, type: $$$.
It will respond:
When you open a Bluetooth connection to this radio, you’ll
see the following message over and over: CMD\r
Once you’re in command mode, you can get some basic This is handy when you want only the other Bluetooth
information about the radio by typing D, just as you did in Mates in the area. As you might have guessed, the device
Chapter 2. You’ll get the radio’s status, which includes its code is 001F00. The IN command also eliminates the
address: text names, so you can get just the addresses and device
codes.
***Settings***
Now that you have the address of your other Bluetooth
BTA=000666112233 radio (which should have shown in the lists above, if you
BTName=FireFly-7256 have it plugged into the other Arduino), you can connect
Baudrt(SW4)=115K to it like so:
Parity=None
Mode =Slav C, 000666481ADF\r
Authen=0
Encryp=0 Replace 000666481ADF with the address of the radio
PinCod=1234 attached to Arduino #2. Radio #1 will respond:
Bonded=0
Rem=NONE SET TRYING
The first line beginning with BTA= is the radio’s address Once it makes a good connection, the green connect light
in hexadecimal notation. Write down this address or copy on both Bluetooth Mates should come on, the radios will
it to a text document—you’ll need it in a moment. Next, shift automatically to data mode, and you should see the
check its connection status by typing GK\r. It will respond message from Arduino #2 as follows:
like so:
Hello Bluetooth!
0 Hello Bluetooth!
Hello Bluetooth!
When it’s connected and you do this, it will respond with 1
instead. The connection goes both ways, of course. Anything you
type in the serial terminal window gets sent to Arduino #2.
Now you want to see which other radios are available. Type It’s not programmed to respond, though, so you won’t see
the following (the capital letter i): anything come back from it. When you’re ready to close
the connection, you first have to get back into command
I\r mode by typing:
You can see that each device has a different address, KILL
name, and device code. You can get a list of only the ones
with a particular address code by typing: There are other status commands as well, but these ones
are most important at first.
IN 0,001F00\r X
WIRELESS COMMUNICATION 209
First, get the Bluetooth addresses for both of your radios. NOTE: It’s a good idea to to remove your Bluetooth Mate while
You already wrote down one. Replace it with the second programming the Arduino boards, just as you’ve had to for other
radio in your Serial-to-USB circuit, and follow the same serial devices.
steps to get that radio’s address as well. While you’re
getting the addresses, make one extra configuration on When the pushbutton is pressed for the first time, the
both radios, as follows: following program connects to another Bluetooth Mate
with a set address. When it connects, it sends its potenti-
SO,BT\r ometer value as an ASCII string, terminated by
a carriage return.
This sets the status string to BT, so that when the radios
connect or disconnect, they’ll send a string to let you Just like the XBee example, this program also looks for
know, like this: incoming ASCII strings and converts them to use as a
PWM value to dim an LED on pin 3. It will take advantage
BTCONNECT\r of the TextFinder library that you saw in Chapter 4. If you
haven’t already installed it, do so now using the instruc-
or: tions from that chapter.
Figure 6-21
Bluetooth Mate radio attached to
an Arduino. This circuit is similar
to the XBee microcontroller circuit
discussed earlier. The pushbutton will
MADE
connect or disconnect the two radios.
RN-42
I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
DIGITAL (PWM ~)
-
L
1 5 10 15 20 25 30
TX
+ UNO ON
A
B
RX ARDUINO C
Connect
Stat
D
E
RESET-EN
RESET ICSP
W W W.ARDUIN O.CC
GND
VCC
F
CTS
RTS
RX
TX
G
H
I
J
POWER ANALOG IN 1 5 10 15 20 25 30
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
AREF
Reset GND
+3.3V D13
+5V D12
Gnd D11/PWM
Gnd D10/PWM
Vin D9/PWM
D8 +5V
Arduino
Module
D7 Connect/Disconnect switch
D6/PWM
+5V
or +3.3V 220Ω
RTS
RX
Bluetooth Mate TX
Module
VCC
CTS
Gnd
WIRELESS COMMUNICATION 211
8
The main loop listens for incoming void loop() {
serial data and checks to see whether // read incoming serial and parse it:
the button’s been pushed. If so, it handleSerial();
connects or disconnects as appropri-
ate. If the radios are connected, it // check to see if the pushbutton's pressed:
reads the analog input and sends it out boolean buttonPushed = buttonRead(connectButton);
if there’s been a significant change.
// if the button's just pressed:
if (buttonPushed) {
// if the client's connected, disconnect:
if (connected) {
BTDisconnect();
} // if the client's disconnected, try to connect:
else {
BTConnect();
}
}
// if connected, take sensor readings:
if (connected) {
// note the current time in milliseconds:
long currentTime = millis();
// if enough time has passed since the last reading:
if (currentTime - lastReadingTime > debounceInterval) {
// read the analog sensor, divide by 4 to get a 0-255 range:
int sensorValue = analogRead(A0)/4;
// if there's a significant difference between the
// current sensor reading and the last, send it out:
if (abs(sensorValue - lastSensorReading) > threshold) {
Serial.println(sensorValue, DEC);
}
// update the last reading time
// and last sensor reading:
lastReadingTime = currentTime;
lastSensorReading = sensorValue;
}
}
}
212 MAKING THINGS TALK
8 The blink() method is the same as void blink(int thisPin, int howManyTimes) {
it was in the earlier XBee example. for (int i=0; i< howManyTimes; i++) {
digitalWrite(thisPin, HIGH);
delay(200);
digitalWrite(thisPin, LOW);
delay(200);
}
}
8 The buttonRead() method will look // this method reads the button to see if it's just changed
familiar, too,—it’s the same one from // from low to high, and debounces the button in case of
the pong clients in Chapter 5. // electrical noise:
8
BTConnect() checks the void BTConnect() {
command/data mode status, then tries // if in data mode, send $$$
to make a connection. If the attempt if (!commandMode) {
fails, it stays in command mode. Serial.print("$$$");
// wait for a response:
if (finder.find("CMD")) {
commandMode = true;
}
}
// once you're in command mode, send the connect command:
if (commandMode) {
Serial.print("C," + remoteAddress + "\r");
// wait for a response:
finder.find("CONNECT");
// if the message is "CONNECT failed":
if (finder.find("failed")) {
connected = false;
}
else {
connected = true;
// radio automatically drops into data mode
// when it connects:
commandMode = false;
}
}
}
214 MAKING THINGS TALK
8
handleSerial() also looks for text void handleSerial() {
messages, but it doesn’t use TextFinder // look for message string
because it needs to be able to see one of // if it's BTCONNECT, connected = true;
three different options. TextFinder makes // if it's BTDISCONNECT, connected = false;
only one pass through the serial stream, // if it's CONNECT failed, connected = false;
so you can’t check for a second string if it // if it's a number, set the LED
doesn’t find the first string. char inByte = Serial.read();
If a valid number is found, this method // add any ASCII alphanumeric characters
uses it to set the brightness of the LED // to the message string:
on pin 3. if (isAscii(inByte)) {
messageString = messageString + inByte;
}
if (connected) {
// convert the string to a number:
int brightness = messageString.toInt();
»
// set the analog output LED:
WIRELESS COMMUNICATION 215
Buying Radios
You’ve seen a few different kinds of wireless modules in this chapter. Though they
do the job well, they’re not the only options on the market. You should definitely shop
around for modules that suit your needs. Here are a few things to consider when
choosing your radios.
The wisest thing you can do when buying your radios mance devices like samplers and lighting dimmers. You
is to buy them as a set. Matching a transmitter from might think that you need your radios to work at MIDI data
one company to a receiver from another is asking for rates to do this, but you don’t. You can send the sensor
headaches. They may say that they operate in the same data from the performers wirelessly at a low data rate to a
frequency range, but there’s no guarantee. Likewise, stationary microcontroller, then have the microcontroller
trying to hack an analog radio—such as that from a baby send the data via MIDI at a higher data rate.
monitor or a walkie-talkie—may seem like a cheap and
easy solution, but in the end, it’ll cost you time and eat Consider the protocols of the devices that you already
your soul. When looking for radios, look for something that have at your disposal. For example, if you’re building an
can take the serial output of your microcontroller. Most object to speak to a mobile phone or a laptop computer,
microcontrollers send serial data at TTL levels, with 0V for and there’s only one object involved, consider Bluetooth.
logic 0 and 3.3V or 5V for logic 1. Converting the output to Most laptops and many mobile phones already have
RS-232 levels is also fairly simple, so radios that can take Bluetooth radios onboard, so you’ll need only one radio
those signals are good for your purposes. to do the job. It may take some work to make your object
compatible with the commands specific to your existing
Consider the data rate you need for your application—more devices, but if you can concentrate on that instead of on
specifically, for the wireless part of it. You may not need getting the RF transmission consistent, you’ll save a lot of
high-speed wireless. One common use for wireless com- time.
munication in the performance world is to get data off X
the bodies of performers, in order to control MIDI perfor-
Until recently, WiFi wasn’t very common in microcon- There are currently a few WiFi solutions on the market.
troller projects for a couple reasons: cost and power. Spark Fun makes the WiFly shield, and Digi just announced
Microcontroller-to-WiFi modules on the market are more WiFi versions of their XBee modules. There’s also a forth-
expensive than equivalent transceivers implementing coming Arduino WiFi shield, which is designed to be easy
other protocols. That’s starting to change. Many earlier to incorporate into an existing Ethernet project with only
WiFi modules were also power hungry, but that too is minor code changes. A short introduction follows.
changing. X
WIRELESS COMMUNICATION 217
Project 12
Hello WiFi!
Remember the daylight color server you MATERIALS
Server server(80);
int lineLength = 0; // length of the incoming text line
8
The setup() looks different from void setup() {
the previous sketch because you’re // initialize serial:
setting up a WiFi connection instead Serial.begin(9600);
of a wired Ethernet connection. If you
get a connection, print out the network Serial.println("Attempting to connect to network...");
name. If you don’t, stop the program // attempt to connect using WPA encryption:
right there. The WiFi shield uses DHCP status = WiFi.begin(ssid, password);
by default, so you don’t need to do
anything in your code to get an address // or use this to attempt to connect using WEP 128-bit encryption:
via DHCP. // status = WiFi.begin(ssid, keyIndex, key);
If you’re working at a school or business where you don’t Here’s how to get the signal strength once you’re attached
control the WiFi routers, make sure you have all the config- to a network:
uration information in advance, and that it matches what
your module can do. Enterprise protocols like WPA2 Enter- // print the received signal strength:
prise are not available for microcontroller-based modules. long rssi = WiFi.RSSI();
Serial.print("RSSI:");
Some public networks use a captive portal, which is an Serial.println(rssi);
open WiFi network, but you have to sign in through a web
page before you can access the wider Internet. These Both of these techniques are handy diagnostic tools.
are difficult to handle, because you have to program the Depending on your environment and network setup, your
microcontroller (not the WiFi module) to make an HTTP wireless network may not be stable all the time. Likewise,
call to the captive portal with the login information first. If you may want to wrap your whole main loop() in an if
you can use a network that doesn’t use a captive portal, statement that checks whether you're still connected to
you’re better off. the network, like so:
Some WiFi modules, like the Arduino WiFi shield, can’t see void loop() {
networks where the SSID is hidden. When possible, make if ( status == WL_CONNECTED) {
sure your network is publicly visible—even when security // do everything here
is on. } else {
// let the user know there's no connection
Since you have no interface to get feedback on errors, }
compare your configuration with that of your laptop, mobile }
phone, or other device that you can connect successfully. X
Conclusion
Wireless communication involves some significant differences from wired communication.
Because of the complications, you can’t count on the message getting through like you
can with a wired connection, so you have to decide what you want to do about it.
If you opt for the least-expensive solutions, you can just own error-checking routines but, increasingly, wireless
implement a one-way wireless link with transmitter-receiver protocols like Bluetooth and ZigBee are making it possible
pairs and send the message again and again, hoping that for you to forget about that, because the modules that
it’s eventually received. If you spend a little more money, implement these protocols include their own error correc-
you can implement a duplex connection, so that each tion.
side can query and acknowledge the other. Nowadays, a
duplex connection is the standard, as the cost difference Just as you started learning about networks by working
is minimal and the availability of transmitter-receiver pairs with the simplest one-to-one network in Chapter 2, you
is waning. Regardless of which method you choose, you began with wireless connections by looking at simple pairs
have to prepare for the inevitable noise that comes with a in this chapter. In the next chapter, you’ll look at peer-to-
wireless connection. If you’re using infrared, incandescent peer networks, in which there is no central controller, and
light and heat act as noise; if you’re using radio, all kinds each object on the network can talk to any other object.
of electromagnetic sources act as noise, from microwave You’ll see both Ethernet and wireless examples.
ovens to generators to cordless phones. You can write your X
Sessionless Networks
So far, the network connections you’ve seen in this book have mostly
been dedicated connections between two objects. Serial communica-
tions involve the control of a serial port; mail, web, and telnet connections
involve a network port. In all these cases, there’s a device that makes the
port available (generally a server), and something that requests access to
the port (a client). Project 8, Networked Pong, in Chapter 5 was a classic
example of this—in that application, the server handled all the commu-
nications between the other devices. In this chapter, you’ll learn how to
make multiple devices on a network talk to each other directly,
or talk to all the other devices at once.
8
2
4 3
Figure 7-1. New parts for this chapter: 1. Charley Chimp 2. 2N3906 transistor 3. MAX8212 Voltage trigger 4. Hanwei gas sensors
5. Gas sensor breakout board 6. Trimmer potentiometer 7. Solar cell 8. Don't forget plenty of male header pins for the breakout boards.
226 MAKING THINGS TALK
Sessions Versus Messages other object on a given subnet. For example, if your
In Chapter 5, you learned about the Transmission Control address is 192.168.1.45, and you send a UDP message
Protocol, TCP, which is used for much of the communica- to 192.168.1.255, everybody on your subnet receives
tion on the Internet. To use TCP, your device has to request the message. Because this is such a handy thing to
a connection to another device. The other device opens do, a special address is reserved for this purpose:
a network port, and the connection is established. Once 255.255.255.255. This is the limited broadcast address—it
the connection is made, information is exchanged; then, goes only to addresses on the same LAN, and does not
the connection is closed. The whole request-connect- require you to know your subnet address. This address is
converse-disconnect sequence constitutes a session. If useful for tasks such as finding out who’s on the subnet.
you want to talk to multiple devices, you have to open and
maintain multiple sessions. Sessions characterize TCP The advantage of UDP is that data moves faster because
communications. there’s no error-checking. It’s also easier to switch the end
device that you’re addressing on the fly. The disadvantage
Not all network communication is session-based. There’s is that it’s less reliable byte-for-byte, as dropped packets
another protocol used on the Internet, called the User aren’t resent. UDP is useful for streams of data where
Datagram Protocol, or UDP. With UDP, you compose a there’s a lot of redundant information, like video or audio.
message, give it an address, send it, and forget about it. If a packet is dropped in a video or audio stream, you may
notice a blip, but you can still make sense of the image or
Unlike the session-based TCP, UDP communication is all sound.
about messages. UDP messages are called datagrams.
Each datagram is given a destination address and The relationship between TCP and UDP is similar to the
is sent on its merry way. There is no two-way socket relationship between Bluetooth and 802.15.4. Bluetooth
connection between the sender and receiver. It’s the devices have to establish a session to each other to com-
receiver’s responsibility to decide what to do if some of municate, whereas 802.15.4 radios (like the XBee radios
the datagram packets don’t arrive, or if they arrive in the in Chapter 6) communicate simply by sending addressed
wrong order. messages out to the network without waiting for a result.
Like TCP, Bluetooth is reliable for byte-critical applications,
Because UDP doesn’t rely on a dedicated one-to-one but it's less flexible in its pairings than 802.15.4.
connection between sender and receiver, it’s possible X
to send a broadcast UDP message that goes to every
SESSIONLESS NETWORKS 227
Querying for Other Devices Using by Stephane Cousot available from the Processing.
org's libraries page at http://processing.org/reference/
UDP libraries/#data_protocols. To use it, download it and make
Arduino's Ethernet library includes the ability to send and a new directory called udp in the libraries subdirectory of
receive UDP packets, so you can use it to write a simple your Processing sketch directory. Then unzip the contents
sketch that listens for broadcast messages and responds of the download and drop them in the directory you
to them. It's useful when you want to make a large number created. After that, restart Processing and you’re ready to
of networked devices all respond at once. You can use Pro- use the UDP library.
cessing to send your broadcast query.
Any Arduino with an Ethernet shield connected to your
There’s no way to send UDP messages using the Process- network will do for this exercise. You don't need any extra
ing Network library, but there’s a good free UDP library hardware other than the shield.
It doesn't matter what the IP address UDP udp; // initialize the UDP object
or router of the machine running
this sketch is, because it uses the void setup() {
special subnet broadcast address: udp = new UDP( this, 43770 ); // open a UDP port
255.255.255.255. udp.listen( true ); // listen for incoming messages
}
Unlike session-based messaging,
where you wrote and read bytes from a void draw()
stream like serial communication, UDP {
messages are all sent with one discrete }
message, udp.send(), which includes
the address and port for sending. void keyPressed() {
String ip = "255.255.255.255"; // the remote IP address
int port = 43770; // the destination port
udp.send("Hello!\n", ip, port ); // the message to send
»
}
228 MAKING THINGS TALK
Respond To It Here's an /*
Arduino UDP Query Responder
sketch that listens for UDP messages Context: Arduino
on the same port and responds in kind. */
Load it onto an Arduino connected to
your network with an Ethernet shield. #include <SPI.h>
#include <Ethernet.h>
#include <Udp.h>
88Change these to match your own device // Enter a MAC address and IP address for your controller below.
and network. // The IP address will be dependent on your local network:
byte mac[] = {
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 };
IPAddress myIp(192,168,1,20);
unsigned int myPort = 43770; // local port to listen on
void setup() {
// start the serial library:
Serial.begin(9600);
query.begin(myPort);
// give the Ethernet shield a second to initialize:
delay(1000);
»
}
SESSIONLESS NETWORKS 229
8 The loop() just calls the listen() Continued from opposite page.
method, which listens for incoming
UDP packets on the same port on void loop()
which the Processing sketch broad- {
casts. listen(query, myPort);
}
88First, you parse the packet
Receiving UDP packets is a bit different to get the header items.
than receiving TCP packets. Each void listen(UDP thisUDP, unsigned int thisPort) {
packet contains a header that tells you // check to see if there's an incoming packet, and
who sent it and from what port, kind // parse out the header:
of like an envelope. When you receive int messageSize = thisUDP.parsePacket();
a packet, you have to parse out that // if there's a payload, parse it all out:
data. The parsePacket() method in if (messageSize > 0) {
the Arduino UDP library does just that. Serial.print("message received from: ");
You can see it in action here. First, you // get remote address and port:
parsePacket() to separate the header IPAddress yourIp = thisUDP.remoteIP();
elements from the message body. unsigned int yourPort = thisUDP.remotePort();
Then, you read the message body byte- for (int thisByte = 0; thisByte < 4; thisByte++) {
by-byte, just like you've done already Serial.print(yourIp[thisByte], DEC);
88Then, you read the rest of
with TCP sockets and serial ports. Serial.print(".");
the message body.
}
Serial.println(" on port: " + String(thisPort));
// send the payload out the serial port:
while (thisUDP.available() > 0) {
// read the packet into packetBufffer
int udpByte = thisUDP.read();
Serial.write(udpByte);
}
sendPacket(thisUDP, Ethernet.localIP(), yourIp, yourPort);
}
}
8
The sendPacket() method sends a void sendPacket(UDP thisUDP, IPAddress thisAddress,
response packet to whatever address IPAddress destAddress, unsigned int destPort) {
and port it receives a message from. It // set up a packet to send:
includes its IP address in the body of thisUDP.beginPacket(destAddress, destPort);
the message as an ASCII string. for (int thisByte = 0; thisByte < 4; thisByte++) {
// send the byte:
You can see that UDP messaging thisUDP.print(thisAddress[thisByte], DEC);
is different than the socket-based thisUDP.print(".");
messaging over TCP. Each message }
packet has to be started and ended. thisUDP.println("Hi there!");
When you beginPacket(), the Ethernet thisUDP.endPacket();
controller starts saving bytes to send in }
its memory; when you endPacket(), it
sends them out.
230 MAKING THINGS TALK
When you've got the Arduino programmed, open a serial The first Hello! is from Processing itself. When you send
connection to it using the Serial Monitor. You should see a a broadcast message, it comes back to you as well!
message like this in the Arduino Serial Monitor when the The second line is from the Arduino. If you have several
Arduino obtains an IP address: Arduinos on your network all running this sketch, you'll get
a response from each one of them. In fact, this exercise is
192.168.1.20. most satisfying when you have multiple units responding.
Next, run the Processing sketch and type any key. In the This is a handy routine to add to any Ethernet-based
Arduino Serial Monitor, you should see: project. You have to provide a separate UDP instance and
port to listen on, but the sendPacket() method can work
message received from: 192.168.1.1. on port: 43770 with other programs to get a response from your device
Hello! when you send broadcast queries.
X
The address will be your computer's IP address. In the
Processing monitor pane, you should see:
Hello!
192.168.1.20.Hi there!
Querying for XBee Radios Once you’ve got the radios connected and working, open
a serial terminal connection to one of them and issue
Using 802.15.4 Broadcast the following command: +++. Then, wait for the radio to
Messages respond with OK. Then type (remember, \r means carriage
return, so press Enter or Return instead of \r): ATND\r.
Just as you can query a subnet to discover devices using
UDP, you can also query an XBee personal area net. The If there are other XBee radios on the same personal
XBee radios have a command to query the air for any area network in range, the radio will respond after a few
available radios. This is referred to as node discovery. seconds with a string like this:
When given the AT command ATND\r, the XBee radio sends
out a broadcast message requesting that all other radios 1234
on the same personal area network (PAN) identify them- 13A200
selves. If a radio receives this message, it responds with its 400842A7
source address, serial number, received signal strength, 28
and node identifier. TIGOE1
NOTE: To do node discovery, your radios must have version 10A1 5678
or later of the XBee firmware. See the sidebar "Upgrading the 13A200
Firmware on XBee Radios" for more details. 400842A9
1E
For the purposes of this exercise, you’ll need at least two TIGOE3
XBee radios connected to serial ports on your computer.
The easiest way to do this is by using a USB-to-XBee Serial
adapter like the XBee Explorer.
SESSIONLESS NETWORKS 231
Each grouping represents a different radio. The first Replace myname with the name you want.
number is the radio’s source address (the number you get
when you send it the command string ATMY). The second Broadcast messages are useful for many reasons.
is the high word of the radio’s serial number; the third is However, they should be used sparingly because they
the low word. The fourth number is a measurement of the create more traffic than is necessary. In the next project,
radio’s received signal strength—in other words, it tells you’ll use broadcast messages to reach all the other
you how strong the radio signal of the query message was objects in a small, closed network.
when it arrived at the receiving radio. The final line gives
the radio’s node identifier. This is a text string, up to 20
characters long, that you can enter to name the radio. You
didn’t use this function in Chapter 6, so your radios may
not have node identifier strings. If you want to set the node
identifier for further use, type: ATNI myname, WR\r
Project 13
Figure 7-3
The completed toxic sensor system: sensor, monkey,
and network connection.
MATERIALS
Cymbal Monkey Circuit
»» 1 USB-to-XBee serial adapter »» 1 solderless breadboard
»» 1 Digi XBee OEM RF module
Sensor Circuit »» 1 cymbal monkey
»» 1 solderless breadboard
»» 1 Digi XBee OEM RF module NOTE: If your monkey uses a 3V power supply (such as two
»» 1 5V regulator D batteries), you won’t need the 3.3V regulator. Make sure
»» 1 3.3V regulator that there’s adequate amperage supplied for the radios. If you
»» 1 9–12V DC power supply Either a 9V battery or connect the circuit as shown and the radios behave erratically,
plug-in supply will do. the monkey’s motor may be drawing all the power. If so, use a
»» 1 XBee breakout board separate power supply for the radio circuit.
»» 2 rows of 0.1-inch header pins
»» 2 2mm female header rows »» 1 3.3V regulator
»» 1 1µF capacitor »» 1 XBee breakout board
»» 1 10µF capacitor »» 2 rows of 0.1-inch header pins
»» 1 Hanwei gas sensor »» 2 2mm female header rows
»» 1 gas sensor breakout board »» 2 LEDs
»» 2 LEDs »» 2 220-ohm resistors
»» 2 220-ohm resistors »» 1 10K trimmer potentiometer
»» 1 10-kilohm resistor »» 1 TIP120 Darlington NPN transistor.
»» 1 1N4004 power diode
Internet Connection Circuit »» 1 1-kilohm resistor
»» 1 Arduino microcontroller module »» 1 100µF capacitor
»» 1 Arduino Ethernet shield
»» 1 Digi XBee OEM RF module
»» 1 Arduino wireless shield If you use this, you won't
need the rest of the parts listed below. They are all for
connecting the XBee to your Arduino.
»» 1 solderless breadboard
»» 1 3.3V regulator
»» 1 1µF capacitor
»» 1 10µF capacitor
»» 1 XBee breakout board
»» 2 rows of 0.1-inch header pins
»» 2 2mm female header rows
»» 2 LEDs
»» 2 220-ohm resistors
234 MAKING THINGS TALK
You’ll be building three separate circuits for this project, so • ATID1111: Sets the PAN.
the parts list is broken down for each one. Most of these • ATP02: Sets PWM pin 0 (P0) to act as a PWM output.
items are available at retailers other than the ones listed • ATIU1: Sets the radio to send any I/O data packets out
here,. the serial port. This is used for debugging purposes
only; you won’t actually attach anything to this radio’s
Radio Settings serial port in the final project.
Connect one of the radios to the USB-to-XBee serial • ATIA01 or ATIAFFFF: Sets the radio to set its PWM
adapter. You’ll use this for configuring the radios only. outputs using any I/O data packets received from
You’ve got three radios: the sensor’s radio, the monkey’s address 01 (the sensor radio’s address). If you set this
radio, and the Arduino's radio. In Chapter 6 you saw how parameter to FFFF, the radio sets its PWM outputs
to configure the radios’ addresses, destination addresses, using data received from any radio on the PAN.
and Personal Area Network (PAN) IDs. In this project, you'll
see how to configure some of their I/O pins' behavior. The Arduino's radio listens for messages on the PAN and
For example, you can configure the digital and analog I/O sends them out its serial port to the XBee. This radio’s
pins to operate as inputs, outputs, or to turn off. You can settings are the simplest, as it’s doing the least. Its
also set them to be digital or analog inputs, or digital or settings are as follows:
pulse-width modulation (PWM) outputs. You can even link
an output pin’s behavior to the signals it receives from • ATMY03: Sets the radio’s source address.
another radio. (If you don't remember how to configure the • ATDL01: Sets the destination address to send only to
XBee, see Step 1 in Project 10). the sensor radio (address 01). It doesn't really matter,
though,as this radio won’t be sending.
The sensor radio is the center of this project. You’ll configure • ATID1111: Sets the PAN.
it to read an analog voltage on its first analog input (AD0, • ATIU1: Sets the radio to send any I/O data packets out
pin 20) and broadcast the value that it reads to all other the serial port. This data will go to the attached Arduino.
radios on the same PAN. Its settings are as follows:
NOTE: If you want to reset your XBee radios to the factory
• ATMY01: Sets the sensor radio’s source address. default settings before configuring for this project, send them the
• ATDLFFFF: Sets the destination address to broadcast to command ATRE\r.
the whole PAN.
• ATID1111: Sets the PAN. Here’s a summary of all the settings:
• ATD02: Sets I/O pin 0 (D0) to act as an analog input.
• ATIR64: Sets the analog input sample rate to 100 Sensor radio Monkey radio XPort radio
milliseconds (0x64 hex).
• ATIT5: Sets the radio to gather five samples before MY = 01 MY = 02 MY = 03
sending, so it will send every 500 milliseconds DL = FFFF DL = 01 DL = 01
(5 samples x 100 milliseconds sample rate = 500 ID = 1111 ID = 1111 ID = 1111
milliseconds. D0 = 2 P0 = 2 IU = 1
IR = 64 IU = 1
The monkey radio will listen for messages on the PAN, and IT = 5 IA = 01 (or FFFF)
if any radio sends it a packet of data with an analog sensor
reading formatted the way it expects, it will set the first
pulse width modulation output (PWM0) to the value of the
received data. In other words, the monkey radio’s PWM0 Make sure to save the configuration to each radio’s
output will be linked to the sensor radio’s analog input. memory by finishing your commands with WR. You can
Its settings are as follows: set the whole configuration line by line or all at once. For
example, to set the sensor radio, type:
• ATMY02: Sets the monkey radio’s source address.
• ATDL01: Sets the destination address to send only to +++
the sensor radio (address 01). However, this doesn’t
really matter, as this radio won’t be sending. Then wait for the radio to respond with OK. Next, type the
following (the 0 in D02 is the number 0):
SESSIONLESS NETWORKS 235
ATMY1, DLFFFF\r NOTE: Air out your workspace as soon as you’ve tested the sensor.
ATID1111, D02, IR64\r You don’t want to poison yourself making a poison sensor!
ATIT5, WR\r
To test whether the XBee is reading the sensor correctly,
For the monkey radio, the configuration is: connect its TX pin to the USB-to-XBee serial adapter’s TX
pin, its RX pin to the adapter’s RX pin, and connect their
ATMY2, DL1\r ground lines together. Make sure there's no XBee in the
ATID1111, P02\r socket when you do this. You're just using the adapter to
ATIU1, IA1, WR\r connect to this circuit. Then plug the adapter into your
computer and open a serial connection to it. Type +++ and
And for the Arduino's radio, it’s: wait for the OK. Then type ATIS\r. This command forces
the XBee to read the analog inputs and return a series of
ATMY3, DL1\r values. You’ll get a reply like this:
ATID1111, IU1, WR\r
1
The Circuits 200
Once you’ve got the radios configured, set up the circuits 3FF
for the sensor, the monkey, and the Arduino. In all of these
circuits, make sure to include the decoupling capacitors Don’t worry about what the values yet; all that matters is
on either side of the voltage regulator—the XBee radios that you’re getting something. You’ll see the actual values
tend to be unreliable without them. as the project develops later.
To +9-12V DC supply
Figure 7-5
XBee radio connected to a gas
7805
+5V Voltage Reg sensor. The MQ-6 is shown here,
but the same circuit will work
In Out
for many of the Hanwei sensors.
H A
You may have to change the
10K resistor to adjust the output
Hanwei voltage range, however.
MQ-6
Gas Sensor
The XBee shown on the bread-
board below is mounted on a
breakout board. The XBee's pins
H B
LD1117-33V
Xbee Radio will not fit into a breadboard
Voltage Reg without the breakout board.
In Out
Vcc AD0 / DIO0
TX AD1 / DIO1
88Many of the projects in this chapter
10K Ω
10µF 1µF
RX AD2 / DIO2 are made using the LD1117-33V 3.3V
DO8 AD3 / DIO3 voltage regulator. The pins on this
RESET RTS / AD6 / DIO6 regulator are configured differently
5V 3.3V
VREG VREG
1 5 10 15 20 25 30
A
B
C
D
E
F
G
H
I
J
1 5 10 15 20 25 30
SESSIONLESS NETWORKS 237
Xbee Radio
To +3V DC supply
RX AD2 / DIO2
NC SLP
DC motor M
TIP120 DTR/DI8 CTS / DIO7
1KΩ
GND AD4 / DIO4
1N4004
TIP120
NPN
1 5 10 15 20 25 30
A
B
C
D
E
F
G
H
I
J
1 5 10 15 20 25 30
Figure 7-6
XBee radio connected to a cymbal monkey.
238 MAKING THINGS TALK
Figure 7-7
The insides of the monkey,
A
showing the wiring modifica-
A
tions. Solder the power to the
breadboard to the positive
terminal of the battery. Solder
the ground wire to the ground
terminal. Cut the existing motor
leads, and add new ones that
connect to the breadboard.
To test this circuit, make sure that the sensor radio is shield. You don't need to connect the XBee's receive line
working, and turn it on. When the sensor’s value is low, to the Arduino's transmit line because the Arduino's never
the motor should be turned off; when the sensor reads going to talk to the XBee—it will just listen. You also won't
a high concentration of VOCs, the motor will turn on and need the LED, or the potentiometer from that project.
the monkey will warn you by playing his cymbals. Use the
potentiometer to affect the motor’s activation threshold. When the Arduino receives the message from the gas
Start with the potentiometer set very high, then slowly sensor XBee, it will parse the message, extract the sensor
turn it down until the motor turns off. At that point, expose value, and convert it to a voltage. It will act as a web server,
the sensor to some alcohol—the motor should turn on so anyone who wants to know the sensor level can check
again. It should go off when the air around the sensor is on the Web. In order to make that happen, it's best to break
clear. If you’re unsure whether the motor circuit is working the task into two parts: first, establish that you can read
correctly, connect an LED and 220-ohm resistor in series and parse the XBee's messages; then, add the web server
from 3V to the collector of the transistor instead of the component to your code.
motor. The LED should grow brighter when the sensor
reading is higher, and dimmer when the sensor reading is Reading the XBee Protocol
lower. The LED has no physical inertia like the motor does, So far, you’ve been able to rely on the XBee radios to do
and it consumes less current, so it turns on at a much their work without having to understand their message
lower duty cycle. protocol. Now it’s time to interpret that protocol. The XBee
radios format the readings from their analog-to-digital
The Arduino circuit converters into a packet before they transmit. The format
If you're using an Arduino wireless shield, all you need to do of the packet is explained in the Digi XBee 802.15.4 user’s
for this project is stack that on top of an Ethernet shield or manual. It works like this:
Arduino Ethernet board, and add them both to your micro-
controller. If you're building the circuit yourself, it's shown in • Byte 1: 0x7E, the start byte value.
Figure 7-8. • Byte 2–3: Packet size, a 2-byte value. This depends on
your other settings.
The Arduino Ethernet and XBee circuit look a lot like the • Byte 4: API identifier value, a code that says what this
circuit you used for the duplex radio transmission project in response is.
Chapter 6. All you're doing differently is adding an Ethernet
SESSIONLESS NETWORKS 239
Reset GND
+3.3V CLK
+5V Ethernet MOSI
Shield
Gnd MISO
Gnd Eth, SS
Vin
SD card SS
AREF
Reset GND
+3.3V D13
+5V D12
Gnd D11/PWM
Gnd D10/PWM
Vin D9/PWM to +5V
D8 LD1117-33V
Arduino
Module Voltage Reg
D7 In Out
D6/PWM
Analog0 D5/PWM
10µF 1µF
A1 D4
Xbee Radio
A2 D3/PWM
A3 D2
A4 Digital1/TX Vcc AD0 / DIO0
RX AD2 / DIO2
PWM1 Vref
220Ω
NC SLP
LINK
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
RX
ETHERNET
SHIELD - + A
1 5 10 15 20 25 30
B
C
RESET
ON
D
100M E
M A D E I N I TA LY
W W W. A R D U I N O.CC
ICSP
F
G
H
I
J
1 5 10 15 20 25 30
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
Figure 7-8
XBee radio connected to an Arduino with Ethernet shield.
240 MAKING THINGS TALK
• Byte 5–6: XBee sender’s address. • Byte 12–21: 10-bit values, each ADC sample from the
• Byte 7: Received Signal Strength Indicator (RSSI). sender. Each 10-bit sample represents a voltage from 0
• Byte 8: Broadcast options (not used here). to the XBee's maximum of 3.3V, so a value of 0 means 0
• Byte 9: Number of samples in the packet (you set it to 5 volts, and a value of 1023 means 3.3 volts. Each point of
using the IT command shown earlier). the sensor's value is then 3.3/1024, or 0.003 volts.
• Byte 10–11: Which I/O channels are currently being
used. This example assumes only one analog channel, Because every packet starts with a constant value, 0x7E
AD0, and no digital channels are in use. (that’s decimal value 126), you can start by looking for that
value.
X
8
The main loop doesn't do much void loop() {
in this sketch; it just calls a method, // listen for incoming serial data:
listenToSerial(), that goes through the if (Serial.available() > 0) {
bytes and does the work. listenToSerial();
}
}
8 When you run this sketch, you’ll 201 1 201 1 200 1 197 91
get a result like what's shown to 126 0 18 131 0 1 43 0 5 2 0 1 197 1 196 1 198 1 198 1 197 106
the right. 126 0 18 131 0 1 43 0 5 2 0 1 197 1 193 1 193 1 192 1 192 125
126 0 18 131 0 1 44 0 5 2 0 1 194 1 194 1 193 1 190 1 190 130
Each line that starts with 126 (0x7E 126 0 18 131 0 1 43 0 5 2 0 1 189 1 189 1 191 1 190 1 190 143
in hexadecimal) is a single XBee 126 0 18 131 0 1 43 0 5 2 0 1 190 1 186 1 186 1 186 1 188 156
message. Most of the lines have 22 126 0 18 131 0 1 43 0 5 2 0 1 187 1 187 1 186 1 183 1 183 166
bytes, corresponding to the packet 126 0 18 131 0 1 43 0 5 2 0 1 182 1 182 1 184 1 183 1 183 178
format described earlier. You may 126 0 18 131 0 1 43 0 5 2 0 1 181 1 180 1 179 1 179 1 182 191
wonder why the first line of the output 126 0 18 131 0 1 43 0 5 2 0 1 181 1 181 1 180 1 178 1 177 195
shown here didn’t have a full comple- 126
ment of bytes. It’s simply because
there’s no way to know what byte the
XBee is sending when the Arduino first
starts listening. That's OK, because the
code below will filter out the incom-
plete packets.
const int packetLength = 22; // XBee data messages will be 22 bytes long
int dataPacket[packetLength]; // array to hold the XBee data
int byteCounter = 0; // counter for bytes received from the XBee
8 Just as you had a method earlier to // this method listens to requests from an HTTP client:
listen to serial data, now you're adding void listenToClient( Client thisClient) {
one to listen to incoming HTTP client while (thisClient.connected()) {
requests. This method reads the bytes if (thisClient.available()) {
and saves them in a string until it gets // read in a byte:
a linefeed. It's not actually parsing the char thisChar = thisClient.read();
lines, except to look for linefeeds or // for any other character, increment the line length:
carriage returns. Whenever it gets two requestLine = requestLine + thisChar;
linefeeds in a row, it knows the HTTP // if you get a linefeed and the request line
request is over, and it should respond // has only a newline in it, then the request is over:
by calling the makeResponse() routine. if (thisChar == '\n' && requestLine.length() < 2) {
// send an HTTP response:
makeResponse(thisClient);
break;
}
//if you get a newline or carriage return,
// you're at the end of a line:
if (thisChar == '\n' || thisChar == '\r') {
// clear the last line:
requestLine = "";
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
thisClient.stop();
}
Figure 7-10
The results of the XBee gas server.
Directed Messages
The more common way to use sessionless protocols is to send directed messages to
the object to which you want to speak. You saw this in action already in Chapter 6, when
you programmed your microcontrollers to speak to each other using XBee radios. Each
radio had a source address (which you read and set using the ATMY command) and a
destination address (which you read and set using the ATDL command). One radio’s
destination was another’s source, and vice versa. Though there were only two radios
in that example, you could have included many more radios, and decided which one to
address by changing the destination address on the fly.
void setup() {
udp = new UDP( this, 43770 ); // open a UDP port
udp.listen( true ); // listen for incoming messages
}
void draw()
{
»
}
SESSIONLESS NETWORKS 247
void keyPressed() {
int port = 43770; // the destination port
String message = ", I'm talking to YOU!"; // the message to send
String ip = "255.255.255.255"; // the remote IP address
Project 14
Internet
3.3V 100kΩ
Voltage Reg
In Out
Xbee Radio
4.7kΩ
10µF 1µF
Vcc AD0 / DIO0
TX AD1 / DIO1
1kΩ
RX AD2 / DIO2
NC SLP
1 5 10 15 20 25 30 35 40 45 50 55 60
A A
B B
C C
D D
E E
MAX8212
F F
G G
H H
I I
J J
1 5 10 15 20 25 30 35 40 45 50 55 60
252 MAKING THINGS TALK
+9V battery
Xbee Radio
LM7833
Voltage Reg
In Out
Vcc AD0 / DIO0
TX AD1 / DIO1
RX AD2 / DIO2
10µF 1µF
DO8 AD3 / DIO3
B
A
C
E
J
F
I
1
1
5
5
10
10
15
15
20
20
25
25
30
30
back into the receive pin, where they will be sent out again Once you’ve got the radios configured and working, you
as transmissions. Figure 7-14 shows the circuit. You could need to program the Arduino to read the incoming XBee
also use a LilyPad XBee, XBee Explorer Regulated, or any packets and relay them to Processing. To do this, you'll use
USB-to-XBee serial adapter. Just tie the transmit and directed UDP datagrams.
receive pins together, and attach a battery to the voltage
input of the regulator.
SESSIONLESS NETWORKS 253
Graphing the Results parsing routine you wrote for the Arduino in the previous
Now that all the hardware is ready, it’s time to write a project. It's useful to compare them to see how the same
Processing sketch to graph the data. This sketch will algorithm is implemented slightly differently in the two
receive UDP packets from the Arduino, parse the XBee programming languages.
packets contained therein, and graph the results. You'll X
notice that the parsing routine looks very similar to the
8 First, you need to import the UDP /* XBee Packet Reader and Graphing Program
library, initialize it, and write a method Reads a packet from an XBee radio via UDP and parses it.
to listen for incoming datagrams. Graphs the results over time.
Context: Processing
This program will print out strings of */
numbers that look a lot like the initial
ones from the Arduino sketch in the import hypermedia.net.*;
gas sensor project. That’s because the import processing.serial.*;
datagrams the program is receiving are
the same protocol—the XBee protocol UDP udp; // define the UDP object
for sending analog readings. int queryPort = 43770; // the port number for the device query
void setup() {
// create a new connection to listen for
// UDP datagrams on query port:
udp = new UDP(this, queryPort);
void draw() {
// nothing happens here.
}
/*
listen for UDP responses
*/
void receive( byte[] data, String ip, int port ) {
int[] inString = int(data); // incoming data converted to string
print(inString);
println();
}
SESSIONLESS NETWORKS 255
8 Now that you’ve got the average int hPos = 0; // horizontal position on the graph
reading printing out, add some
code to graph the result. For this, you’ll
need a new global variable before
the setup() method that keeps track
of where you are horizontally on the
graph.
8 You’ll also need to add a line at the // set the window size:
beginning of the setup() method to size(400,300);
set the size of the window.
256 MAKING THINGS TALK
8
Now, add a new method, void drawGraph(int thisValue) {
drawGraph(), to the end of the // draw the line:
program. stroke(#4F9FE1);
// map the given value to the height of the window:
Call this from the parseData() method, float graphValue = map(thisValue, 0, 1023, 0, height);
replacing the println() statement that // determine the line height for the graph:
prints out the average, like so: float graphLineHeight = height - (graphValue);
// draw the line:
// draw a line on the graph: line(hPos, height, hPos, graphLineHeight);
drawGraph(average); // at the edge of the screen, go back to the beginning:
if (hPos >= width) {
Now when you run the program, it hPos = 0;
should draw a graph of the sensor //wipe the screen:
readings, updating every time it gets background(0);
a new datagram. }
else {
// increment the horizontal position to draw the next line:
hPos++;
}
}
8
Next, add some code to add a time int lineHeight = 14; // a variable to set the line height
stamp. First, add a global variable to
set the text line height.
8 Add a method to the end of the void drawReadings(int thisReading, int thisSignalStrength) {
program, drawReadings() . This will // set up an array to get the names of the months
display the date, time, voltage reading, // from their numeric values:
and received signal strength. String[] months = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
Call this method from a few different "Sep", "Oct", "Nov", "Dec"
places in the program; first, at the end };
of the setup() method:
// format the date string:
// show the readings text: String date = day() + " " + months[month() -1] + " " + year() ;
drawReadings(0,0);
// format the time string
Next, to draw the latest readings, call it // all digits are number-formatted as two digits:
at the end of the parseData() method: String time = nf(hour(), 2) + ":" + nf(minute(), 2) + ":" + nf(second(),
2);
// draw a line on the graph,
// and the readings: // calculate the voltage from the reading:
drawGraph(average); float voltage = thisReading * 3.3 / 1024;
drawReadings(average, signalStrength);
// choose a position for the text:
int xPos = 20;
»
int yPos = 20;
SESSIONLESS NETWORKS 257
Figure 7-16
The output of the solar graph program.
These sensor values were faked with a
flashlight! Your actual values may differ.
258 MAKING THINGS TALK
Conclusion
Sessionless networks can be really handy when you’re just passing short messages
around and don’t need a lot of acknowledgment. They involve a lot less work because
you don’t have to maintain the connection. They also give you a lot more freedom
in how many devices you want to address at once.
By comparing the two projects in this chapter, you can Now that you’ve got a good grasp of both session-based
see there’s not a lot of work to be done to switch from and sessionless networks, the next chapters switch
directed messages and broadcast messages when you’re direction slightly, covering two other activities of connecting
making a sessionless network. It’s best to default to directed networks to the physical world: location and identification.
messages when you can, which reduces the traffic for X
those devices that don’t need to get every message.
The solar energy display by Gilad Lotan and Angela Pablo The solar panel powering the
display on the roof of NYU's
Tisch School of the Arts
SESSIONLESS NETWORKS 259
260 MAKING THINGS TALK
8
MAKE: PROJECTS
How to Locate
(Almost) Anything
By now, you’ve got a pretty good sense of how to make things talk to each
other over networks. You’ve learned about packets, sockets, datagrams,
clients, servers, and all sorts of protocols. Now that you know how to
talk, this chapter and the next deal with two common questions: “where
am I?”, and “who am I talking to?” Location and identification technolo-
gies share some important properties. As a result, it’s not uncommon
to confuse the two, and to think that a location technology can be used
to identify a person or an object, and vice versa. These are two different
tasks in the physical world, and often in the network environment as
well. Systems for determining physical location aren’t always very good
at determining identity, and identification systems don’t do a good job
of determining precise location. Likewise, knowing who’s talking on a
network doesn’t always help you to know where the speaker is. In the
examples that follow, you’ll see methods for determining location and
identification in both physical and network environments.
6 1
5 3
2
Figure 8-1. New parts for this chapter: 1. Sharp GP20Y0A21 IR ranger 2. JST pigtail for IR ranger 3. Maxbotix LV-EZ1 ultrasonic
ranger 4. EM-406A GPS receiver 5. Interface cable for EM-406A 6. LMS303DLH digital compass 7. LED tactile button 8. Breakout
board for button 9. ADXL335 accelerometer. Don't forget plenty of male header pins for the breakout boards.
HOW TO LOCATE (ALMOST) ANYTHING 263
»» 3 0.1-inch male header pins J 103377, D A26509- PROJECT 20: DETERMINING HEADING USING A
20ND, SF PRT-00116, F 1593411 DIGITAL COMPASS
»» 1 solderless breadboard or prototyping shield The
PROJECT 16: ULTRASONIC DISTANCE-RANGER same as used in previous projects.
»» 1 Arduino module See description in Project 15. D 438-1045-ND, J 20723 or 20601, SF PRT-00137,
D 1050-1019-ND, J 2121105, SF DEV-09950, F 4692810, AF 64, SS STR101C2M or STR102C2M, MS
A A000046, AF 50, F 1848687, RS 715-4081, SS MKKN2
ARD132D2P, MS MKSP4 »» 1 Arduino module See description in Project 15.
»» 1 MaxBotix LV-EZ1 ultrasonic ranger Another D 1050-1019-ND, J 2121105, SF DEV-09950,
distance-ranging sensor, this one uses sonar and has a A A000046, AF 50, F 1848687, RS 715-4081,
longer range; 0 to 6.4m. SS ARD132D2P, MS MKSP4
SF SEN-00639, AF 172, P 726, SS SEN136B5B »» 1 ST Microelectronics LSM303DLH digital compass
»» 3 0.1-inch male header pins J 103377, D A26509- Both Pololu and Spark Fun carry a module with this
20ND, SF PRT-00116, F 1593411 compass. As of this writing, the Pololu model is
operable at 5V with no external components, but the
PROJECT 17: READING RECEIVED SIGNAL STRENGTH Spark Fun one is not.
USING XBEE RADIOS SF SEN-09810, RS 717-3723, P 1250
»» 2 Digi XBee 802.15.4 RF modules J 2113375, SF »» 1 LED tactile button This example uses an LED tactile
WRL-08664, AF 128, F 1546394, SS WLS113A4M, MS button and breakout board from Spark Fun, which has a
MKAD14 built-in LED, but you can use any pushbutton and LED.
»» 1 USB-XBee adapter J 32400, SF WRL-08687, AF 247 SF COM-10443 and SF BOB-10467
»» XBee breakout board Use the circuit you used for the »» 1 220-ohm resistor D 220QBK-ND, J 690700, F
XBee solar cell or gas monitor in Chapter 7. 9337792, RS 707-8842
J 32403, SF BOB-08276, AF 127 »» 1 10-kilohm resistor D 10KQBK-ND, J 29911,
F 9337687, RS 707-8906
PROJECT 18: READING RECEIVED STRENGTH USING »» 1 LED Not needed if you are using the Spark Fun LED
BLUETOOTH RADIOS tactile button. D 160-1144-ND or 160-1665-ND, J 34761
»» 1 Bluetooth Mate module The same one used in or 94511, F 1015878, RS 247-1662 or 826-830, SF
Chapters 2 and 6. COM-09592 or COM-09590
SF WRL-09358 or WRL-10393 »» 13 0.1-inch male header pins J 103377, D A26509-
»» 1 USB-to-Serial adapter SF DEV-09718 or DEV-09716, 20ND, SF PRT-00116, F 1593411
AF 70, A A000059, M MKAD22, SS PRO101D2P, D TTL-
232R-3V3 or TTL-232R-5V PROJECT 21: DETERMINING ATTITUDE USING AN
»» 1 Bluetooth-enabled personal computer If your ACCELEROMETER
laptop doesn't have a Bluetooth radio, use a USB »» 1 solderless breadboard or prototyping shield The
Bluetooth adapter: SF WRL-09434, F 1814756 same as used in previous projects. D 438-1045-ND, J
20723 or 20601, SF PRT-00137, F 4692810, AF 64, SS
PROJECT 19: READING THE GPS SERIAL PROTOCOL STR101C2M or STR102C2M, MS MKKN2
»» 1 solderless breadboard Just as you've used for »» 1 Arduino module See description in Project 15.
previous projects. D 438-1045-ND, J 20723 or 20601, D 1050-1019-ND, J 2121105, SF DEV-09950,
SF PRT-00137, F 4692810, AF 64, SS STR101C2M or A A000046, AF 50, F 1848687, RS 715-4081,
STR102C2M, MS MKKN2 SS ARD132D2P, MS MKSP4
»» 1 EM-406A GPS receiver module S GPS-00465, »» 1 Analog Devices ADXL320 accelerometer This
PX 28146, AF 99 is a three-axis analog accelerometer, the same one
»» 1 interface cable for GPS module S GPS-09123, as you used in the balance board client project in
PX 805-00013 Chapter 5. You can also use the accelerometer on your
»» 1 Bluetooth Mate module The same one used in LSM303DLH digital compass from the previous project.
Chapters 2 and 6. SF WRL-09358 or WRL-10393 J 28017, SF SEN-00692, AF 163, RS 726-3738, P 1247,
»» 12 0.1-inch male header pins J 103377, D A26509- MS MKPX7
20ND, SF PRT-00116, F 1593411
»» 1 5V regulator J 51262, D LM7805CT-ND, SF COM-
00107, F 1860277, RS 298-8514
264 MAKING THINGS TALK
The downside of this freedom is the perception that in a Getting a good location starts with cultural and behavioral
networked world, you can be located anywhere. Ubiqui- cues. If you want to know where you are, ask another
tous surveillance cameras and systems like Wireless E911 person near you. In an instant, she’s going to sum up all
(which locates mobile phones on a network), make it seem kinds of things—your appearance, your behavior, the
as though anyone or anything can be located anywhere setting you’re both in, the things you’re carrying, and
and at any time—whether you want to be located or not. more—in order to give you a reasonably accurate and
The reality of location technologies lies somewhere in contextually relevant answer. No amount of technology
between these extremes. can do that, because the connection between where
you are and why you want to know is seldom explicit
Locating things on a network is different than locating in the question. As a result, the best thing you can do
things in physical space. As soon as a device is connected when you’re designing a locating system is to harness
to a network, you can get a general idea of its network the connection-making talents of the person who will be
location using a variety of means—from address lookup to using that system. Providing him with cues as to where
measuring its signal strength—but that doesn’t mean that to position himself when he should take action, and what
you know its physical location. You just know its relation- actions he can take, helps eliminate the need for a lot of
ship to other nodes of the network. You might know that technology. Asking him to tell your system where things
a cell phone is closest to a given cell transmitter tower, or are, or to position them so that the system can easily find
that a computer is connected to a particular WiFi access them, makes for a more effective system.
point. You can use that information along with other data
to form a picture of the person using the device. If you For example, imagine you’re making an interactive space
know that the cell transmitter tower is less than a mile that responds to the movements of its viewers. This is
from you, you’d know that the person with the cell phone popular among interactive artists, who often begin by
is going to reach you soon, and you can act appropriately imagining a “body-as-cursor” project, in which the viewer
in response. For many network applications, you don’t is imagined as a body moving around in the space of
need to know physical location as much as you need to the gallery. Some sort of tracking system is needed to
know relationship to other nodes in the network. determine his position and report it back in two dimen-
sions, like the position of a cursor on a computer screen.
• Step 1: Ask a Person What’s missing here is the reason why the viewer might be
People are really good at locating things. At the physical moving in the first place. If you start by defining what the
level, we have a variety of senses to throw at the problem viewer’s doing, and give him cues as to what you expect
as well as a brain that’s wonderful at matching patterns of him to do at each step, you can narrow down the space
shapes and determining distances from different sensory in which you need to track him. Perhaps you only need to
clues. At the behavioral level, we’ve got thousands of know when he’s approaching one of several sculptures in
patterns that make it easier to determine why you might the space so that you can trigger the sculpture to move
be looking for something. Computer systems don’t have in response. If you think of the sculptures as nodes in
these same advantages, so when you’re designing an a network, the task gets easier. Instead of tracking the
interactive system to locate things or people, the best viewer in an undefined two-dimensional space, now all
tool you have to work with—and the first one you should you have to do is determine his proximity to one of several
consider—is the person for whom you’re making your
system.
HOW TO LOCATE (ALMOST) ANYTHING 265
points in the room. Instead of building a tracking system, based lookup at www.geocoder.us, and Worldkit offers an
you can now just place a proximity sensor near each extended version that also looks up international cities:
object, look up which he’s near, and read how near he is to www.worldkit.org/geocoder.
it. You’re using a combination of spatial organization and
technology to simplify the task. You can make your job Street addresses are the most common coordinates
even easier by giving him visual, auditory, and behavioral that are mapped to latitude and longitude, but there
cues to interact appropriately. He’s no longer passive; he’s are other systems for which it would be useful to have
now an active participant in the work. physical coordinates as well. For example, mobile phone
cell transmitters all have physical locations. It would be
Or, take a different example: let’s say you’re designing handy to have a database of physical coordinates for
a mobile phone city-guide application for tourists that those towers. However, cell towers are privately owned by
relies on knowing the phone’s position relative to nearby mobile telephone carriers, so detailed data about the tower
cell towers to determine the user’s position. What do locations is proprietary, and the data is not in the public
you do when you can’t get a reliable signal from the cell domain. Projects such as OpenCellID (www.opencellid.org)
towers? Perhaps you ask the tourist to input the address attempt to map cell towers by using GPS-equipped mobile
she’s at, or the postal code she’s in, or some other nearby phones running custom software. As there are many
cue. Then, your program can combine that data with the different mobile phone operating systems, just developing
location based on the last reliable signal it received, and the software to do the job is a huge challenge.
determine a better result. In these cases, and in all loca-
tion-based systems, it’s important to incorporate human IP addresses don’t map exactly to physical addresses
talents in the system to make it better. because computers can move. Nevertheless, there are
several geocoding databases for IP addresses. These work
on the assumption that routers don’t move a lot, so if you
• Step 2: Know the Environment know the physical location of a router, then the devices
Before you can determine where you are, you need to gaining access to the Net through that router can’t be too
determine your environment. For any location, there far away. The accuracy of IP geocoding is limited, but it
are several ways to describe it. For example, you could can help you determine a general area of the world, and
describe a street corner in terms of its address, its latitude sometimes even a neighborhood or city block, where a
and longitude, its postal code, or the businesses nearby. device on the Internet is located. Of course, IP lookup
Which of these coordinates you choose depends in part on doesn’t work on private IP addresses. In the next chapter,
the technology you have on hand to determine it. If you’re you’ll see an example that combines network identity and
making the mobile city guide described earlier, you might geocoding.
use several different ones—the nearest cell transmitter
ID, the street address, and the nearby businesses could all You can develop your own database relating physical
work to define the location. In this case, as in many, your locations to cultural or network locations if the amount of
job in designing the system is to figure out how to relate information you need is small, or if you have a large group
one system of coordinates to another in order to give of people to do the job. But, generally, it’s better to rely on
some meaningful information. existing infrastructures when you can.
which way you’re oriented. It’s also valuable information • Ask someone.
when two people or objects are close to each other. You • Association: who or what are you near?
don’t want to activate the animatronic sculpture if the • Proximity to phone boxes, public transport stops,
viewer has his back to the thing! and utility markings.
X • Use a map.
• Which cell phone operators are available?
• Public phone operators?
• Phone number syntax?
• Newspapers available?
• Language being spoken?
• Post codes/ZIP codes.
• Street names.
• Street corners/intersections.
• Street numbers.
• Business names.
• Mobile phone location, through triangulation or
trilateration.
• Triangulation and trilateration on other radio
infrastructures, such as TV, radio, and public WiFi.
• GPS, assisted GPS, WAAS, and other GPS
enhancements.
• Landmarks and “littlemarks.”
• Dead reckoning.
HOW TO LOCATE (ALMOST) ANYTHING 267
Determining Distance
Electronic locating systems—like GPS, mobile phone location, and sonar—seem
magical at first because there’s no visible evidence as to how they work. However, when
you break the job down into its components, it becomes relatively straightforward. Most
physical location systems are based on one of two methods: measuring the time of a
signal's travel from a known location, or measuring its strength at the point of reception.
Both methods combine measurements from multiple sources to determine a position in
two or three dimensions using trilateration.
For example, a GPS receiver determines its position on Sometimes distance ranging is used for acquiring a
the surface of the planet by measuring the time delay position; other times, it’s used for refining it. In the
of received radio signals from several geosynchronous following examples, the passive distance rangers deliver a
satellites. Mobile phone location systems function measurement of physical distance.
similarly, using the signal from nearby cell towers to
determine the phone's position. Systems like Skyhook
(www.skyhookwireless.com) use several different systems Passive Distance Ranging
(WiFi, GPS, and cell tower location) to refine their posi- Ultrasonic rangers like the MaxBotix LV-EZ1, and infrared
tional accuracy. Sonar and infrared-ranging sensors work rangers like the Sharp GP2Y0A21YK, shown in Figure 8-2,
by sending out an acoustic signal (sonar) or an infrared are examples of distance rangers. The MaxBotix sensor
signal (IR rangers), and then measuring the strength of sends out an ultrasonic signal and listens for an echo.
that signal when it’s reflected off the target. The Sharp sensor sends out an infrared light beam, and
senses the reflection of that beam. These sensors work in
Distance ranging techniques can be classified as active or a short range only. The Sharp sensor can read about 10cm
passive. In active systems, the target has a radio, light, or to 80cm, and the MaxBotix sensor reads from about 0 to
acoustic source on it, and the receiver listens for the signal 7.5m. Passive sensors like these are handy when you want
generated directly by the target. In passive systems, the to measure the distance of a person in a limited space, and
target doesn’t need to have any technology on board. The you don’t want to put any hardware on the person. They’re
receiver emits a signal, then listens for the signal reflected also useful when you’re building moving objects that need
back from the target. Mobile phone location is active to know their proximity to other objects in the same space
because it relies on a two-way transmission between as they move.
the phone and the cell tower. GPS is also active, even X
though the transmission is one-way, because the signal
used to determine location is direct, not reflected. The
target is a radio receiver. Sonar and infrared ranging are
passive because the signal is reflected off the target, not
generated by it.
268 MAKING THINGS TALK
Project 15
MADE
I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
DIGITAL (PWM ~)
-
L
TX
+ UNO ON
RX ARDUINO
RESET-EN
RESET ICSP
W W W. A R D U IN O. CC
POWER ANALOG IN Figure 8-2
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
The Sharp GP2Y0A21YK IR ranger
5V
AREF
Reset GND
+3.3V D13
+5V D12
Gnd D11/PWM
Gnd D10/PWM
Vin D9/PWM
D8
Arduino
Module
+5V
D7
10µF
GND
D6/PWM
Analog out
Analog0 D5/PWM
A1 D4
A2 D3/PWM
A3 D2
A4 Digital1/TX
A5 Digital0/RX
270 MAKING THINGS TALK
Project 16
MADE
I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
DIGITAL (PWM ~)
-
L
TX
+ UNO ON
RX ARDUINO
RESET-EN
RESET ICSP
W W W. A RDU I NO. CC
Sensor Sensor
3 2
POWER ANALOG IN
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
+5V
TX
RX
AN
PW
BW
Sensor Sensor
4 5
HOW TO LOCATE (ALMOST) ANYTHING 271
8
This sketch is similar to the /*
infrared ranging sketch in Project 15. MaxBotix LV-EZ1 ultrasonic ranger reader
It reads the sensor and converts the Context: Arduino
results to a voltage, then converts that */
to a distance measured in centimeters. void setup() {
The conversion formula again gives // initialize serial communications at 9600 bps:
only an approximation. Serial.begin(9600);
}
The MaxBotix sensors can read only
every 50 milliseconds, so you need a void loop() {
delay after each read to give the sensor // read the sensor value and convert to a voltage:
time to stabilize before the next read. int sensorValue = analogRead(A0);
float voltage = map(sensorValue, 0, 5, 0, 1023);
Figure 8-4
at right, opposite page
MaxBotix LV-EZ1 ultrasonic sensor
connected to an Arduino module.
AREF
Reset GND
+3.3V D13
Figure 8-5
BW +5V D12
Schematic for MaxBotix
Gnd D11/PWM LV-EZ1 ultrasonic sensor
PW out
Gnd D10/PWM connected to an Arduino
Analog out
Vin D9/PWM module.
RX
D8
TX Arduino
Module
+5V
D7
GND
D6/PWM
Analog0 D5/PWM
A1 D4
A2 D3/PWM
A3 D2
A4 Digital1/TX
A5 Digital0/RX
272 MAKING THINGS TALK
Active Distance Ranging ZigBee, and WiFi radios all provide data about signal
The ultrasonic and infrared rangers in the preceding strength as well. In order to relate this to distance, you
sections are passive distance-sensing systems. Mobile need to be able to calculate that distance as a function
phones and the Global Positioning System (GPS) measure of signal strength. The main function of a GPS receiver
longer distances by using ranging as well. These systems is to calculate distances to the GPS satellites based on
include a radio beacon (the cell tower or GPS satellite) signal strength, and then determine a position using those
and a radio receiver (the phone or GPS receiver). The distances. The other radio systems mentioned here don’t
receiver determines its distance from the beacon based do those calculations for you.
on the received signal from the beacon. These systems
can measure much greater distances on an urban or In many applications, though, you don’t need to know the
global scale. The disadvantage of active distance ranging distance—you just need to know how relatively near or far
is that you must have a powered device at both ends. You one person or object is to another. For example, if you’re
can’t measure a person’s distance from somewhere using making a pet door lock that opens in response to the pet,
active distance ranging unless you attach a receiver to the you could imagine a Bluetooth beacon on the pet’s collar
person. and a receiver on the door lock. When the signal strength
from the pet’s collar is strong enough, the door lock opens.
GPS and cellular location systems don’t actually give you In this case, and in others like it, there’s no need to know
the distance from their radio beacons, just the relative the actual distance.
signal strength of the radio signal. Bluetooth, 802.15.4, X
Figure 8-6
Active vs. passive
distance ranging
Project 17
void setup () {
size(320, 480); // window size
»
}
274 MAKING THINGS TALK
void draw() {
// if you have new data and it's valid (>0), graph it:
if ((rssi > 0 ) && (rssi != lastReading)) {
// set the background:
background(0);
// set the bar height and width:
int rectHeight = rssi;
int rectWidth = 50;
// draw the rect:
stroke(23, 127, 255);
fill (23, 127, 255);
rect(width/2 - rectWidth, height-rectHeight, rectWidth, height);
// write the number:
text("XBee Radio Signal Strength test", 10, 20);
text("Received from XBee with address: " + hex(address), 10, 40);
text ("Received signal strength: -" + rssi + " dBm", 10, 60);
// save the current byte for next read:
lastReading = rssi;
}
}
/*
Once you've got a packet, you need to extract the useful data.
This method gets the address of the sender and RSSI.
*/
int parseData(int[] thisPacket) {
int result = -1; // if you get no result, -1 will indicate that.
»
if (thisPacket.length > 6) {
HOW TO LOCATE (ALMOST) ANYTHING 275
Figure 8-7
Output of the XBee RSSI test program.
276 MAKING THINGS TALK
Project 18
Once you’ve done this, open a serial connection to the These are the signal strength values of the link, in hexa-
radio via Bluetooth. Once you’re connected, drop out of decimal. FF is the strongest possible value, and 00 is
data mode into command mode by typing the following: the weakest. The first of the two values is the current
link quality; the second is the lowest recorded value so
$$$ far. As you move the radio closer to or farther from your
computer, the values will change just as it did in the XBee
You’ll get a CMD prompt from the radio. Next, type L and example in the preceding project. To turn this off and get
hit Return. The radio will respond like so: back to sending data, type L and hit Return again. Then,
type --- and press Return to leave command mode.
RSSI=ff,ff
RSSI=ff,ff
Figure 8-8
The multipath effect. Reflected radio waves create phantom
beacons that the receiver can’t tell from the real beacon, causing
errors in calculating the distance based on signal strength.
HOW TO LOCATE (ALMOST) ANYTHING 277
In order to locate it within a two- or three-dimensional The Global Positioning System uses trilateration to determine
space, though, you need to know more than distance. The an object’s position. GPS uses a network of satellites circling
most common way to do this is by measuring the distance the globe. The position of each satellite can be determined
from at least three points. This method is called trilatera- from its flight path and the current time. Each one is broad-
tion. If you measure the object’s distance from two points, casting its clock signal, and GPS receivers pick up that
you get two possible places it could be on a plane, as broadcast. When a receiver has at least three satellites,
shown in Figure 8-9. When you add a third circle, you have it can determine a rough position using the time difference
one distinct point on the plane where your object could between transmission and reception. Most receivers use at
be. A similar method, triangulation, uses two known points least six satellite signals to calculate their position, in order
and calculates the position using the distance between to correct any errors. Cell phone location systems like
these points; it then uses the angles of the triangle formed Wireless E911 calculate a phone’s approximate position in
by those points and the position you want to know. a similar fashion, by measuring the distance from multiple
cell towers based on the time difference of arrival (TDOA)
of signals from those towers.
Figure 8-9
Trilateration on a two-dimensional plane. Knowing the distance from one point defines a circle of
possible locations. Knowing the distance from two points narrows it to two possible points on the plane.
Knowing the distance from three points determines a single point on the plane.
278 MAKING THINGS TALK
Project 19
$GPGGA,180226.000,4040.6559,N,07358.1789,W,1,04,6.6,75.4,M,-34.3,M,,0000*5B
$GPGSA,A,3,12,25,09,18,,,,,,,,,6.7,6.6,1.0*36
$GPGSV,3,1,10,22,72,171,,14,67,338,,25,39,126,39,18,39,146,35*70
$GPGSV,3,2,10,31,35,228,20,12,35,073,37,09,15,047,29,11,09,302,20*7D
$GPGSV,3,3,10,32,04,314,17,27,02,049,15*73
$GPRMC,180226.000,A,4040.6559,N,07358.1789,W,0.29,290.90,220411,,*12
$GPGGA,180227.000,4040.6559,N,07358.1789,W,1,04,6.6,75.4,M,-34.3,M,,0000*5A
$GPGSA,A,3,12,25,09,18,,,,,,,,,6.7,6.6,1.0*36
$GPRMC,180227.000,A,4040.6559,N,07358.1789,W,0.30,289.06,220411,,*1C
HOW TO LOCATE (ALMOST) ANYTHING 279
RN-42
Connect
Stat
Gnd
Gnd
Vcc
1PPS
Vcc
5V out
GND
GND
RX
TX
RX
1 5 10 15 20
TX
GND
Vin
V in
RX
TX
A
B
C
D
E
F
G
H
I
J
1 5 10 15 20
7805
Voltage Reg Figure 8-10
EM-406a GPS receiver attached to a
In +5V Out
to battery + Bluetooth radio. In order to get a real
GPS signal, you’ll have to go outside,
to battery - so wireless data and a battery power
source are handy.
GND
There are several types of sentences within the NMEA dollar sign ($), followed by five letters that identify the
protocol, and each serves a different function. Some tell type of sentence. After that come each of the parameters
you your position, some tell you about the satellites in of the sentence, separated by commas. An asterisk comes
view of the receiver, some deliver information about your after the parameters, then a checksum, then a carriage
course heading, and so on. Each sentence begins with a return and a linefeed.
280 MAKING THINGS TALK
information almost any application Status of the data (valid or not valid) A = valid data (V = not valid)
might need. This sentence contains the
information shown in the table. Latitude 4043.8432 or 40°43.8432'
Figure 8-11
The output of the Processing
GPS parser.
HOW TO LOCATE (ALMOST) ANYTHING 281
8
The setup() method sets the void setup() {
window size, defines the drawing size(400, 400); // window size
parameters, and opens the serial port.
// settings for drawing:
noStroke();
smooth();
8
drawArrow() is called by the void drawArrow(float angle) {
draw() method. It draws the arrow // move whatever you draw next so that (0,0) is centered on the screen:
and the circle. translate(width/2, height/2);
// if the first item in the sentence is the identifier, parse the rest
if (items[0].equals("$GPRMC")) {
// $GPRMC gives time, date, position, course, and speed
getRMC(items);
}
if (items[0].equals("$GPGGA")) {
// $GPGGA gives time, date, position, satellites used
getGGA(items);
}
if (items[0].equals("$GPGSV")) {
// $GPGSV gives satellites in view
satellitesInView = getGSV(items);
}
}
northSouth = data[4];
longitude = minutesToDegrees(float(data[5]));
eastWest = data[6];
heading = float(data[8]);
»
int date = int(data[9]);
284 MAKING THINGS TALK
When you run this sketch, it may take several GPS and cellular location tracking together. So, even if
minutes before you get a position. Different they don't have enough satellite signals, they can generally
receivers take varying times to acquire an initial determine their position relative to the nearest cell towers,
position when first started, or when moved to a new place and—using the known locations of those towers—approxi-
on the planet. So, pick a spot with a clear view of the skies mate a fix.
and be patient. Pay attention to the number of satellites in
view as well. If that number is less than four, your receiv- NMEA 0183 is just one of many protocols used in mapping
er's not going to acquire a position too well. Satellites GPS data. You'll learn about a few more, as well as some
move, though, so if you don't get anything, wait a half-hour tools for using them to map routes and locations, in
or so and try again. Chapter 11. The great thing about NMEA, though, is that
it's nearly ubiquitous among GPS receivers. No matter
Many mobile phones on the market these days feature a what other protocols they use, they all seem to have NMEA
GPS receiver, and seem to have a signal most of the time, as an option. So it's a good one to know about no matter
which may make you wonder why your receiver can't get a what GPS tools you're working with.
signal as fast. Remember, mobile phones tend to use both X
There are many GPS receiver modules on the market, and receiver mentioned in this project because it gets good
it can get confusing choosing the right tools for this job. reception, acquires a fix fast, and has been the most reliable
Here are a few things to consider. compared to others I've tested. There are other good ones,
though. Spark Fun has a nice GPS receiver buying guide on
Most common GPS receivers communicate with the their site.
microcontroller via TTL serial, using the NMEA 0183
protocol. So when it comes to connecting them to your To connect a GPS receiver, all you need is a serial transmit
microcontroller, and reading their data, they're largely connection, power, and ground. There are some shields
interchangeable. The big difference between them is how available that allow you to mount a receiver to your Arduino,
well they receive a GPS signal, which is influenced by how but they're optional. You need only three wires.
many channels they receive (generally more is better),
what kind of antenna they have (generally larger is better), Images courtesy of Spark Fun. Thanks to the students of
and how much power they consume. I prefer the EM-406a 2011's Wildlife Tracking class for confirming my tests.
X
EM-406a GPS receiver. D2523T GPS receiver. LS20126 receiver. Has a GPS MiniMod with GR10/
20 channels, good 50 channels, great very small antenna, but MN1010 receiver. Smallest
reception, less expensive reception, but more works decently in open I could find. Takes a long
than other alternatives. expensive. areas. time to acquire a signal.
286 MAKING THINGS TALK
Determining Orientation
People have an innate ability to determine their orientation relative to the world around
them, but objects don’t. So, orientation sensors are typically used for refining the
position of objects rather than of people. In this section, you’ll see two types of orientation
sensors:
a digital compass for determining heading relative to Earth’s magnetic field, and an
accelerometer for determining orientation relative to Earth’s gravitational field. Using
these two sensors, you can determine which way is north and which way is up.
Project 20
trical induction. The compass operates on 5V. Its pins are as follows:
MADE
I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
DIGITAL (PWM ~)
-
L 1 5 10 15 20 25 30
TX
+ UNO ON
A
B
RX ARDUINO C
D
B2
B1
A
E
RESET-EN
RESET ICSP
DRDY
W W W.A R DUIN O.CC
INT1
INT2
GND
F
VIN
1V8
SCL
SDA
3V
G
H
I
J
POWER ANALOG IN 1 5 10 15 20 25 30
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
Figure 8-12 NOTE: To calibrate the compass, rotate it slowly through 360
ST Microelectronics LSM303DLH compass connected to an degrees on a flat, level surface while in calibration mode (see
Arduino. code). When calibrating the compass, you need to know the
cardinal directions precisely. Get a magnetic needle compass
and check properly. You should calibrate away from lots of
electronic equipment and sources of magnetic energy (except
the earth). For example, in my office, needle compasses tend to
point west-southwest, so I calibrate outside, powering the whole
Arduino circuit from a battery. To calibrate the accelerometer,
rotate the module through every possible axis.
AREF
Reset GND
+3.3V D13
+5V D12
Gnd D11/PWM
Gnd D10/PWM
Vin D9/PWM
D8
Arduino
INT2 Module
INT1 D7
220Ω
DRDY D6/PWM
+5V
SDA Analog0 D5/PWM
LSM303DLH
Compass SCL A1 D4
Module D3/PWM
GND A2
VIN A3 D2
3V A4 Digital1/TX
10kΩ
1V8 A5 Digital0/RX
288 MAKING THINGS TALK
This sketch uses the Wire library to communicate via I2C This sketch also uses Alexander Brevig's Button library;
with the compass. The Wire library is encapsulated in the current Wiring version is at http://wiring.uniandes.
another library, the LSM303DLH library, originally written edu.co/source/trunk/wiring/firmware/libraries/Button;
by Ryan Mulligan of Pololu. I've made a variation on it with the current Arduino version is at http://github.com/tigoe/
a few extra functions, available at http://github.com/ Button. Download it to your libraries directory as well. Then,
tigoe/LSM303DLH. Download version 1.1.0 (the latest as restart Arduino and you're ready to begin.
of this writing) and copy the LSM303DLH folder into the X
libraries directory of your Arduino sketch directory. Note
that there is a folder called LSM303DLH inside the folder
you download. It's the inner folder that you want.
8
The main loop starts by checking void loop() {
the button. If the button is currently // if the button changes state, change the calibration state
pressed and its state has changed // and the state of the LED:
since the last check, the sketch toggles if(button.isPressed() && button.stateChanged()){
between normal mode and calibrating calibrating = !calibrating;
mode. It also changes the LED state: digitalWrite(buttonLed, calibrating);
on means you're calibrating, off means }
normal mode.
HOW TO LOCATE (ALMOST) ANYTHING 289
Project 21
AREF
Reset GND
+3.3V D13
+5V D12
Gnd D11/PWM
Gnd D10/PWM
Vin D9/PWM
D8
Arduino
Module
TST D7
3V D6/PWM
X Analog0 D5/PWM
ADXL335
Accelerometer Y A1 D4
Z A2 D3/PWM
GND A3 D2
A4 Digital1/TX
A5 Digital0/RX
TX
+ UNO ON
Adafruit breakout board for the
RX ARDUINO ADXL335. This accelerometer
operates on 3.3V, so its output
range is also 0 to 3.3V. The micro-
RESET-EN
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
TST
3V
GND
292 MAKING THINGS TALK
roll
surge
yaw
pitch
heave
sway
Figure 8-14
Rotations and translations of a body
in three dimensions.
Since you know that, you can calculate the portions of the
acceleration using sines and cosines. The X-axis portion
of the acceleration is gravity * sinq, and the Y-axis portion
is gravity * cosq (remember, sine = opposite/hypotenuse,
and cosine = adjacent/hypotenuse).
HOW TO LOCATE (ALMOST) ANYTHING 293
From there, you have to calculate the portions along all acceleration = voltage / 0.3;
three axes at once. It turns out that:
Once you've got the acceleration for each axis, you can
roll = arctan (x-axis / √(y-axis2 + z-axis2)) apply the earlier trigonometric formulas to get the pitch
and roll.
and:
The following sketch reads an analog accelerometer's X
pitch = arctan (y-axis / √(x-axis2 + z-axis2)) and Y axes, calculates pitch and roll as an angle from -90
degrees to 90 degrees, and sends the results out serially.
In order to know the acceleration on each axis, though, you If you want to use this sketch with an analog accelerom-
have to convert the reading you get from the analogRead() eter other than the Adafruit ADXL335 module, rearrange
command. It's not too difficult. You already know that the the pins to match your accelerometer. If you're using a 5V
accelerometer's range is from 0 volts to 3.3 volts (because accelerometer, change the voltage calculation as well.
the accelerometer operates on 3.3 volts), and that it gets X
converted to a range from 0 to 1023. So, you can say that:
From the accelerometer's data sheet, you can find out that
the sensitivity of the accelerometer is 300 millivolts per g,
where 1g is the amount of the acceleration due to gravity.
When any axis is perpendicular to the ground, it experienc-
es 1g of force, and should read about 300 mV, or 0.3V. So,
the acceleration on each axis is the voltage reading divided
by the sensitivity, or:
Listen to It (Analog)
The /*
setup() method initializes serial com- Accelerometer reader
munications, and configures the Context: Arduino
analog-to-digital converter to take its Reads 2 axes of an accelerometer, calculates pitch and roll,
reference from the external analog and sends the values out the serial port
reference pin. */
Regardless of the accelerometer you're using, If you're using the accelerometer on the LSM303DLH
you'll find that the angle readings aren't always compass from the earlier project, you're in luck. The
accurate, and that they can be quite noisy. The Arduino library for that accelerometer does the pitch and
calculations explained above assume there are no forces roll calculations for you, and simply returns the results as
acting on the accelerometer besides gravity, but that is pitch and roll. The sketch below reads them and returns
seldom the case. As you move the accelerometer through the values as angles from -90 degrees to 90 degrees, just
space, your movement accelerates and decelerates, like the analog accelerometer sketch above.
adding more force along all three axes to the calculation. X
Generally, accelerometer data is combined with data from
gyrometers to help adjust for these forces.
void setup() {
// initialize serial and Wire, and enable the compass:
Serial.begin(9600);
Wire.begin();
compass.enable();
void loop() {
// read the compass and print the accelerometer
// X and Y readings:
compass.read();
Serial.print(compass.pitch()); // X axis angle
Serial.print(",");
Serial.println(compass.roll()); // Y axis angle
delay(100);
}
296 MAKING THINGS TALK
8
The setup() method initializes the void setup() {
window, the serial connection, and sets // draw the window:
the graphics smoothing. size(400, 400, P3D);
// calculate translate position for disc:
88You will probably need
position = width/2; to look at the output of
Serial.list() and change
// List all the available serial ports this number to match
the serial port that cor-
println(Serial.list());
responds to your micro-
controller.
// Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[2], 9600);
// only generate a serial event when you get a newline:
myPort.bufferUntil('\n');
// enable smoothing for 3D:
hint(ENABLE_OPENGL_4X_SMOOTH);
}
8
The serialEvent() method reads all void serialEvent(Serial myPort) {
the incoming serial bytes and parses // read the serial buffer:
them as comma-separated ASCII String myString = myPort.readStringUntil('\n');
values, just as you did in Project 2,
Monski pong in Chapter 2. // if you got any bytes other than the linefeed:
if (myString != null) {
myString = trim(myString);
// split the string at the commas
String items[] = split(myString, ',');
if (items.length > 1) {
pitch = float(items[0]);
roll = float(items[1]);
}
}
}
298 MAKING THINGS TALK
Figure 8-16
The output of the Processing
accelerometer sketch.
Though it may seem like a lot of work to go The advantage of having the results in degrees is that
from the raw output of an accelerometer to it's a known standard measurement, so you didn't have
the visualization shown in Figure 8-16, it's to do a lot of mapping when you sent the values to Pro-
useful to understand the process. You went from the cessing. Instead, Processing could take the output from
translation of acclerations along three axes into analog an accelerometer that gave it pitch and roll in degrees.
voltages, then converted those voltages to digital values
in the microcontroller's memory using analogRead(). You don't always need this level of standardization. For
From there, you converted the digital values into voltage many applications, all you care about is that the accel-
readings, and then converted those to acceleration mea- erometer readings are changing. However, if you want to
surements relative to the acceleration due to gravity. convert those readings into a measurement of attitude
Then, you used some trigonometry to convert the relative to the ground, the process you went through is
results to angles in degrees. the process you'll use.
X
Conclusion
When you start to develop projects that use location systems, you usually find that
less is more. It’s not unusual to start a project thinking you need to know position,
distance, and orientation, then pare away systems as you develop the project.
The physical limitations of the things you build and the spaces you build them in
solve many problems for you.
This effect, combined with your users’ innate ability to The examples in this chapter are all focused on a solitary
locate and orient themselves, makes your job much person or object. As soon as you introduce multiple par-
easier. Before you start to solve all problems in code or ticipants, location and identification become more tightly
electronics, put yourself physically in the place for which connected. This is because you need to know whose
you’re building, and do what you intend for your users to signal is coming from a given location, or what location a
do. You’ll learn a lot about your project, and save yourself given speaker is at. In the next chapter, you’ll see methods
time, aggravation, and money. crossing the line from physical identity to network identity.
X
300 MAKING THINGS TALK
9
MAKE: PROJECTS
Identification
In the previous chapters, you assumed that identity equals address. Once
you knew a device’s address on the network, you started talking. Think
about how disastrous this would be if you used this formula in everyday
life: you pick up the phone, dial a number, and just start talking. What if
you dialed the wrong number? What if someone other than the person you
expected answers the phone?
Networked objects mark the boundaries of networks, but not of the
communications that travel across them. We use these devices to send
messages to other people. The network identity of the device and the
physical identity of the person are two different things. Physical identity
generally equates to presence (is it near me?) or address (where is it?), but
network identity also takes into consideration network capabilities of the
device and the state it’s in when you contact it. In this chapter, you’ll learn
some methods for giving physical objects network identities. You’ll also
learn ways that devices on a network can learn each other’s capabilities
through the messages they send and the protocols they use.
1 3
9
2
10
13
14
11
4
12
8
15 6
5
7
Figure 9-1. New parts for this chapter: 1. Prototyping shield 2. X10 interface module 3. X10 lamp module or
4. X10 appliance module 5. Four-wire telephone (RJ-11) cable 6. Perforated circuit board 7. Eight-wire Ethernet
cable 8. EM4001 RFID tags 9. Mifare RFID tags 10. ID Innovations ID-12 or ID-20 125kHz RFID reader 11. Spark
Fun 13.56 MHz RFID board or 12. TinkerKit RFID shield 13. Antenna for SM130 RFID reader 14. Extra-long female
header pins 15. 2x16 LCD screen. Don't forget plenty of male header pins for the breakout boards.
IDENTIFICATION 303
»» 0.1-inch male header pins J 103377, D A26509-20ND, »» 1 220-ohm resistor D 220QBK-ND, J 690700,
SF PRT-00116, F 1593411 F 9337792, RS 707-8842
»» RFID tags Get the tags that match your reader. All the »» Interface module: X10 One-Way Interface Module
retailers listed sell tags that match their readers in a SH 1134B
variety of physical packages, so choose the ones you »» 2 X10 modules Either: 2 appliance modules from
like best. The examples use EM4001 tags, which are Smarthome, part number 2002; or 2 Powerhouse X10
interchangeable with EM4102 tags. lamp modules from Smarthome, part number 2000.
CR WON002, SF COM-10169 You’ll need two modules total. Choose one of each,
»» 1 FTDI USB-to-Serial adapter You could use the one or two of one as you see fit. If you’re going to control
you’ve been using throughout this book in conjunction incandescent lamps only, get lamp modules. For
with the RFID breakout board mentioned above. If you anything else, get appliance modules.
want a breakout that’s designed specifically for your »» 4-wire phone cable with RJ-11 connector
reader, you can use the RFID USB reader from Spark You can take this from any discarded phone,
Fun, part SEN-09963. or get one at your local electronics shop.
SF DEV-09718 or DEV-09716, AF 70, A A000059, D A1642R-07-ND, J 115617, F 1335141
M MKAD22, SS PRO101D2P, D TTL-232R-3V3 or TTL-
232R-5V PROJECT 27: Tweets from RFID
»» 1 SonMicro SM130 RFID read/write module SF SEN-
PROJECT 26: RFID Meets Home Automation 10126
»» 1 Arduino module An Arduino Uno or something based »» 3 Mifare RFID read/write tags SF SEN-10127
on the Arduino Uno, but the project should work on »» 1 Arduino Ethernet board A A000050
other Arduino and Arduino-compatible boards. Alternatively, an Uno-compatible board (see Chapter 2)
D 1050-1019-ND, J 2121105, SF DEV-09950, with an Ethernet shield will work.
A A000046, AF 50, F 1848687, RS 715-4081, SF DEV-09026, J 2124242, A A000056, AF 201,
SS ARD132D2P, MS MKSP4 F 1848680
»» 1 prototyping shield J 2124314, SF DEV-07914, AF 51, »» 1 RFID shield SF DEV-10406, A T040030 or T040031
F 1848696, SS STR104B2P, M MSMS01 »» 13.56MHz antenna Unless your reader incorporates an
»» RFID reader The ID Innovations ID-12 or ID-20 can work antenna, A C000027
in this project. The ID-20 has a slightly longer range »» 2 potentiometers J 29082, SF COM-09939, F 350072,
than the ID-12, but otherwise their operation is identical. RS 522-0625
CR IDI003 or IDI004, SF SEN-08419 »» 1 perforated printed circuit board RSH 276-150, D
»» RFID reader breakout Or use the parts below. V2018-ND, J 616673, SS STR125C2B, F 4903213, RS 159-
SF SEN-08423 5420
»» Two 2mm 10 pin female header rows Not necessary »» 1/16-inch Mat board
if using the breakout board. Samtec, like many part »» 16 pin female header rows ST MMS-110-01-L-SV, J
makers, supplies free samples of this part in small 164822, SF PRT-08272, F 1109732
quantities. »» 6 pin stackable header SF PRT-09280, AF 85
ST MMS-110-01-L-SV, J 164822, SF PRT-08272, F »» 8-conductor wire Ribbon cable or Ethernet cable will do.
1109732 D AE08A-5-ND , F 1301013
»» 2 rows of 20 0.1-inch male header pins J 103377, D »» 16x2 character LCD SF LCD-00709
A26509-20ND, SF PRT-00116, F 1593411
The parts for building the reader circuit without a shield are listed below,
»» 2mm 5-pin socket SF PRT-10519
for those who prefer that option:
»» 2mm 7-pin socket SF PRT-10518
»» RFID tags Get the tags that match your reader. All the »» 2 4.7-kilohm resistors J 691024, D CF14JT4K70CT-ND,
retailers listed sell tags that match their readers in a F 735033, RS 707-8693
variety of physical packages, so choose the ones you »» 1 solderless breadboard D 438-1045-ND, J 20723
like best. The examples use EM4001 tags, which are or 20601, SF PRT-00137, F 4692810, AF 64,
interchangeable with EM4102 tags. SS STR101C2M or STR102C2M, M MKKN2
CR WON002, SF COM-10169
»» 1 LED D 160-1144-ND or 160-1665-ND, J 34761 or 94511,
F 1015878, RS 247-1662 or 826-830, SF COM-09592 or
COM-09590
304 MAKING THINGS TALK
Physical Identification
The process of identifying physical objects is such a fundamental part of our experience
that we seldom think about how we do it. We use our senses, of course: we look at, feel,
pick up, shake and listen to, smell, and taste objects until we have a reference—then we
give them a label. The whole process relies on some pretty sophisticated work by our
brains and bodies, and anyone who’s ever dabbled in computer vision or artificial intel-
ligence in general can tell you that teaching a computer to recognize physical objects is
no small feat. Just as it’s easier to determine location by having a human narrow it down
for you, it’s easier to distinguish objects computationally if you can limit the field—and if
you can label the important objects.
Just as we identify things using information from our Like locations, identities become more uniquely descrip-
senses, so do computers. They can identify physical tive as the context they describe becomes larger. For
objects only by using information from their sensors. example, knowing that my name is Tom doesn’t give you
Two of the best-known digital identification techniques much to go on. Knowing my last name narrows it down
are optical recognition and radio frequency identification some more, but how effective that is depends on where
(RFID). Optical recognition can take many forms, from you’re looking. In the United States, there are dozens of
video color tracking and shape recognition to the ubiq- Tom Igoes. In New York, there are at least three. When you
uitous barcode. Once an object has been recognized by need a unique identifier, you might choose a universal
a computer, the computer can give it an address on the label, like using my Social Security number, or you might
network. choose a provisional label, like calling me “Frank’s son,
Tom.” Which you choose depends on your needs in a
The network identity of a physical object can be centrally given situation. Likewise, you may choose to identify
assigned and universally available, or it can be provisional. physical objects on a network using universal identifiers,
It can be used only by a small subset of devices on a or you might choose to use provisional labels in a given
larger network or used only for a short time. RFID is an temporary situation.
interesting case in point. The RFID tag pasted on the side
of a book may seem like a universal marker, but what it The capabilities assigned to an identifier can be fluid as
means depends on who reads it. The owner of a store may well. Considering the RFID example again: in the store,
assign that tag’s number a place in his inventory, but to a given tag’s number might be enough to set off alarms
the consumer who buys it, it means nothing unless she at the entrance gates, or to cause a cash register to add
has a tool to read it and a database in which to categorize a price to your total purchase. In another store, that
it. She has no way of knowing what the number meant to same tag might be assigned no capabilities at all, even
the store owner unless she has access to his database. if it’s using the same protocol as other tags in the store.
Perhaps he linked that ID tag number to the book’s title, or Confusion can set in when different contexts use similar
to the date on which it arrived in the store. Once it leaves identifiers. Have you ever left a store with a purchase
the store, he may delete it from his database, so it loses and tripped the alarm, only to be waved on by the clerk
all meaning to him. The consumer, on the other hand, may who forgot to deactivate the tag on your purchase? Try
link it to entirely different data in her own database, or she walking into a Barnes & Noble bookstore with jeans you
may choose to ignore it, relying on other means to identify just bought at a Gap store. You’re likely to trip the alarms
it. In other words, there is no central database linking because the two companies use the same RFID tags, but
RFID tags and the things to which they’re attached or the they don’t always set their security systems to filter out
people who possessed them. tags that are not in their inventory.
IDENTIFICATION 305
Figure 9-2
Video color recognition in
Processing, using the code in
Project 22. This simple sketch
works well with vibrantly pink
monkeys.
Video Identification
All video identification relies on the same basic method: page, then follow the directions to install OpenCV on your
the computer reads a camera’s image and stores it as a platform. Download the Processing OpenCV library and
two-dimensional array of pixels. Each pixel has a char- copy it to the libraries directory of your Processing sketch-
acteristic brightness and color that can be measured book directory (find it listed in Processing’s preferences).
using any one of a number of palettes: red-green-blue is Now you’re all set to build the examples below.
a common scheme for video- and screen-based applica-
tions, as is hue-saturation-value. Cyan-magenta-yellow- NOTE: The current home of OpenCV for Processing as of this
black is common in print applications. The properties of writing is at http://ubaa.net/shared/processing/opencv. A new
the pixels, taken as a group, form patterns of color, bright- version is in the works, so check the Processing site for the most
ness, and shape. When those patterns resemble other up-to-date link.
patterns in the computer’s memory, it can identify those
patterns as objects. Figure 9-2 shows an example, using a Color Recognition
bright pink monkey. Recognizing objects by color is a relatively simple process,
if you know that the color you’re looking for is unique in
In the three projects below, you’ll use a computer-vision the camera’s image. This technique is used in film and
library called OpenCV to read an image from your personal television production to make superheroes fly. The actor
computer’s camera or webcam, and then analyze the is filmed against a screen of a unique color, usually green,
image. The first, and simplest, will look for a color. The which isn’t a natural color for human skin. Then, the pixels
second will look for something resembling a face. The third of that color are removed, and the image is combined with
will look for a 2D barcode called a QR (Quick Response) a background image.
code.
Color identification can be an effective way to track
OpenCV is a computer-vision library originally developed physi-cal objects in a controlled environment. Assuming
by Intel and released under an open source license. It’s you’ve got a limited number of objects in the camera’s view,
been adapted for many programming environments, and each object’s color is unique and doesn’t change with
including Processing. The Processing version can be found the lighting conditions, you can identify each object reason-
linked off the Processing site at http://processing.org/ ably well. Even slight changes in lighting can change the
reference/libraries/. Follow the OpenCV link from that color of a pixel, however, so lighting conditions need to be
tightly controlled, as the following project illustrates.
X
306 MAKING THINGS TALK
Project 22
The setup() sets the initial condi- // import the opencv library:
tions as usual, in this case, initial- import hypermedia.video.*;
izing OpenCV using the first camera
available to your computer, sizing the OpenCV opencv; // opencv instance
window, and initializing smooth, anti- int[] pixelArray; // array to copy the pixel array to
alised graphics. color trackColor; // the color you're looking for
void setup() {
NOTE: Because the OpenCV application // initialize the window:
uses the first camera available, you may size( 640, 480 );
have problems if you have both a built-in
camera on a laptop and an external webcam. // initialize opencv
One solution is to open the camera you opencv = new OpenCV( this );
don’t want to use in another application, opencv.capture( width, height );
so only the one you want is available to // Start off tracking for red
OpenCV. It’s a crude solution, but it works. trackColor = color(255, 0, 0);
// draw smooth edges:
smooth();
}
IDENTIFICATION 307
8 Next comes a pair of nested for // Begin loop to walk through every pixel
loops that iterates over the rows and for (int x = 0; x < opencv.width; x++ ) {
columns of pixels. This is a standard for (int y = 0; y < opencv.height; y++ ) {
algorithm for examining all the pixels // calculate the pixel's position in the array
of an image. With each pixel, you // based on its width and height:
determine its position in the array with int loc = x + y*opencv.width;
the following formula (which you’ll see // get the color of the current pixel:
frequently.) color currentColor = pixelArray[loc];
float r1 = red(currentColor);
arrayLocation = x + (y * width); float g1 = green(currentColor);
float b1 = blue(currentColor);
Once you have the pixel’s position, you float r2 = red(trackColor);
extract the red, green, and blue values, float g2 = green(trackColor);
as well as the values for the color you float b2 = blue(trackColor);
wish to track.
8 Next, calculate the difference between // use the dist() function to figure the aggregate color
the two colors. By treating the red, green, // of the current pixel. This method treats the red, green, and blue
and blue values of each color as positions // of the current pixel's color and of the target color as
in 3-dimensional space, you can find the // coordinates
difference by calculating the Euclidean // in 3D space and calculates the difference between them
distance between them. Processing’s dist() // as Euclidean distance.
function is handy for this. // In this formula, closer distance = closer color similarity:
float d = dist(r1, g1, b1, r2, g2, b2);
Once you know the difference, compare
that to the closest match so far (which was // If current color is more similar to tracked color than
set arbitrarily high for the first match). If the // closest color, save current location and current difference
current difference is less than the closest if (d < closestMatch) {
match, the current pixel is the new closest closestMatch = d;
match. closestX = x;
closestY = y;
}
}
»
}
308 MAKING THINGS TALK
8 Once you have the closest match, Continued from previous page.
the nested for loops are over. All that
remains in the draw() method is to see // Only consider the color found if its color distance is less than
whether the closest match is less than // the color threshold. For greater color accuracy, make this lower.
the threshold you set as an acceptable // For more forgiving matching, make it higher:
match. If it is, draw a circle there. if (closestMatch < colorThreshold) {
// Draw a circle at the tracked pixel
fill(trackColor);
strokeWeight(2.0);
stroke(0);
ellipse(closestX, closestY, 16, 16);
}
}
Lighting for Color Tracking • Regular LEDs don’t work well as color-tracking objects
As you can see when you run this sketch, it’s not the most unless they’re relatively dim. Brighter LEDs tend to show
robust color tracker! The closest match tends to jump up as white in a camera image because their brightness
around a lot. Changing the color- overwhelms the camera’s sensor.
Threshold helps, but not a lot. You can get it to be more • Color recognition doesn’t have to be done with a
precise by controlling the image and the lighting very camera; color sensors can do the same job. Texas
carefully. There are some lighting tricks you can use as Advanced Optoelectronic Solutions (www.taosinc.com)
well: makes a few different color sensors, including the TAOS
TCS230. This sensor contains four photodiodes, three
• DayGlo colors under ultraviolet fluorescent lighting tend of which are covered with color filters; the fourth is not,
to be the easiest to track, but they lock you into a very so it can read red, green, blue, and white light. It outputs
specific visual aesthetic. the intensity of all four channels as a changing pulse
• Objects that produce their own light are easier to track, width. The cheaper TAOS TSL230R has no LEDs—it
especially if you put a filter on the camera to block just detects ambient color. Other color sensors are
out stray light. A black piece of 35mm film negative (if available as well. Their shortcoming is that they are
you can still find 35mm film!) works well as a visible designed to detect color only relatively close (within a
light filter, blocking most everything but infrared light. few centimeters), and they don’t have the ability to see
Two polarizers, placed so that their polarizing axes are a coherent image. They are basically one-pixel camera
perpendicular, are also effective. Infrared LEDs track sensors.
very well through this kind of filter, as do incandescent
flashlight lamps.
IDENTIFICATION 309
Project 23
The setup() is similar, but this time, OpenCV opencv; // new instance of the openCV library
you’re going to have OpenCV look for
detection pattern using the library’s
cascade() method. The available void setup() {
patterns are described on the Process- // initialize the window:
ing OpenCV site at http://ubaa.net/ size( 320,240 );
shared/processing/opencv/opencv_ // initialize opencv:
cascade.html. opencv = new OpenCV( this );
opencv.capture( width, height );
Finally, the setup() sets the drawing // choose a detection description to use:
conditions for ellipses, so you can draw opencv.cascade( OpenCV.CASCADE_FRONTALFACE_DEFAULT );
circles over the faces. // draw smooth edges:
smooth();
// set ellipses to draw from the upper left corner:
ellipseMode(CORNER);
}
IDENTIFICATION 311
Figure 9-3
The face detection finds
me fairly well.
Turning sideways, I
disappear.
Figure 9-4
Barcode Recognition A one-dimensional
A barcode is simply a pattern of dark and light lines or cells barcode. This is the ISBN
used to encode an alphanumeric string. A computer reads bar code for this book.
Project 24
import hypermedia.video.*;
import pqrcode.*;
void setup() {
// initialize the window:
size(400, 320);
// initialize opencv:
opencv = new OpenCV( this );
opencv.capture( width, height );
8
The pqrcode library has a method void keyReleased() {
called decodeImage(). To use it, pass it String code = "";
an image in the keyReleased() method. // Depending on which key is hit, do different things:
A switch statement checks to see switch (key) {
which key has been pressed. If you type case ' ': // space bar takes a picture and tests it:
f, it passes the decoder a file called // Decode the image:
qrcode.png from the data subdirectory. decoder.decodeImage(opencv.image());
If you press the space bar, it passes the break;
camera image. If you type s, it brings case 'f': // f runs a test on a file
up a camera settings dialog box. PImage preservedFrame = loadImage("qrcode.png");
// Decode the file
decoder.decodeImage(preservedFrame);
break;
}
}
image, you wait. When it’s decoded // When the decoder object finishes
the image, it generates a decoder- // this method will be invoked.
Event(), and you can read the tag’s ID void decoderEvent(Decoder decoder) {
using the getDecodedString() method. statusMsg = decoder.getDecodedString();
}
IDENTIFICATION 315
Radio Frequency There are two types of RFID system: passive and active,
just like distance-ranging systems. Passive RFID tags
Identification (RFID) contain an integrated circuit that has a basic radio
Like barcode recognition, RFID relies on tagging objects transceiver and a small amount of nonvolatile memory.
in order to identify them. Unlike barcodes, however, RFID They are powered by the current that the reader’s signal
tags don’t need to be visible to be read. An RFID reader induces in their antennas. The received energy is just
sends out a short-range radio signal, which is picked up by enough to power the tag to transmit its data once, and the
an RFID tag. The tag then transmits back a short string signal is relatively weak. Most passive readers can only
of data. Depending on the size and sensitivity of the read tags a few inches to a few feet away.
reader’s antenna and the strength of the transmission,
the tag can be several feet away from the reader, enclosed In an active RFID system, the tag has its own power supply
in a book, box, or item of clothing, and still be read. In fact, and radio transceiver, and it transmits a signal in response
some clothing manufacturers are now sewing RFID tags to a received message from a reader. Active systems can
into their merchandise, which customers remove after transmit for a much longer range than passive systems,
purchasing. and they are less error-prone. They are also much more
expensive. If you’re a regular automobile commuter, and
you pass through a toll gate during your commute, you’re
probably an active RFID user. Systems like E-ZPass use
active RFID tags so that the reader can be placed several
meters away from the tag.
316 MAKING THINGS TALK
You might think that because RFID is radio-based, you Figure 9-6
could use it to do radio distance ranging as well, but that’s The field of an RFID reader, by Timo Arnall. This stop-motion
not the case. Neither passive nor active RFID systems are photo shows the effective range and shape of the RFID reader’s
typically designed to report the signal strength received field. The reader shown is an ID Innovations ID-20, which you’ll see
in the next project.
from the tag. Without this information, it’s impossible
to use RFID systems to determine the actual location of
a tag. All the reader can tell you is that the tag is within to different frequencies, there are also different protocols.
reading range. Although some high-end systems can For example, in the 13.56 band alone, there are the ISO
report the tag signal strength, the vast majority of readers 15693 and ISO 14443 and 14443-A standards. Within the
are not made for location as well as identification. ISO 15693 standard, there are different implementations
by different manufacturers—Philips’ I-Code, Texas Instru-
RFID systems vary widely in cost. Active systems can cost ments’ Tag-IT HF, Picotag—as well as implementations by
tens of thousands of dollars to purchase and install. Com- Infineon, STMicroelectronics, and others. Within the ISO
mercial passive systems can also be expensive. A typical 14443 standard, there’s Philips’ Mifare and Mifare UL, ST’s
passive reader that can read a tag a meter away from SR176, and others. So, you can’t expect one reader to read
the antenna typically costs a few thousand dollars. At the every tag. You can’t even count on one reader to read all
low end, short-range passive readers can come as cheap the tags in a given frequency range. You have to match the
as $30 or less. As of this writing, $30 to $100 gets you a tag to the reader.
reader that can read a few inches. Anything that can read
a longer distance will be more expensive. There are a number of cheap and simple readers on the
market now, covering the range of passive RFID frequen-
There are many different RFID protocols, just as with cies and protocols. ID Innovations makes a range of small,
barcodes. Short-range passive readers come in at least inexpensive, and easy-to-use 125kHz readers with a serial
three common frequencies: two low-frequency bands output. The smallest of these is less than 1.5 inches on a
at 125 and 134.2kHz, and high-frequency readers at side and is capable of reading the EM4001 protocol tags.
13.56MHz. The higher-frequency readers allow for faster Spark Fun and CoreRFID both sell these readers and
read rates and longer-range reading distances. In addition matching tags. You’ll use one of these in the next project.
IDENTIFICATION 317
Figure 9-7
RFID tags in all shapes and sizes. All
of thes items have RFID tags in them.
Photo by Timo Arnall. For more infor-
mation on RFID design research by
Arnall and his colleagues, see www.
nearfield.org.
Parallax sells a 125kHz reader that can also read EM Micro- research carefully in advance, because not all readers will
electronic tags, such as EM4001. It has a built-in antenna, read all tags. Pet tags can be some of the trickiest—many
and the whole module is about 2.5" x 3.5" on a flat circuit of them operate in the 134.2kHz range, in which there are
board. The ID Innovations readers and the Parallax readers fewer readers to choose from.
can read the same tags. The EM4001 protocol isn’t as
common in everyday applications as the Mifare protocol, You also have to consider how it behaves when tags are in
a variation on the ISO 14443 standard in the 13.56MHz range. For example, even though the Parallax reader and
range. Mifare shows up in many transit systems, like the the ID Innovations readers can read the same tags, they
London Tube. SonMicro makes a module that can both behave very differently when a tag is in range. The ID Inno-
read from and write to these tags, which you’ll see in the vations reader reports the tag ID only once. The Parallax
project after next. reader reports it continually until the tag is out of range.
The behavior of the reader can affect your project design,
As shown in Figure 9-7, RFID tags come in a number of as you’ll see later on.
different forms: sticker tags, coin discs, key fobs, credit
cards, playing cards, even capsules designed for injection The readers mentioned here have TTL serial interfaces, so
under the skin. The last are used for pet tracking and they can be connected to a microcontroller or a USB-to-
are not designed for human use, though there are some Serial module very easily. The ID Innovations and Parallax
adventurous hackers who have inserted these tags under readers have a similar serial behavior, so you could swap
their own skin. Like any radio signal, RFID can be read one for the other with only a few code changes to your
through a number of materials, but it is blocked by any program.
kind of RF shielding, such as wire mesh, conductive fabric X
lamé, metal foil, or adamantium skeletons. This feature
means that you can embed it in all kinds of projects, as
long as your reader has the signal strength to penetrate
the materials. Most RFID capsules are not sterilized for internal
! use in animals (humans included), and they’re
Before picking a reader, think about the environment in definitely not designed to be inserted without qualified
which you plan to deploy it, and how that affects both the medical supervision. Besides, insertion hurts. Don’t
tags and the reading. Will the environment have a lot of RFID-enable yourself or your friends. Don’t even do it
RF noise? In what range? Then, consider a reader outside to your pets—let your vet do it. If you’re really gung-ho
that range. Will you need a relatively long-range read? If so, to be RFID-tagged, make yourself a nice set of RFID-tag
look at the high-frequency readers. If you’re planning to earrings.
read existing tags rather than tags you purchase yourself,
318 MAKING THINGS TALK
Project 25
void setup() {
size(150,150);
// list all the serial ports:
println(Serial.list());
Figure 9-8
GND The ID Innovations ID-12 RFID
reader attached to an FTDI USB-
CTS
to-Serial adapter. The ID-12 has
Vcc FTDI-style pins spaced 2mm apart. Spark
USB-to-Serial Fun’s breakout board breaks it out
TX adapter to standard breadboard spacing,
RX however.
RTS
If you plan to use the ID Innova-
tions readers a lot, you might
Vdd
consider replacing this circuit with
LED Spark Fun’s RFID USB reader (part
TX no. SEN-09963), which combines
the FTDI adapter and mount for
RES ID Innovations 220Ω
the reader in one module.
GND ID12 reader Format
FTDI-style
USB-to-serial
Adapter
Gnd
Vcc
TX 1 5 10 15 20 25 30
RX A
B
C
D
E
ID12Part
Title
F
INNOVATIONS
G
H
I
J
1 5 10 15 20 25 30
320 MAKING THINGS TALK
Figure 9-9
Output of the ID Innovations Reader sketch.
When you have this sketch working, use it to test the range
of your reader to see from how far away you can read a
tag. You’ll notice that the tag has to leave the reader’s
range before it can be read a second time. You may not be
able to tell that from the screen output, but you’ll notice
that the LED goes off when the tag goes out of range,
and it turns on again when it comes back in range. Many
readers have a similar behavior. You should also see that
the reader can’t read more than one tag at a time—this is
common among all the readers mentioned here.
X
IDENTIFICATION 321
Project 26
X10 Interface
Module
X10 AC
over AC power lines
What Is X10?
X10, a communications protocol that works over AC power module is useful as a diagnostic tool because it already
lines, is designed for use in home automation. Companies works. When you can’t get the appliance or lamp modules
such as Smarthome (www.smarthome.com) and X10.com to respond to your own projects, you can at least get them
(www.x10.com) sell various devices that communicate over to respond to the control panel module—that way, you
power lines using X10: cameras, motion sensors, switch know whether the bits are passing over the power lines.
control panels, and more. It’s a slow and limited protocol, Smarthome sells versions of all four of these:
but it has been popular with home automation enthusiasts
for years because the equipment is relatively inexpensive • Interface module: X10 One-Way Interface Module, part
and easy to obtain. number 1134B. You’ll see two common versions of this:
the PL513 and the TW523. They both work essentially the
X10 is basically a synchronous serial protocol, like I2C and same way. The TW523 is a two-way module—it can send
SPI. Instead of sending bits every time a master clock signal and receive X10 signals—while the PL513 can only send.
changes, X10 devices send a bit every time the AC power
line crosses zero volts. This means that X10’s maximum • Appliance control module: X10 Appliance Module 3-Pin,
data rate is 120 bits per second in the U.S., as the AC signal part number 2002. These can control anything you can
crosses the zero point twice per cycle, and AC signals are plug into an AC socket, up to 15 Amps.
60Hz in the U.S. The protocol is tricky to program if you
have to do it yourself, but many microcontroller-develop- • Lamp control module: Powerhouse X10 Lamp Module,
ment systems include libraries to send X10 signals. part number 2000. These can control incandescent (not
fluorescent or neon) lamps only.
There are four devices that come in handy for developing
X10 projects: an interface module, an appliance control • Control panel module: X10 Mini Controller, part
module, a lamp control module, and a control panel module. number 4030.
You’ll be building your own controllers, but the control panel
IDENTIFICATION 323
MADE
I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF DIGITAL (PWM ~)
-
L 1 5 10 15 20 25 30
TX
+ UNO ON
A
B
RX ARDUINO C
D
E
RESET-EN
ID12Part
Title
RESET ICSP
INNOVATIONS
W W W.ARDUINO.CC
F
G
H
I
J
POWER ANALOG IN 1 5 10 15 20 25 30
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
+5V
Figure 9-11
Vdd The circuit for
LED the RFID-to-X10
TX project. The
AREF ID Innovations
RES ID Innovations 220Ω
Reset GND reader’s reset is
GND ID12 reader Format
+3.3V D13 connected to the
microcontroller’s
+5V D12
reset so that they
Gnd D11/PWM
will always reset
Gnd D10/PWM together.
Vin D9/PWM
D8
Arduino
Module
D7
D6/PWM
Analog0 D5/PWM PL513
A1 D4 X10 Interface
A2 D3/PWM +5V
A3 D2
A4 Digital1/TX 10KΩ
A5 Digital0/RX
324 MAKING THINGS TALK
void loop() {
// open transmission to house code A:
x10.beginTransmission(A);
Serial.println("Lights on:");
// send a "lights on" command:
x10.write(ON);
delay(500);
Serial.println("Lights off:");
// send a "lights off" command:
x10.write(OFF);
x10.endTransmission();
delay(500);
}
It’s unlikely that this will work the first time. fluorescent bulbs are generally not dimmable, and they
X10 is notorious for having synchronization are not designed for use on lamp modules either. If
problems while you’re developing the hardware you’re unsure, use an appliance module instead of a lamp
and firmware. For one thing, it doesn’t work when the module.
transmitter and receiver are on different circuits, so
you need to know which circuits in your house’s circuit- If your lights don’t turn on correctly, first unplug every-
breaker panel control which outlets. Some surge pro- thing, then set the addresses, then plug everything back in,
tectors and power strips might filter out X10 as well, so then reset the Arduino. If that fails, make sure your units
make sure that the X10 units are plugged into the wall, are on the same circuit, and eliminate surge protectors (if
not the surge protector. You can plug surge protectors you’re using them.) Try to turn the modules using a control
into X10 appliance modules, but avoid plugging them into panel module. Make sure the control panel isn’t sending an
lamp modules unless everything plugged into the surge ALL UNITS OFF signal at the same time as your Arduino. If
protector is an incandescent lamp. needed, unplug the control panel once you know the lamp
module is responding. Once you’ve got control over your
X10 lamp modules allow you to dim incandescent lights, modules, you can combine the RFID and X10 programs.
but they will control only resistive loads—that means no X
blow dryers, blenders, or anything with a motor. Compact
326 MAKING THINGS TALK
The global variables are the X10 pin const int x10ZeroCrossing = 2; // x10 zero crossing pin
and SoftwareSerial pin numbers, the const int x10Tx = 3; // x10 transmit pin
number of tags being used, and a const int x10Rx = 4; // x10 receive pin (not used)
bunch of arrays for the tag IDs, unit const int rfidRx = 7; // rfid receive pin
names, and unit states. const int rfidTx = 8; // rfid transmit pin (not used)
int numTags = 2; // how many tags in your list
The setup() method initializes serial,
software serial, and X10, then sends an String currentTag; // String to hold the tag you're reading
ALL LIGHTS OFF code to reset all the // lists of tags, unit names, and unit states:
remote X10 units. String tag[] = {
"10000CDFF7","0F00AD72B5"};
int unit[] = {
UNIT_1, UNIT_2};
int unitState[] = {
OFF, OFF};
SoftwareSerial rfid(rfidRx,rfidTx);
void setup() {
// begin serial:
Serial.begin(9600);
rfid.begin(9600);
// begin x10:
x10.begin(x10Tx, x10Rx,x10ZeroCrossing);
// Turn off all lights:
x10.beginTransmission(A);
x10.write(ALL_LIGHTS_OFF);
x10.endTransmission();
}
8
The checkTags() method checks void checkTags() {
the current tag string against the // iterate over the list of tags:
known list. When it finds the tag, it for (int thisTag = 0; thisTag < numTags; thisTag++) {
checks the state of the corresponding // if the current tag matches the tag you're on:
X10 unit from a list of unit states. Then
it sends that unit a message to change if (currentTag.equals(tag[thisTag])) {
its state from ON to OFF, or vice versa. // unit number starts at 1, but list position starts at 0:
Serial.print("unit " + String(thisTag +1));
// start transmission to unit:
x10.beginTransmission(A);
x10.write(unit[thisTag]);
// change the status of the corresponding unit:
if (unitState[thisTag] == ON) {
unitState[thisTag] = OFF;
Serial.println(" turning OFF");
}
else {
unitState[thisTag] = ON;
Serial.println(" turning ON");
}
// send the new status:
x10.write(unitState[thisTag]);
// end transmission to unit:
x10.endTransmission();
}
}
}
328 MAKING THINGS TALK
When you run this code, you’ll see that the The reader is vertical so I can’t leave my keys on it, and the
RFID reader only reads when a new tag enters inside locks are regular keys, so I have incentive to remove
its field. The ID Innovations readers don’t have the keyring once I open the front door if I want to open the
the ability to read multiple tags if more than one tag is in inner door.
the field. That’s an important limitation. It means that you X
have to design the interaction so that the person using the
system places only one tag at a time, and then removes it
before placing the second one. In effect, it means that two
people can’t place their key tags on the reader at the same
time. Users of the system need to take explicit action to
make something happen. Presence isn’t enough.
Project 27
Twitter handles to tags. In the second part, The parts for building the reader circuit without a shield are listed
below, for those who prefer that option:
you’ll build a microcontroller-based reader
»» 2 4.7-kilohm resistors
to read the data from those tags and »» 1 solderless breadboard
display it on a 2x16-character LCD display.
This links the physical identity of an RFID
tag to your network identity on Twitter.
RFID tags are often used for more than just the serial The Circuit
number stored on them. In some mass-transit systems, The SonMicro SM130 RFID reader operates on 5 volts, and
the customer’s available balance is read from, decre- it can communicate with a microcontroller using either
mented, and written to the card with each transaction. asynchronous serial communication or synchronous serial
Some conferences use the RFID tag to store business card via I2C. You’ll see both in practice in this project. For the
information, so attendees can exchange data digitally by first part, you’ll communicate with Processing directly
tapping their cards to a reader. Near field communica- using asynchronous serial. In the second part, you’ll com-
tions (NFC) enhances this kind of exchange even further. municate with the microcontroller directly using I2C.
NFC involves both passive and active exchange, where
two devices communicate with each other over short There are two Arduino shields available to connect the
distances. NFC accommodates a number of communica- SM130 to an Arduino: the TinkerKit RFID shield and the
tions standards, including some of the RFID standards Spark Fun RFID Evaluation shield 13.56MHz. Both allow
like ISO14443A and B, which includes Mifare. Because of you to connect to either the asynchronous serial or the I2C
this, NFC devices are often compatible with Mifare RFID connections. The Spark Fun board uses solder jumpers,
readers and tags. It is starting to gain popularity in mobile which let you choose whether to connect to digital pins 7
phones and other portable devices, so look for many NFC and 8 for a software serial connection. The TinkerKit shield
and RFID applications in the near future. Projects like this has a switch that turns the serial connection hardware on
one here may become relatively commonplace. or off. The Spark Fun comes with a built-in antenna. The
TinkerKit shield has connections for an external antenna
so you can place it where you wish, relative to the board.
There’s only a difference between these two shields when If you’re not using a shield, connect the SonMicro reader
you’re communicating with the RFID reader via asynchro- to a USB-to-Serial adapter, as shown in Figure 9-13. Then
nous serial, because they use differing pins for that. When load the appropriate Arduino sketch below, and you’re
you’re communicating with the reader using I2C, as you ready to try the Processing sketch on the following pages.
will later in the project, they’re functionally identical. X
This project was built using the TinkerKit RFID shield. It’s
been tested on both, however.
Bypass It (TinkerKit) /*
TinkerKit RFID shield serial pass through
This sketch passes data from a Context: Arduino
SonMicro RFID reader on a TinkerKit */
RFID shield to the Arduino’s USB-
to-Serial adapter, bypassing the void setup() {
microcontroller. When your board is }
programmed this way, the Arduino
acts as a USB-to-Serial adapter for the void loop() {
SonMicro reader. }
/*
Bypass It (Spark Fun)
Spark Fun RFID shield serial pass through
This sketch passes data from a Context: Arduino
SonMicro RFID reader on a Spark Fun */
RFID shield to the Arduino’s hardware
serial port, and vice versa. When #include <SoftwareSerial.h>
your board is programmed this way,
the Arduino acts as a USB-to-Serial // using pins 7 and 8 (7 is the Arduino's RX, 8 is TX)
adapter for the SonMicro reader. SoftwareSerial rfid(7,8);
void setup() {
rfid.begin(19200); // set up software serial port
Serial.begin(19200); // set up serial port
}
void loop() {
// pass any hardware serial to the software serial:
if (Serial.available()) {
rfid.write(Serial.read());
}
// pass any software serial to the hardware serial:
if (rfid.available()) {
Serial.write(rfid.read());
}
}
IDENTIFICATION 331
Figure 9-13
1 5 10 15 20 25 30
SonMicro RFID reader attached to a USB-to-Serial
A
B
adapter, exploded view. The reader and antenna
C normally sit on the breadboard in the same
D
E position as shown in the I2C breadboard view in
Figure 9-14.
F
FTDI G
USB-to-Serial H
Cable I
J
RX 1 5 10 15 20 25 30
TX
Figure 9-14
Vcc SonMicro RFID reader attached to an Arduino
Gnd via I2C, exploded view, showing the connections
under the module on the breadboard. The circuit
here is basically the same as both the TinkerKit
shield and the Spark Fun shield. The I2C connec-
tions need the two 4.7-kilohm pullup resistors.
You don’t need this circuit if you’re using an RFID
shield.
MADE
I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
DIGITAL (PWM ~)
-
L 1 5 10 15 20 25 30
TX
+ UNO ON
A
B
RX ARDUINO C
D
E
RESET-EN
RESET ICSP
W W W. A RD UI NO.CC
F
G
H
I
J
POWER ANALOG IN 1 5 10 15 20 25 30
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
332 MAKING THINGS TALK
MADE
I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
DIGITAL (PWM ~)
-
L 1 5 10 15 20 25 30
TX
+ UNO ON
A
B
RX ARDUINO C
D
E
RESET-EN
RESET ICSP
W W W. A R D U I NO. CC
F
G
H
I
J
POWER ANALOG IN 1 5 10 15 20 25 30
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
Figure 9-15
SonMicro RFID reader attached to an Arduino
via I2C, normal position on the breadboard. The
module sits in the same position on the board for
the USB-to-Serial adapter circuit as well.
RF Vcc Vcc
RF GND
ANT2
RF GND Antenna
ANT1
RF GND
4.7kΩ O2
SonMicro
RFID reader O1
to A5 I2C SCL I2
to A4 I2C SDA I1
UART RX RESET
UART TX ERROR
OK
Figure 9-16 GND
SonMicro RFID reader schematic. The I2C con-
nections need pullup resistors. These resistors
are built into the TinkerKit shield and the Spark
Fun shield.
IDENTIFICATION 333
SonMicro Communications If you were reading from memory address 04, the
checksum would be as follows (note that these values are
Protocol in hexadecimal):
The SonMicro readers use a binary communications
protocol to communicate with other devices. The protocol 0x02 (length) + 0x86 (command) + 0x04 (address) = 0x8C
is similar whether you’re communicating over asynchro- (checksum)
nous serial or I2C. The I2C version looks like this:
For the asynchronous serial protocol, the header byte is
Length Command Data Checksum always 0xFF, and the reserved byte is always 0. They’re
not added in the checksum, so you can use the same
1 byte 1 byte N bytes 1 byte commands and calculations as you do for the I2C version,
and just add 0xFF and 0x00 at the beginning. The replies
The serial version just adds two extra header bytes. It sent back from the reader follow this same protocol.
looks like this:
There are both Processing and Arduino libraries to handle
Header Reserved Length Command Data Checksum
this protocol so you don’t have to, but it’s useful to know
1 byte 1 byte 1 byte 1 byte N bytes 1 byte the basics. To start out, write a simple Processing sketch
that sends the command to get the firmware version, and
The commands for the reader are single-byte values. The then reads the reply. Readers come with different firmware
most common ones are shown below: versions, and you might need to change the firmware on
yours (see the sidebar on page 336), so you’ll save a lot of
troubleshooting time up front by knowing the firmware
Byte value Command
version.
0x80 Reset
When you run this sketch, you can see the responses in
0x81 Get firmware version hexadecimal at the top, and in ASCII at the bottom (see
Figure 9-17). The firmware command is the only one that
0x82 Seek for tag
returns any ASCII, because this is a binary protocol. The
0x83 Select tag select tag command returns a binary string similar to the
command protocol. It starts with the header and reserved
0x85 Authenticate byte (0xFF, 0x00), then the data length (0x06 if there’s a
tag, 0x02 if not), the command received (0x83), the tag
0x86 Read memory block
type (0x02 means Mifare classic), four bytes representing
0x89 Write memory block the tag number (0x0A, 0xD4, 0xF0, 0x28, in my case), and
the checksum (0x81). The ASCII representation, on the
0x90 Antenna power (turns on or off antenna) other hand, looks like garbage.
X
The length byte indicates the length of the command,
plus any data that goes with it. So, for example, a reset
command—which has no data to follow the command—
has a length of 1. A read command has one byte of data
indicating the address you want to read from, so the length
is 2.
void setup() {
size(500, 200); // window size
// List all the available serial ports
println(Serial.list());
// Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[2], 19200);
}
void draw() {
// Dystopian waterscape color scheme,
// by arem114, http://kuler.adobe.com/
background(#7B9B9D);
fill(#59462E);
// write the response, in hex and ASCII:
text(binaryString, 10, height/3);
text(asciiString, 10, 2*height/3);
}
void keyReleased() {
int command = 0x81; // read firmware command is the default
int dataLength = 1; // data length for both commands here is 1
if (key == 's') { // "select tag" command
command = 0x83;
}
// send command:
myPort.write(0xFF);
myPort.write(0x00);
myPort.write(dataLength);
myPort.write(command);
myPort.write(command + dataLength);
// reset the response strings:
binaryString = "";
asciiString = "";
}
Figure 9-17
Screenshots of the Processing sketch to read
SonMicro firmware, showing the results of the
read firmware command (top) and the select tag
command (bottom).
Figure 9-18
Screenshot of the Processing SonMicroWriter
sketch, showing the response to a successful
Read Block request.
»
color buttonText = #ACB0B9;
338 MAKING THINGS TALK
// print the hex values for all the bytes in the response:
»
IDENTIFICATION 339
8
TheSonMicroReader library uses /*
the Serial library to communicate with This function is called automatically whenever there's
the reader—like the Serial library—it a valid packet of data from the reader
generates an event when new data */
is available. sonMicroEvent() occurs void sonMicroEvent(SonMicroReader myReader) {
whenever there’s a response from the // get all the relevant data from the last data packet:
reader. In this sketch, you read all the lastCommand = myReader.getCommand();
parts of the response in the sonMi- lastTagType = myReader.getTagType();
croEvent() method, including the tag lastPacketLength = myReader.getPacketLength();
number, tag type, any data returned lastTag = myReader.getTagString();
from reading a memory block, the lastErrorCode = myReader.getErrorCode();
antenna status, and more. lastAntennaPower = myReader.getAntennaPower();
lastResponse = myReader.getSonMicroReading();
lastChecksum = myReader.getCheckSum();
8
The button functionality is handled }
by a separate Java class in the sketch /*
called Button. There are also a few initialize all the buttons
methods for managing the list of */
buttons, including makeButtons(), void makeButtons() {
which creates them initially, and draw- // Define and create rectangle button
Buttons(), which draws and updates for (int b = 0; b < buttonNames.length; b++) {
them. // create a new button with the next name in the list:
Button thisButton = new Button(400, 30 +b*30,
150, 20,
buttoncolor, highlight, buttonNames[b]);
buttons.add(thisButton);
}
}
/*
draw all the buttons
*/
void drawButtons() {
for (int b = 0; b < buttons.size(); b++) {
// get this button from the Arraylist:
Button thisButton = (Button)buttons.get(b);
// update its pressed status:
thisButton.update();
// draw the button:
thisButton.display();
}
IDENTIFICATION 341
/*
if one of the command buttons is pressed, figure out which one
and take the appropriate action.
*/
void doButtonAction(Button thisButton) {
// figure out which button this is in the ArrayList:
int buttonNumber = buttons.indexOf(thisButton);
Reading from Mifare Tags When you’re sure you’ve got a couple tags with Twitter
To prepare for the next part of this project, use the handles on them, you’re ready to build the next part of the
previous Processing sketch to write Twitter handles to a project: an Arduino tweet reader.
few tags in this format:
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("I've been running for:");
}
void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis()/1000);
}
344 MAKING THINGS TALK
Backlight connections
are optional. Not all
compatible LCDs
MADE
Backlight+
Backlight-
I N I TA LY have backlight connections
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
DIGITAL (PWM ~)
R/W
Gnd
Vcc
D6
D4
RS
D5
D7
En
Vo
-
L
TX
+ UNO ON
RX ARDUINO
RESET-EN
RESET ICSP
W W W.A R D U I N O.CC
POWER ANALOG IN
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
+5V
AREF
Reset GND VSS
Gnd D11/PWM RS
! If you’re using the Ethernet shield rather than the Ethernet board, you might
need to supply external power for this circuit. Together, the Ethernet shield,
RFID shield, LCD display, and Arduino draw enough current that in the moment the RFID
reader reads a tag, the circuit draws more current than USB can supply, causing the
voltage to drop. In some cases, a 220µF capacitor across power and ground of the RFID
shield will help, but if not, use an external power supply, a Power-over-Ethernet supply, or
an Ethernet board instead of the Ethernet shield/Uno combination.
IDENTIFICATION 345
So far, you’ve only used the Arduino board as a serial pass- I2C in action, try the sketch below. It sends a command to
through, but for this phase of the project, you’ll control the the reader to ask for the firmware revision, and prints the
RFID reader using the I2C protocol. The Wire library that results to the Serial Monitor. You’ll recognize some of the
comes with Arduino lets you control I2C devices. For the SonMicro communications protocol in this sketch.
main sketch, the Wire library commands will be wrapped
inside another library that’s specifically for the RFID
reader. But to make sure things are working, and to see
void setup() {
// initialize serial and I2C:
Serial.begin(9600);
Wire.begin();
// give the reader time to reset:
delay(2000);
void loop() {
}
346 MAKING THINGS TALK
When you run the firmware reader sketch, you should get This sketch looks for RFID tags and reads block 4 when
a response like this in the Serial Monitor: it finds a tag. If it finds a Twitter handle there, it makes an
HTTP call to Twitter’s XML API to get the latest tweet from
asking for firmware that Twitter user. Then it displays the result on an LCD
getting reply: I2C 2.8ÿ screen.
Regardless of what state the sketch is // Enter a MAC address and IP address for your controller below.
in, it should also update the LCD every // The IP address will be dependent on your local network:
time through the loop(). byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 };
IPAddress ip(192,168,1,20); // will only be used if DHCP fails
There are also the usual IP and IPAddress server(199,59,149,200); // Twitter's API address
»
Ethernet configuration variables. Client client; // the client connection
IDENTIFICATION 347
Finally, there are global variables for long lastRequestTime = 0; // last time you connected to the server
the various characteristics of the LCD int requestDelay = 15 * 1000; // time between HTTP requests
display and constants for the scroll-
delay potentiometer.
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(9,8, 7, 6,5, 3);
const int screenWidth = 16; // width of the LCD in characters
long lastScrollTime = 0; // last time you scrolled the LCD
int scrollDelay = 130; // delay between LCD moves
int cursorPosition = 0; // cursor position on the LCD
const int potVoltage = A0; // voltage for the scroll delay pot
const int potGround = A2; // ground for the scroll delay pot
const int potInput = A1; // scroll delay pot
»
cursorPosition++;
IDENTIFICATION 349
}
else {
cursorPosition = 0;
}
// note the last time you moved the LCD:
lastScrollTime = millis();
}
8
Finally, it updates scrollDelay by // update the speed of scrolling from the second potentiometer:
mapping the input of the potentiom- int sensorReading = analogRead(potInput);
eter on pin A1. // map to a scrolling delay of 100 - 300 ms:
scrollDelay = map(sensorReading, 0, 1023, 100, 300);
}
»
}
350 MAKING THINGS TALK
Troubleshooting Can it reach the server? If not, try the HTTP test client in
There are a lot of things that can go wrong in this sketch, Chapter 4 with the URL that this sketch calls.
so make sure you’re clear on each of the parts, and have a
plan for troubleshooting. Below are a few things to look for: Can it read the user’s tweets? Are you sure you didn’t
pick a Twitter user who protects her tweets? Or who hasn’t
Is it reaching each of the four major states? If not, tweeted yet? Put the URL in a browser and search for the
determine at which one it’s stopping. Have the sketch print <tweet> tags yourself. If they’re not there, the sketch can’t
a message when it reaches each new state, as well as the see them.
results of the previous state.
Is the LCD working? Separate this out using the Serial
Is it reading a tag? Can it read the tag’s memory Monitor. This sketch contains a number of print state-
blocks? If not, try one of the example sketches that ments to let you know what’s happening. Use them when
comes with the SonMicroReader library. In particular, the troubleshooting.
ReadBlock example was written to do a basic read of tags.
IDENTIFICATION 351
Make sure to test the circuit before you put it in the box!
+5V
D9
D8
D7
D6
D5
D3
GND
Figure 9-20 Figure 9-21
The LCD and potentiometer connections The header pin connections for the
to a perfboard. The wire colors show cable to the perfboard.
which wires correspond to those in Figure
9-18.
25
20
15
10
1
B C D
E
F G H
LINK
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
- +
I
L ETHERNET
SHIELD
J
RX
K L
RESET
ON
M
N
100M
M A D E I N I TA LY
WWW.ARDUINO.CC
ICSP
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
352 MAKING THINGS TALK
Attach the RFID antenna to the top of the box with Velcro.
A set of extra long female headers provides enough length
to hold it above the wires of the LCD circuit. You can see
the inside of the box in Figure 9-22.
Figure 9-23
The final box.
IDENTIFICATION 353
Network Identification
So far, you’ve identified network devices computationally by their address. For devices
on the Internet, you’ve seen both IP and MAC addresses. Bluetooth and 802.15.4
devices have standard addresses as well. However, the address of a device doesn’t tell
you anything about what the device is or what it does.
Recall the networked air-quality project in Chapter 4. messages—about the sender’s and receiver’s identity and
The microcontroller made a request via HTTP and the capabilities. You can use these to your advantage when
PHP script sent back a response. Because you already designing network systems like the ones you’ve seen
knew the microcontroller’s capabilities, you could send here. There’s not space to discuss this concept
a response that was short enough for it to process effi- comprehensively, but following are two examples that
ciently, and format it in a way that made it easy to read. use HTTP and mail.
But what if that same PHP script had to respond to HTTP
requests from an Arduino Ethernet, a desktop browser
like Safari or Chrome, and a mobile phone browser? How HTTP Environment Variables
would it know how to format the information? When a server-side program, such as a PHP script,
receives an HTTP request, it has access to a lot more
Most Internet communications protocols include a basic information about the server, the client, and more than
exchange of information—as part of the initial header you’ve seen thus far.
You should get something like this in your browser: SCRIPT_FILENAME: /home/username/example.com/php/09_env.php
REMOTE_PORT: 52138
#CGI __utmz: 152494652.1295382826.13.2.utmccn=(referral) REDIRECT_URL: /php/09_env.php
|utmcsr=itp.nyu.edu|utmcct=/physcomp/studio/Spring2011/ GATEWAY_INTERFACE: CGI/1.1
TomIgoe|utmcmd=referral SERVER_PROTOCOL: HTTP/1.1
__utma: 152494652.402968136.1288069605.1308754712.130876886 REQUEST_METHOD: GET
1.29 QUERY_STRING:
PATH: /usr/local/bin:/usr/bin:/bin REQUEST_URI: /php/09_env.php
REDIRECT_HANDLER: php-cgi SCRIPT_NAME: /php/09_env.php
REDIRECT_STATUS: 200 ORIG_SCRIPT_FILENAME: /dh/cgi-system/php5.cgi
UNIQUE_ID: Thtgla3sqiUAAFdwW-UAAAAP ORIG_PATH_INFO: /php/09_env.php
SCRIPT_URL: /php/09_env.php ORIG_PATH_TRANSLATED: /home/username/example.com/php/09_env.
SCRIPT_URI: http://www.example.com/php/09_env.php php
HTTP_HOST: www.example.com ORIG_SCRIPT_NAME: /cgi-system/php5.cgi
HTTP_CONNECTION: keep-alive PHP_SELF: /php/09_env.php
HTTP_USER_AGENT: Mozilla/5.0 (Macintosh; Intel Mac REQUEST_TIME: 1310417045
OS X 10_6_8) AppleWebKit/534.30 (KHTML, like Gecko)
Chrome/12.0.742.112 Safari/534.30 As you can see, there's a lot of information: the
HTTP_ACCEPT: text/html,application/xhtml+xml,application/ web server's IP address, the client's IP address, the
xml;q=0.9,*/*;q=0.8 browser type, the directory path to the script, and more.
HTTP_ACCEPT_ENCODING: gzip,deflate,sdch You probably never knew you were giving up so much
HTTP_ACCEPT_LANGUAGE: en-US,en;q=0.8 information by making a simple HTTP request, and this is
HTTP_ACCEPT_CHARSET: ISO-8859-1,utf-8;q=0.7,*;q=0.3 only a small part of it! This is very useful when you want
HTTP_COOKIE: __utmz=152494652.1295382826.13.2.utmccn=(refer to write server-side scripts that can respond to different
ral)|utmcsr=itp.nyu.edu|utmcct=/physcomp/studio/Spring2011/ clients in different ways.
TomIgoe|utmcmd=referral; __utma=152494652.402968136.12880696
05.1308754712.1308768861.29 For example, HTTP_USER_AGENT tells you the name of
SERVER_SIGNATURE: the software browser with which the client connected.
SERVER_SOFTWARE: Apache From that, you can determine whether if it’s a mobile
SERVER_NAME: www.example.com phone, desktop, or something else, and serve appropriate
SERVER_ADDR: 77.248.128.3 content for each. HTTP_ACCEPT_LANGUAGE tells you
SERVER_PORT: 80 the language in which the client would like the response.
REMOTE_ADDR: 66.168.47.40 When you combine REMOTE_ADDR with the IP geocoding
DOCUMENT_ROOT: /home/username/example.com example to follow, you can even make a reasonable esti-
SERVER_ADMIN: [email protected] mation as to where the client is, assuming its request did
not come through a proxy.
IDENTIFICATION 355
Project 28
IP Geocoding
The next example uses the client’s IP address to get its latitude and longitude. It gets
this information from www.hostip.info, a community-based IP geocoding project. The
data there is not always the most accurate, but it is free. This script also uses the HTTP
user agent to determine whether the client is a desktop browser or an Ethernet module.
It then formats its response appropriately for each device.
8
The website www.hostip.info will // use http://www.hostIP.info to get the latitude and longitude
return the latitude and longitude from // from the IP address. First, format the HTTP request string:
the IP address in a convenient XML $IpLocatorUrl = "http://api.hostip.info/?&position=true&ip=";
format. The latitude and longitude are // add the IP address:
inside a tag called <gml:coordinates>. $IpLocatorUrl .= $ipAddress;
That’s what you’re looking for. First,
format the HTTP request string and // make the HTTP request:
make the request. Then wait for the $filePath = fopen ($IpLocatorUrl, "r");
results in a while loop, and separate the
results into the constituent parts. // as long as you haven't reached the end of the incoming text:
while (!feof($filePath)) {
// read one line at a time
$line = fgets($filePath, 4096);
// if the line contains the coordinates, then you want it:
if (preg_match('/<gml:coordinates>/', $line)) {
$position = strip_tags($line); // strip the XML tags
$position = trim($position); // trim the whitespace
$coordinates = explode(",",$position); // split on the comma
$lat = $coordinates[0];
$long = $coordinates[1];
}
»
}
356 MAKING THINGS TALK
8 Now that you’ve got the location, Continued from previous page.
it’s time to find out who you’re // close the connection:
sending the results to, and format fclose($filePath);
your response appropriately. The
information you want is in the HTTP // decide on the output based on the client type:
user agent. switch ($userAgent) {
case "arduino":
// Arduino wants a nice short answer:
echo "<$lat,$long,$country>\n";
break;
case "processing":
// Processing does well with lines:
echo "Latitude:$lat\nLongitude:$long\nCountry:$country\n\n";
break;
default:
// other clients can take a long answer:
echo <<<END
<html>
<head></head>
<body>
<h2>Where You Are:</h2>
Your country: $country<br>
Your IP: $ipAddress<br>
Latitude: $lat<br>
Longitude: $long<br>
</body>
</html>
END;
}
?>
IDENTIFICATION 357
If you call this script from a browser, you’ll As you can see, this is a powerful feature. To use it, all you
get the HTML version. If you want to get the need to do is add one line to your HTTP requests from Pro-
“processing” or “arduino” responses, you’ll cessing or the microcontroller (see Chapter 3). Just add an
need to send a custom HTTP request. Try calling it from extra print statement to send the user agent, and you’re all
your terminal program, as follows. set. In Processing or Arduino, the HTTP request would now
look like this:
First, connect to the server as you did before:
// Send the HTTP GET request:
telnet example.com 80 String requestString = "/~yourAccount/ip_geocoder.php";
client.write("GET " + requestString + " HTTP/1.0\r\n");
Then send the following (press Enter one extra time client.write("HOST: example.com\r\n");
after you type that last line): client.write("USER-AGENT: processing\r\n\r\n");
GET /~yourAccount/ip_geocoder.php HTTP/1.1 Using the user agent variable like this can simplify your
HOST: example.com development a great deal. This is because it means that
USER-AGENT: arduino you can easily use a browser or the command line to
debug programs that you’re writing for any type of client.
You should get a response like this:
Figure 9-24
Permissions for the pwds.php file. Make sure that no one
can read from and write to it—besides you.
You’ll need to make sure you have at least one There’s a lot of useful information in this header. Though
unread mail message on your server for that the mail says it’s from [email protected], it’s actually
code to work. When you do, you should get from a server that’s run by myhost.com. It’s common to
something like this when you open the script in a browser: put an alias on the from: address, to assign a different
reply-to: address than the from: address, or both. It allows
number of messages: 85 sending from a script such as the cat script in Chapter 3,
yet the reply goes to a real person who can answer it. It’s
Delivered-To: [email protected] important to keep this in mind if you’re writing scripts that
Received: by 10.52.188.138 with SMTP id ga10cs129118vdc; reply to each other. If you’re using email to communicate
Sat, 28 May 2011 between networked devices, the program for each device
12:32:30 -0700 (PDT) must be able to tell the from: address from the reply-to:
Received: by 10.42.176.136 with SMTP id address—otherwise, they might not get each other’s
be8mr4324248icb.15.1306611150331; Sat, messages.
28 May 2011 12:32:30 -0700 (PDT)
Return-Path: <[email protected]> This particular message doesn’t have a field called
Received: from myhost.com (crusty.g.myhost. X-Mailer:, though many do. X-Mailer tells you which
com [67.225.8.42]) by mx.google.com with ESMTP id program sent the mail. For example, Apple Mail messages
f8si10612848icy.106.2011.05.28.12.32.29; Sat, 28 May 2011 always show up with an X-mailer of Apple Mail, followed by
12:32:29 -0700 (PDT) a version number such as (2.752.3). Like the HTTP User
Received-SPF: pass (google.com: domain of tigoe@algenib. Agent, the X-Mailer field can help you decide how to format
myhost.com designates 67.225.8.42 as permitted sender) mail messages. You could use it in a similar fashion, to tell
client-ip=67.225.8.42; something about the device that’s mailing you, so you can
Authentication-Results: mx.google.com; spf=pass (google.com: format messages appropriately when mailing back.
domain of [email protected] designates 67.225.8.42 as
permitted sender) [email protected]
Received: from algenib.myhost.com (algenib.myhost.com
[173.236.170.37]) by crusty.g.myhost.com (Postfix) with
ESMTP id 6EAC3BE813 for <[email protected]>; Sat, 28 May
2011 12:31:15 -0700 (PDT)
Received: by algenib.myhost.com (Postfix, from userid
1774740) id 00AD1156BB6; Sat, 28 May 2011 12:32:09 -0700
(PDT)
To: [email protected]
Subject: Hello world!
From: [email protected]
Message-Id: <[email protected]>
Date: Sat, 28 May 2011 12:32:10 -0700 (PDT)
360 MAKING THINGS TALK
Conclusion
The boundary between physical identity
and network identity always introduces
the possibility for confusion and miscom-
munication. No system for moving infor-
mation across that boundary is foolproof.
Establishing identity, capability, and
activity are all complex tasks, so the more
human input you can incorporate into the
situation, the better your results will be.
and to work with conductive fabrics and PROJECT 29: CatCam Redux
threads. You’ll also learn about reading »» 1 Arduino Ethernet board A A000050
Alternatively, an Uno-compatible board (see Chapter 2)
and writing from an SD card. with an Ethernet shield will work.
SF DEV-09026, J 2124242 , A 139, AF 201, F 1848680
DISTRIBUTOR KEY »» SD card reader that can read MicroSD Ethernet
• A Arduino Store (http://store.arduino.cc/ww/) shields and the Arduino Ethernet have one onboard.
• AF Adafruit (http://adafruit.com) »» MicroSD card Available at most any electronics store.
• D Digi-Key (www.digikey.com) »» IP-based camera The examples use a D-Link DCS-930L.
• F Farnell (www.farnell.com) »» Temperature sensor AF 165, D TMP36GT9Z-ND,
• J Jameco (http://jameco.com) F 1438760, RS 427-351
1
4 2
3
10
5
13
11 8
12
9
16
7
15
14
Figure 10-1. New parts for this chapter: 1. IP-based camera 2. Hoodie 3. Conductive ribbon 4. Conductive thread 5. LilyPad
Arduino Simple 6. Lithium Polymer battery charger 7. Shieldex conductive fabric 8. Embroidery thread 9. Lithium Polymer battery
10. Android device 11. TMP36 temperature sensors 12. MicroSD card 13. MicroSD card reader 14. Relay board 15. AC junction box
and socket 16. AC cord.
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 365
»» Relay Control PCB This is used to mount the rest of PROJECT 30: Phoning the Thermostat
the components below. Alternately, you can use the »» Completed Project 27
Power Switch Tail below. »» Twilio account
SF COM-09096
»» 1 Relay SF COM-00101, D T9AV1D12-12-ND, F 1629059 PROJECT 31: Personal Mobile Datalogger
»» 2 1-kilohm resistors Any model will do. »» Android device You’ll need a device running version 2.1
D 1.0KQBK-ND, J 29663, F 1735061, RS 707-8669 or later. See http://wiki.processing.org/w/Android for
»» 1 10-kilohm resistor D 10KQBK-ND, J 29911, details.
F 9337687, RS 707-8906 »» LilyPad Arduino SF DEV-09266, A A000011,
»» 1 1N4148 diode SF COM-08588, F 1081177, »» 1 Bluetooth Mate module SF WRL-09358 or WRL-
D 1N4148TACT-ND, RS 544-3480 10393
»» 1 2N3906 PNP-type transistor J 178618, »» Lithium Polymer Ion Battery SF PRT-00341, AF 258,
D 2N3906D26ZCT-ND, SF COM-00522, F 1459017, RS RS 615-2472, F 1848660
294-328 »» 1 270-kilohm resistor J 691446, D P270KBACT-ND,
»» 1 LED D 160-1144-ND or 160-1665-ND, J 34761 or 94511, RS 163-921, F 1565367
F 1015878, RS 247-1662 or 826-830, SF COM-09592 or »» Conductive ribbon SF DEV-10172
COM-09590 »» Thick conductive thread SF DEV-10120, L A304
»» 1 2-pin Screw Terminal SF PRT-08432, D 732-2030- »» Shieldit Super Conductive Fabric L A1220-14
ND, F 1792766, RS 189-5893 »» Velcro
»» 1 3-pin Screw Terminal SF PRT-08235, D 732-2031- »» Hoodie MS MKSWT
ND, F 1792767, RS 710-0166 »» Embroidery thread Available at most fabric or yarn
»» 1 Power Switch Tail This is an alternative device to shops.
the relay board, relay, and support parts above. A 240V
version is available from www.powerswitchtail.com.
SF COM-09842, AF 268, MS MKPS01
»» Cat
»» Air conditioner
»» Country estate (optional)
366 MAKING THINGS TALK
There are plenty of IP-based telephony tools that blur the down versions of what you find on a laptop, desktop, or
line between phone call and Internet connection, including tablet computer. Most smartphones also incorporate
the open source telephony server Asterisk (www.asterisk. some basic sensors, such as a camera, accelerometer,
org), as well as telephony services from companies like light sensor, and sometimes GPS. And, of course, they
Twilio (www.twilio.com), Google Voice (www.voice.google. are networked all the time. What they lack, however, is
com), and Skype (www.skype.com). These voice services the capability for adding sensors, motors, and other
are compatible with those offered by your phone company. actuators—the stuff for which microcontrollers are made.
What the phone company is giving you on top of the When you treat the phone as a multimedia computer and
software service is a network of wires and routers that mobile network gateway, you open up a whole host of pos-
prioritizes voice services, so you are guaranteed a quality sibilities for interesting projects.
of service that you don’t always get on IP-only telephony
services. Interfacing phones and microcontrollers can be done
in a number of ways, depending on the phone’s capa-
Telephony services and Internet services meet on gateway bilities. For the purposes of this chapter, I’ll be talking
servers and routers that run software to translate between about smartphones, so you can assume most or all of
protocols. For example, mobile phone carriers all offer the following capabilities, many of which you’ll use in the
SMS gateway services that allow you to send an email projects to come:
that becomes an SMS, or to send an SMS that emails the
person you want to reach. Google Voice and many of the • Programmability
other online telephony services offer voicemail-to-text, • Touchscreen or keyboard
in which an incoming call is recorded as a digital audio • Mobile network access
file, then run through voice-recognition software and • Bluetooth serial port
turned into text, and finally emailed to you. The major task • USB connection
when building projects that use the telephony network is • Microphone, speaker
learning how to convert from one protocol to another. • Onboard accelerometer
• Onboard GPS
A Computer in Your Pocket
Mobile phones are far more than just phones now. The
typical smartphone—such as an Android phone, iPhone,
Blackberry, or Windows Phone—is a computer capable of
running a full operating system. The processing power is Figure 10-2
well beyond that of older desktop machines, and smart- Possible ways of linking microcontrollers and
phones run operating systems that are slightly stripped mobile phones.
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 367
Possible distance:
local (less than 10m)
SPI
Microcontroller Phone
USB Host USB
Controller
Serial Bluetooth
Serial
Microcontroller Bluetooth Phone
Mate
Possible distance:
global
WiFi or mobile
SPI Internet network
Microcontroller Phone
Ethernet
or WiFi shield
SMS, email, or
TCP/HTTP
Mobile network
Serial
GSM shield
Microcontroller Phone
SMS, email, or
TCP/HTTP
368 MAKING THINGS TALK
There are a few possible system arrangements afforded Native Application Interfaces
by these capabilities and the kinds of things you might If you don’t want to use the browser, you can build your
want to make. Figure 10-2 shows the four most common own application on the phone to interact with the micro-
arrangements. controller via Bluetooth, network, SMS, or USB. You’ll see
an example of this using Processing for Android later in the
Three of the four options shown use wireless links. Current chapter. The advantage of building a dedicated app is that
mobile phones don’t make it easy to make a wired serial you have complete control over what happens. The disad-
link to external devices, though that is beginning to vantage is the challenge of learning a new programming
change. So, for most applications, a wireless link is the environment, as well as the limitation of not being able to
better option. It’s not often that you’d prefer your phone use your program on a phone with a different operating
be tethered to your project. system. Because most phone operating systems don’t
allow the browser to access the communications hardware
of the phone directly, you have to build an app if you plan
Start with What Happens to use local connections like Bluetooth or USB.
By now this should be a common theme to you: start with
what you want people to do with the thing you’re building, SMS and Email Interfaces
and design whatever makes that easiest to do. Are you Not every project requires real-time interaction between
making a system where your users have real-time interac- your phone and the thing you’re building. If you just want
tive control over a nearby model helicopter or boat? Are to get occasional updates from remote sensors, or you
they controlling a remote device like their home thermo- want to start a remote process that can then run by itself—
stat while on vacation? Consider how tight an interactive like turning on a sprinkler or controlling your house lights
coupling you need. Do you need real-time interaction like via a remote timer—SMS or email might be useful. You
you saw in Chapter 5, or will updates every few seconds or can make a microcontroller application that can receive
minutes be enough? And what about the distance between SMS messages using a GPRS modem, or you can write a
the devices—do you need to be able to communicate at networked server that checks email and sends messages
long range, or will a local connection like Bluetooth or USB to an Internet-connected microcontroller when it gets a
suffice? If it’s a remote connection, how will your users particular email message. The advantage of this method is
know what happened on the other side? Can they see the that you can control remote things using applications that
result? Do they get an email or SMS message telling them are already on your phone, email, and SMS.
about it? Evaluate whether you need a wired or wireless
connection, based on how the people need to move and Voice Interfaces
manipulate the devices involved. Consider what networks Don’t forget the phone’s original purpose: two-way com-
are available where you plan to use your system. Got WiFi? munication of sound over distance. Voice interfaces for
Got mobile networks? Got Ethernet? Can you create a networked devices can be simple and fun. Telephony
local network between the two devices using Bluetooth or gateways like Asterisk and Twilio allow you to use voice
WiFi? calls to generate networked actions.
Project 29
CatCam Redux
If the phone has a web browser, you don’t MATERIALS
Microcontroller
communicates with the microcontroller via SPI, as does 4. ... and the current thermostat trigger point.
the SD card on the shield or board. The temperature 5. The server sends the resulting page to the client.
sensor is an analog input, and the 120V relay to control 6. Because the cat cam image is embedded in the page,
the air conditioner is a digital output. The IP camera in this the client requests it from the IP camera.
project is a consumer item that has a built-in server, so all 7. The IP camera sends the image to the client.
you have to do is configure it to speak to your router. The 8. The client changes the trigger point via a form on the
clients are just web browsers on your smartphone, tablet, page, and submits it using HTTP POST.
or personal computer. 9. The server reads the POST request and updates the
thermostat.
Even though it seems simple enough, there are actually 10 10. The server sends back a response page.
steps to the interaction, which are listed below:
Some of this, like getting the camera image and the
1. The client makes an HTTP GET request for the main resulting page, can be solved using HTML. You won’t need
interface page (index.htm). to do any extra programming, because it will be taken care
2. The microcontroller server reads the page from the SD of by the browser when it interprets the HTML. The main
card. programming challenge is to build a basic web server on
3. The server reads the temperature... the Arduino that serves files from the SD card.
Mobile
Client
1 GET
index.htm 5
7
200 OK 6
index.htm 8
GET 200 OK
POST image.jpg image.jpg
form
200 OK
result.htm
10
Ethernet
Shield
Camera
Microcontroller
2
4
Get
Relay Get SD
index page
thermostat Card
Figure 10-4
The interaction diagram for the CatCam 2
and air conditioner controller.
Update
thermostat
9
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 371
Figure 10-7
The CatCam 2 and air conditioner circuit.
MADE
I N I TA LY
GND
AREF
3 2 1 0 9 8 7 6 5 4 3 2 1 0
9
8
7
6
5
4
PWM 3
2
TX 1
RX 0
13
12
11
10
GND
AREF
1 1 1 1 DIGITAL
RX
TX
DIGITAL (PWM ~)
PWM
PWM
PWM
PWM
PWM
1 5 10 15 20
-Arduino UNO
L L A
LOAD
TX
+ B
Gnd Cntl. 5V
TX ON
PWR C
RX
RX ARDUINO D
1
E
TMP
PWR SEL
USB 36
RESET-EN
G
H
I
J
www.arduino.cc 1 5 10 15 20
RESET
POWER ANALOG IN
POWER ANALOG IN
RESET
3V3
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V Gnd Vin 0 1 2 3 4 5
5V
372 MAKING THINGS TALK
The Circuit Spark Fun’s AC relay board is a safe and less expensive
Once you’ve got a grasp on the plan and the system, option if you want to build your own circuit. Solder the
you’re ready to build it. The circuit is shown in Figure 10-7. relay to the relay board. Then take an AC cord, cut one of
Because the SD card is on the Ethernet module (Ethernet the two wires, and attach it to the relay board’s LOAD con-
shield or Arduino Ethernet), you only need to add the tem- nections. Figure 10-5 shows a close-up of a household AC
perature sensor and the relay. cord attached to the relay. The relay’s ground, control, and
5V connections connect to your microcontroller. To build
The relay contains a coil wrapped around a thin switch. a more robust version—such as the one shown in Figure
When the coil gets voltage, it forms a magnetic field 10-6—with a household electrical outlet junction box, see
through induction, pulling the two sides of the switch Nathan Seidle’s excellent tutorial at www.sparkfun.com/
together. To use it, take an alternating current circuit tutorials/119.
(AC) and break one of the wires, as shown in Figures 10-5
through 10-7. To test the circuit safely before you plug it in, set your mul-
timeter to measure continuity, and to measure between
Working with AC can be dangerous, so make sure every- one of the plug’s pins and the corresponding socket hole
thing is connected properly before plugging it in. If you’re on the other end of the cord. One pin/hole pair should
uncomfortable building an AC circuit, the Power Switch have continuity all the time. The other should not, unless
Tail will allow you to control 120V AC. A 240V version was you power the 5V and ground contacts of the relay and
recently announced at www.powerswitchtail.com. It’s connect the control line to 5V. Then you’ll get continuity.
available from Adafruit, Spark Fun, and the Maker SHED. When you connect the control line to ground, you won’t
get continuity. When you’re sure the circuit’s working, test
it by attaching the control line to a pin of your microcon-
troller and use the Blink sketch to turn the relay on and off.
Figure 10-8
The CatCam 2 and air conditioner schematic.
AREF
Reset GND
+3.3V D13 To Ethernet shield Clock
Vin D9/PWM
D8
Arduino
Module
D7
Vin 0.1µF
D6/PWM
TMP36
Temperature Out Analog0 D5/PWM
sensor
Gnd A1 D4 To Ethernet shield SD card. SS
A2 D3/PWM Relay
A3 D2
AC power
A4 Digital1/TX
A5 Digital0/RX
AC cord outlet
for air conditioner
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 373
Make sure to install your circuit in an insulated box and The Code
add plenty of strain relief to the AC lines. If they acci- Since the sketch is complex, it’s built up piece-by-piece
dentally disconnect, they can cause a short circuit—and below, as follows:
AC shorts are not pleasant. An electronic project case is
safest. You can add strain relief to the wires by using hot 1. Read the temperature sensor (for more on this sensor,
glue or rubber caulking, though some cases come with see Adafruit’s tutorial at www.ladyada.net/learn/
wire strain relief glands to hold the wire in place. Once sensors/tmp36.html).
you’ve done that, give the wires a tug to make sure they 2. Control the relay.
won’t move. Take your time and get this part very secure 3. Read from the SD card.
before you proceed. 4. Write a web server. This one will be more full-featured
than the one you wrote in Chapter 4.
Writing to an SD Card
Arduino's SD library makes it easy to write to an SD card,
and there are several SD card-mount options available. All
of them use the SPI synchronous serial protocol that the
Arduino Ethernet shield and Ethernet board use to com-
GND
CLK
DO
CD
5V
3V
CS
DI
municate with the Ethernet chip. As you saw in Chapter
4, this protocol can be used with a number of different
devices, all attached to the same serial clock and data
pins, but each device will need its own Chip Select pin. The
Arduino communicates with all SPI devices through pin 11 MADE
I N I TA LY
for MOSI (Master Out, Slave In), Pin 12 for MISO (Master
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
DIGITAL (PWM ~)
In, Slave Out), and pin 13 for Clock. The Arduino Ethernet
-
L
shield and board use pin 10 for the Ethernet module's Chip TX
+ UNO ON
RX ARDUINO
Select, and pin 4 for the SD card's Chip Select. SD boards
from other companies use other pins for chip select.
RESET-EN
RESET ICSP
Spark Fun's SD card shield uses pin 8, and Adafruit's SD
W W W. A R D U I N O. CC
card breakout board (shown in Figure 10-9) uses pin 10.
Whenever you're using multiple SPI devices in a project,
POWER ANALOG IN
like the Ethernet and the SD card together, you need to
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
check to see that they all have individual Chip Select pins.
Figure 10-9
SD cards operate on 3.3V only! So if you're using a socket The Adafruit SD card shield connected to the
that attaches your SD card directly to the pins of any Arduino using the SPI pins 11 (MOSI), 12 (MISO), and
microcontroller operating 5 volts, you need to make sure 13 (Clock). Different SPI card boards use different
pins for the Chip Select pin, however. This one uses
the input pins receive only 3.3V.
pin 10.
Good SD Card Practice are not allowed. So, datalog1.txt and mypage.htm are OK, but
To get the most reliable results out of an SD card shield really long file name or someArbitraryWebPage.html are not.
or an adapter with an Arduino, there are some habits you
should develop. Writing to the card takes time. Normally, the file write(),
print(), and println() operations saves data in a volatile
Never insert or eject the card while the sketch is buffer on the card, which is lost when the card is removed.
running. You’d never pull a card out of your computer Only the flush() or close() operations save to the card per-
while it’s in use, and the same goes for the Arduino. Make manently, but they take time. To keep up with user inter-
sure the microcontroller’s not using the card when you action, use flush() and close() the way you would to save
insert or remove it. The simplest way to do this is to hold a file on a regular computer: do it frequently, but not too
the reset button of the Arduino whenever you’re inserting frequently, and preferably when the user or other devices
or removing the card. aren’t doing anything else.
Format cards as FAT16 or FAT32. The SD card library Practice safe file management. The SD library gives
works only with these two file formats. Fortunately, every you some helpful tools for managing your files. filename.
operating system can format disks this way. Check your exists() lets you check whether a file already exists.
operating system’s disk-utility application for how to if (filename) lets you check whether the file can be
format your card as FAT16 or FAT32. accessed. filename.remove() lets you remove a file. size(),
position(), seek(), and peek() let you see how big a file
Filenames have to be in 8.3 format. The SD library uses is, where you’re at in the file, and to move around in the
the old DOS file-naming convention that all filenames are a file. mkdir() and rmdir() let you make and remove whole
maximum of eight-characters long with a three-character directories. Use these methods, especially those that let
exension. All file names are case-insensitive and spaces
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 377
you look without changing, like exists(), size(), and peek(), even have one built in. Most microSD cards come with an
which keep track of what you’re doing when you write adapter to allow you to fit them into a regular SD card slot.
more complex file-handling sketches. Some cards even come with their own readers.
Indicate when you’re accessing the card, and when Once you’ve formatted your card, make a text file called
you can’t. Using LEDs to indicate when the Arduino is index.htm and save it to the card. Then insert it into your
accessing the card and when there’s an error is a handy shield. When the sketch runs, it should print the file out
way to know what’s going on when you can’t see the once at the end of setup(), then proceed to read the
output on a screen. temperature sensor and control the relay as it did before.
When that’s working, you’re ready to write the server. This
For this project, you’ll only read from the card from code can be added to the sketch you’ve already got in
the microcontroller. To write to the card, you’ll need an progress.
SD card reader/writer that can handle MicroSD cards.
Readers are cheap, and they are becoming more and
more ubiqitous. If your computer is a recent model, it may
Server server(80);
88These will be used char inputString[inputLength]; // for input from the browser
to manage the incoming char requestTypeString[typeLength]; // what type of request: GET or POST
HTTP requests. int nextChar = 0; // index counter for requestTypeString
const int fileStringLength = 16; // length of the file requested
char fileString[fileStringLength]; // for input from the browser
long now; // last temperature check time
378 MAKING THINGS TALK
if (client) {
// make an instance of TextFinder to look for stuff from the client:
TextFinder finder(client );
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 379
Put this while() block inside the if // gather what comes after the / into an array,
statement that checks to see whether // it's the filename the client wants:
the client exists. It checks to see requestedFileLength = finder.getString("", " ",
whether the client is connected, and fileString, fileStringLength);
whether it has sent any bytes. If so, it
looks for the GET or POST requests, // now you're done with the GET/POST line, process what you got:
and gets the file requested as well. If it switch (requestType) {
gets a POST, it extracts the thermostat case 1: // GET
variable. Then it calls sendFile() to send // do nothing with GET except send the file, below
the file to the client. break;
case 2: //POST
// skip the rest of the header,
// which ends with newline and carriage return:
finder.find("\n\r");
// if the client sends a value for thermostat, take it:
if (finder.find("thermostat")) {
int newThermostat = finder.getValue('=');
// if it's changed, save it:
if (thermostat != newThermostat) {
thermostat = newThermostat;
// constrain it to a range from 20 to 40 degrees:
thermostat = constrain(thermostat, 20, 40);
// save it to EEPROM:
EEPROM.write(thermostatAddress, thermostat);
}
}
break;
}
// whether it's GET or POST, give them the string they asked for.
// if there's nothing after the /,
// then the client wants the index:
88Wait, this sendFile() if (requestedFileLength < 2) {
call looks different from sendFile(client, "index.htm");
the one on page page 375!
}
The change is coming up.
// otherwise send whatever file they asked for:
else {
sendFile(client, fileString);
}
»
}
380 MAKING THINGS TALK
8 After the while() block, the ther- Continued from previous page.
mostat check block from the
original sketch closes out the loop() // give the client time to receive the data:
method. delay(1);
// close the connection:
Serial.println(F("Closing the connection"));
client.stop();
} // close of the if (client.available() block
} // close of the while (client.connected() block
} // close of the if (client) block
// NOTE: the thermostat check (the body of the loop() method on
// page 374) goes here,
}
8
The sendFile() method needs to // send the file that was requested:
change so you can send to the client void sendFile(Client thisClient, char thisFile[]) {
instead of printing it out. It also needs String outputString = ""; // a String to get each line of the file
to send the HTTP headers that come
before the file. If the file isn’t available, // open the file for reading:
you should tell the client that, too. And File myFile = SD.open(thisFile);
you might as well use the standard if (myFile) {
HTTP error codes to do it. So now // send an OK header:
sendFile() sends an HTTP 200 OK sendHttpHeader(thisClient, 200);
header if it can read the file, and an // read from the file until there's nothing else in it:
HTTP 404 File Not Found header if it while (myFile.available()) {
can’t. Changes are shown in blue. // add the current char to the output string:
char thisChar = myFile.read();
outputString += thisChar;
If you run the code you’ve got so far, you should Next, it’s time to write the actual HTML interface pages.
have a working web server. Whatever text files You need a page that can show the temperature and
you put on the SD card should be accessible via provide a form to enter a new thermostat setting. When
the browser. You’re not set up to serve anything other than the user submits the form, she should get feedback that
HTML text documents (note that the sendHttpHeader() her new setting has been received and stored, and the
method only returns Content-Type: text/html), but you can interface should reset itself. You also need a camera to get
do a lot with that. Try making a few pages that link to each a picture of the room. Finally, it should look good on the
other and put them on the SD card, then navigate through small screen of a tablet or smartphone. All of this can be
them with a browser. Try it on a mobile phone browser, too, done in HTML.
since that’s your original goal here. Resist the temptation
to send the URL to all your friends just yet—there is more
work to do.
»
</head>
382 MAKING THINGS TALK
Network Cameras insecure because anyone who views source on the page
Cameras that connect to the Internet have been available can see the password, so make sure the account has no
for several years now, and the prices on them, predictably, privileges whatsoever to change or view settings!
get cheaper and cheaper. For about $60, you can get a
small camera that has a WiFi module onboard and that Once you think you know the public URL of your camera’s
runs as its own server. The one used for this project, the image, test it in a browser. It’s a good idea to test away
D-Link DCS-930L, was purchased at an office-supply store from your home network. When you’re satisfied it works,
for $70. embed the link in the index.htm page that you wrote previ-
ously, and try it out. You’ll also need to make the change
Setting up these cameras is very straightforward, and is to the image’s URL in the JavaScript in the document’s
explained in the documentation that comes with them. head. Now your server is on the Internet for real!
First, you need to connect to the camera through a wired
Ethernet connection, and open its administrator page in There’s one last stage of this project. You have to replace
a browser (just like you’re building for the air condition- those placeholder variables for the temperature, thermo-
er—hey, how about that!). There, you configure the WiFi stat setting, and air conditioner status. To do that, you
network you want to connect to, save it to the camera’s need to add some more code to your sketch.
memory, and restart the camera. X
Once you’ve made this change and uploaded popular mobile applications are developed by making
it, you’re done. When you go to the Arduino’s a basic browser shell without any user interface, then
address in your browser, you’ll get the tem- developing the user interface in HTML5. When you click
perature, the current thermostat setting, and the status of through the app’s interfaces, you’re just browsing pages
the air conditioner. If you change any of the settings, you’ll on their site. Because so many mobile phone applica-
change the temperature in your home as a result. With tions are mainly network applications, it makes sense to
the change you made to the image tag and the JavaScript use this as your primary approach. By doing so, you avail
in the index.htm document to accommodate your camera, yourself of all the protocols the Web has to offer.
you’ll have an image from home as well. In a browser, your
final application should look like Figure 10-10. The web approach to mobile apps means you get to take
advantage of protocols that don’t run in a browser, but still
The great thing about using the browser as your appli- rely on HTTP. You’ll see this in practice in the next project.
cation interface for mobile applications is that you only X
have to write the app once for all platforms. Many of the
386 MAKING THINGS TALK
Project 30
Luba is a bit of a luddite when it comes to new tech- If you’ve called an automated help service in the last few
nologies, and she’s not really fond of the mobile web years, chances are you were talking to a SIP server. When
interface for the thermostat. “But it’s a phone!”, she you spoke, it tried to recognize your words using speech-
complains. “Couldn’t I just call someone and have to-text software, or it directed you to touch numbers on
them stop by to change the temperature?” It’s a fair your keypad using text-to-speech software. When you
point: if you’ve got a phone, you should be able to entered numbers or words, it translated your input into
make things happen with a phone call. HTTP GET or POST requests to query a remote server or
local database. When it got results, it read those back to
IP-based telephony has taken leaps and bounds in the you using text-to-speech again. If it couldn’t understand
last several years, to the point where the line between what you were saying (perhaps you were screaming
a phone call and a web page is very blurry. Server “Operator! Operator! Give me a human being!” as I often
applications such as Google Voice and Asterisk are do), it rerouted your call to a number where a human
like virtual switchboards—they connect the public would answer.
switched telephone network (PSTN), and the Internet.
These servers use a protocol called Session Initiation For this project, you’re going to use a commercial SIP
Protocol, or SIP, to establish a connection between service from Twilio to make a voice interface to the ther-
two clients and determine what services they are mostat you just built. Twilio provides a variety of Voice
capable of sending and receiving. For example, a SIP over IP (VoIP) services like voicemail, conference calling,
client might be able to handle voice communications, and more. With their commercial accounts, you can buy
text messages, route messages to other clients, and phone numbers to which you attach these services, so
so forth. Sometimes a SIP server sets up the con- your customers can call your service directly. They also
nection between the clients, then gets out of the way have a free trial service. With the free service, you must
and lets them communicate directly. Other times it use the phone number they assign to you, and you have
manages the traffic between them, translating the to use a passcode to access your application once you’ve
protocols of one into something that the other can called in. For readers outside the U.S. and Canada, Twilio
understand. It’s the 21st-century version of the old offers only U.S./Canada-based numbers at the time of this
switchboard operators. When application designers writing. Read on to get the general idea, then find an equiv-
have done their job right, you never need to know alent service that works in your country. Phone number
anything about SIP, because your phone or software exchange is unfortunately one place the PSTN lags con-
just tells you what it can do, and provides you a way siderably behind the Internet, mostly for commercial and
to address other people. The phone does this by pre- political reasons. If you really want to get deep into VoIP
senting you with a dial tone and a keypad. and SIP, check out Asterisk: The Future of Telephony by
Jim Van Meggelen, Jared Smith, and Leif Madsen (O’Reilly).
X
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 387
What’s the Standard? You’ll also need the URL of your Arduino server from
Here’s the bad news about SIP and VoIP applications: the previous project. For example, if your server is
there’s not a standard approach to them yet. They all offer at 63.118.45.189, the address for this project will be
slightly different services, though the basics of making http://63.118.45.189/voice.xml. Log in to your Twilio
calls, sending SMS messages, recording calls, and reading account and go to the dashboard. There, you’ll be given
touchtones are available most everywhere. Each server a sandbox phone number and passcode. The phone
and each commercial provider has a different approach number will connect you to Twilio’s gateway. The gateway
to providing an application programming interface (API) will connect you to an HTTP server whose address you
for its service. The markup you learn here for Twilio won’t provide (give it the one above). Once you’ve done that, it’s
apply when you’re building an application using another time to write an XML file for the server, and to modify the
service like Tropo, Google Voice, or any of the dozens of sketch so it will respond as needed. Figure 10-11 shows the
other providers out there. dashboard panel.
There are four questions that can help you choose which
tool to use for any project: A Brief Introduction to XML
XML, or eXtensible Markup Language, is a general markup
• Does it offer the features I need? language used by many web and database services.
• Is it available in my area? XML allows you to describe nearly anything in machine-
• Is it simple to use? readable form. XML is made up of tags that begin and
• Will it work with my existing tools? end with < and >. Tags describe elements, which can be
any concept you want to label. Elements can have subele-
For this application, I chose Twilio because its markup ments; for example, a <body> might have <paragraph>
language, TwiML, is very simple. Also, Twilio’s examples subelements, marked up like so:
make it clear how to separate the markup language from
another server-based language, like PHP or Ruby. Every- <body>
thing happens through GET or POST. Twilio has excellent <p>This is the content of the paragraph</p>
PHP examples, but you don’t need them to get started. </body>
Its debugger is useful, and its technical support is good
as well. It lacks features that other services have—like the
ability to get the audio level while recording, or speech-
to-text conversion—but, on the whole, the benefits of its
simplicity outweigh any of the missing features.
Figure 10-11
The Twilio dashboard. Enter the URL for your
Arduino server in the Voice URL box.
388 MAKING THINGS TALK
The stuff between the tags is the content of an element. Voice elements:
It’s usually the stuff that humans want to read, but that the <Say>
machines don’t care about. <Play>
<Gather>
Every element should have an opening and closing tag, <Record>
though sometimes a tag can close itself, like this: <Sms>
<Dial>
<Pause length="10" /> <Number>
<Conference>
What’s inside a tag other than the tag’s name are its attri- <Hangup>
butes. The length above is an attribute of a Pause, and this <Redirect>
specific pause’s length is 10 seconds. Attributes allow you <Reject>
to describe elements in great detail. <Pause>
If you’re thinking all of this looks like HTML, you’re right. SMS elements:
XML and HTML are related markup languages, but XML’s <Sms>
syntax is much stricter. Because it’s such a general <Redirect>
language, though, it’s possible to write XML-parsing
programs that work from one schema to another. They’re all explained in depth on Twilio’s documentation
pages, but you can probably guess what most of them do.
TwiML
Twilio’s markup schema, TwiML, is a description of the For this project, you’re going to describe a <Response>.
functions Twilio offers written in XML. It describes what Within that, you’ll use <Gather> to collect keypresses
you can do with Twilio. There are elements for handling a from the caller. The <Gather> element is TwiML’s version
voice call, and elements for handling an SMS message. of an HTML form, so it has an action attribute and a
The list of elements is pretty short: method attibute that you’ll use to tell it where and how
to send its results. You’ll also use the <Say> element to
speak to the caller using text-to-speech.
X
8
The Twilio gateway that acts as // send the file that was requested:
a client to your server is a bit more void sendFile(Client thisClient, char thisFile[]) {
picky about what it expects than most String outputString = ""; // a String to get each line of the file
browsers. It works best when you tell
it in advance the length of the content // open the file for reading:
you’re going to send it. That means File myFile = SD.open(thisFile);
you need to make some changes to if (myFile) {
sendFile() and sendHttpHeader(). // get the file size:
First, in sendFile(), you’re going to get int mySize = myFile.size();
the size of the file you’re sending, and // determine whether the file is XML or HTML
identify whether the file you’re sending // based on the extension (but assume it's HTML):
is HTML or XML. Then you’ll send the int fileType = 1; // 1 = html, 2 = xml
file size and type to the sendHttp- if (String(thisFile).endsWith("xml")) {
Header() method. The beginning of the fileType = 2;
sendFile() changes, as follows, are in }
blue.
// send an OK header:
sendHttpHeader(thisClient, 200, mySize, fileType);
// read from the file until there's nothing else in it:
while (myFile.available()) {
8
You also need to change the call else {
to sendHttpHeader() for a 404 error, // if the file didn't open:
which occurs later in sendFile(), as sendHttpHeader(thisClient, 404, 0, 1);
follows. }
When you’ve made these changes and put the is true with $thermostat, which you’re replacing with a
voice.xml file on your SD card, restart the server two-digit number, and $status, which you’re replacing
and call your Twilio sandbox number. Enter the with a two- or three-character string. To calculate the
PIN, and the phone will ring. If you did everything right, content length correctly, you have to account for this.
you’ll hear the text of the document read out to you, and There are two possible solutions.
you’ll be able to enter a new thermostat setting using your
phone keypad. You can keep changing the thermostat The hack solution: Since most browsers don’t care about
setting for as long as you like; when you’re done, hang up. the content length, don’t print it if you’re serving HTML.
Put an if statement around the two lines that print the
content length, like so:
Getting the Content Length Right
The server can theoretically serve both the XML and if (fileType == 1) {
HTML documents now, so you should be able to see the thisClient.print(F("Content-Length: "));
pages in a browser as well. However, your browser may thisClient.println(fileSize);
have problems with the content length. If you paid close }
attention, you may have realized that the size of the file
is not actually the number of bytes you’re sending as
content. The thorough solution: You know that the thermostat
is a two-digit number because you constrained it. That’s
The file size is determined before you replaced the $tem- nine fewer characters than “$thermostat”. You also know
perature, $thermostat, and $status variables with their that the temperature is a five-character string because
actual values. For example, when the temperature is you limited it to two decimal places (and over 100°C is
27.28 degrees Celsius, you’re replacing “$temperature” deadly). That’s seven fewer than “$temperature”. You
with “27.28”—that’s 5 characters instead of 12. The same know that the status string is two or three characters,
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 391
which is five or four fewer than “$status”. So, calculate When you’re changing the contents of a file dynamically
the difference before you send the HTTP header. The before you serve it, you have to make adjustments like this
total is 20 or 21 characters shorter than the original file, all the time. So, it’s good to know a few methods for doing
depending on the relay status, which you can determine it. On a server with plenty of memory, you might simply
by calling checkThermostat(). You can change the put the whole file in an array and get the size of the array.
sendFile() to adjust for this right before it sends the OK One of the valuable things you learn when working on
header, like this: microcontrollers with limited memory is how to do work-
arounds like this.
if (checkThermostat()) {
mySize = mySize - 21; I’ll admit it: I went for the hack solution first.
} X
else {
mySize = mySize - 20;
}
// send an OK header:
sendHttpHeader(thisClient, 200, mySize, fileType);
HTML5 and Other Mobile and send and retrieve data to locations other than the
browser—whether the data is on the user’s hard drive or a
Web Approaches remote server.
There’s currently a lot of excitement among mobile appli-
cation developers around HTML5, the next version of the Previously, applications running within a web browser
HyperText Markup Language standard. HTML5 aims to had very limited access to the hardware of the computer
make HTML able to support a greater amount of interac- on which they were running. Operating system manufac-
tion and control over how web pages look and behave. turers felt that it was unsafe to allow an application that
In fact, what makes HTML5 interesting is not just the you downloaded from the Internet to access your hard
markup language itself, but the possibilities it offers when drive, camera, microphone, or other computer hardware.
combined with JavaScript and CSS3, the Cascading Style Hackers might do evil things! Of course, now that nearly
Sheets standard. every application is downloaded from the Internet, that
thinking seems dated. You could still download a program
So, how do HTML5, JavaScript, and CSS3 work together? that does malicious things—but, by now, most people
Roughly, you could say that HTML gives you nouns, CSS have a sense of what makes an online source more or less
gives you adjectives and adverbs, and JavaScript gives trustworthy, whether that source is delivering a web page
you the verbs to put them into action. HTML describes the or an application that’s native to your operating system.
basic page structure and the elements within it: forms, At the same time, more of the data we need to access
input elements, blocks of text, and so forth. CSS primarily lives online today, whether on a social media site or a web
describes the characteristics of the visual elements: data storage service like Google Docs or Dropbox. There’s
the colors, fonts, spacing, etc. The scripting language no need for a browser to access your hard drive if your
JavaScript allows you to make connections between the files are online.
elements of a page, between pages in a browser, and
between the browser and remote servers. The grammar The blurring of the distinction between browser security
analogy isn’t perfect, but the point is that the three tools and general security is good news if you like to build
give you a wide range of means to present information, physical interfaces. HTML5 and JavaScript include
listen to user input, generate interactive responses, methods to access some of the hardware of your
392 MAKING THINGS TALK
computer or phone. For example, there are methods now iOS). You don’t need to do anything to that code—it’s
that let you determine the device’s orientation by reading just there to act as a shell for your app. You write your
an accelerometer, if you have one built in (and most own HTML5 and JavaScript documents, which form the
smartphones do); reading the compass and GPS receiver, core of your app. Then you compile it all and upload it to
if they’re available; and more. your phone. PhoneGap also offers an online compilation
service: upload your HTML files and it compiles an appli-
The bad news is that not all of these new methods are cation for you to download to your phone.
universally agreed upon among the companies who make
browsers. Not every browser gives you access to all of There are things you don’t get with PhoneGap. For
these features, and not every browser implements them example, you can’t open a connection to your phone’s
the same way. For example, the Safari browser on Apple’s Bluetooth serial port, if it has one, nor can you access the
iPhone and iPad gives you access to the accelerometer as phone’s USB connection. Despite that, it’s a promising
of this writing, but the standard browser on Android does start.
not. So, while it’s easy to access devices external to your
phone through the browser, getting access to the ones on PhoneGap is not the only platform for developing mobile
your phone may take a bit more work. phone apps for multiple operating systems. MoSync
(www.mosync.com) also offers application frameworks
for multiple platforms, but you develop your own appli-
PhoneGap cation in C++, not in HTML. You get access to more of
If you’re interested in getting access to the sensors on the hardware with MoSync, but it definitely requires
your phone, and you’re comfortable working in JavaScript, a greater familiarity with programming than anything
PhoneGap (www.phonegap.com) is a very promising you’ve seen in this book so far. Several other companies
option. PhoneGap is a platform that gives you access to all are offering cross-platform tools like this now, and more
the phone’s hardware sensors through HTML5 and JavaS- will certainly come along. If you’re interested in develop-
cript. Basically, PhoneGap embedded the phone’s built-in ing applications for the phone that use built-in sensors,
browser engine (which implements all of HTML5’s new and you don’t want to write an application native to each
standards), added a bunch of hooks into useful function- different phone operating system, PhoneGap is your best
ality (such as built-in sensors) and released it as a basic option until the browsers catch up.
frame for you to develop in. You download the application X
framework, which is written in your phone’s preferred
programming language (Java on Android, Objective-C on
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 393
Text-Messaging Interfaces
Text messaging is fast becoming the most common use for mobile phones. Many
people regard texts as less intrusive than voice calls in the flow of daily life. With a text
message, you can get information across quickly and with no introduction. In addition,
it’s easy to send email to SMS, and vice versa; they’re not platform-dependent—as
long as you have a mobile phone or email account. For situations where you need an
immediate, unobtrusive notification, or to give a single instruction, they work wonderfully.
AT&T: [email protected]
T-Mobile: [email protected]
Virgin Mobile: [email protected]
Sprint: [email protected]
394 MAKING THINGS TALK
<html>
<head></head>
<body>
<h2>SMS Messenger</h2>
<form name="txter" action="sms.php" method="post">
The mobile phone industry is fast changing, as are its offers an environment familiar to many experienced devel-
smartphone operating systems, and keeping up with it opers. For those less comfortable with code, Google offers
all can be exhausting. Google’s Android OS, Blackberry, a graphic programming environment called App Inventor
Palm’s webOS, Windows Mobile, Symbian, and Apple’s (http://appinventor.googlelabs.com) that allows you to
iOS (for iPad, iPhone, and iPod touch) are currently the create applications by combining graphic objects. For
largest players. Of those, Android, iOS, and Blackberry the rest of this chapter, you’ll learn to make Android apps
are the three largest at the moment, covering most of using a familiar environment: Processing. As of version 1.5,
the market. Nokia’s Symbian was one of the largest, but Processing can compile and install sketches as Android
Nokia is no longer supporting it as its primary operating apps.
system. As of the last quarter of 2010, Android was the
most popular of smartphone operating systems, taking
35% of the world market. Processing for Android
Processing for Android is a very exciting update to Pro-
There’s a lot of interest in programming for iOS because cessing, but as it is very new, it is still under development.
it’s such an attractive environment, but Apple is notori- The examples that follow were developed at the same
ously controlling about iOS development. You have to time as the tools to make them possible—in some cases,
register as a developer, and they’ve limited the available they are the first real tests of the libraries they use. So be
toolkits severely. In addition, you can’t just distribute warned, you’re sailing in uncharted waters now. As the
your app independently—you have to do it through the Processing for Android wiki (http://wiki.processing.org/w/
App Store. That’s fine for commercial developers, but for Android) explains: “Do not use this code while operating
hobbyists and home hackers, it can be quite forbidding. heavy equipment. Do not rely on this code for thesis or
For more on iPhone programming, see Alasdair Allan’s diploma work, as you will not graduate. Do not use this
books, Learning iPhone Programming (O’Reilly) and iOS code if you’re prone to whining about incomplete software
Sensor Programming (O’Reilly). Alasdair has done a great that you download for free.” The libraries used here are
deal to make iPhone programming accessible. likely to change after the publication of this book, and they
will hopefully become more stable and easier to use. So
Android, on the other hand, is somewhat more accessible make sure to check the online documentation of anything
to programmers. Applications can be installed on Android mentioned here for updates.
phones using the Android Market, or they can be installed
over USB. Based on Linux and programmed in Java, it
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 397
Setting Up Processing for Beneath “Third party Add-ons”, expand the Google Inc.
entry, and select “Google APIs by Google Inc., Android API
Android 7”.
Processing for Android has a slightly different workflow
than standard Processing, so you’ll need to install some You can install more recent packages if you want,
new components and get used to some new tools. The depending on what version of Android your device is
first thing you’ll need is Processing version 1.5.1 or later, running, and what features you want to access (but you
which can be downloaded from the Processing site (www. need at least these for Processing for Android to work).
processing.org/download). You’ll also need the Android
Software Developers’ Kit (SDK), available at http:// To check your device’s operating system version, go to the
developer.android.com/sdk. Download and install both. home sceeen, and from the menu, choose Settings. Scroll
Then open Processing. You’ll see a new button in the main to the bottom and choose “About phone”. In that menu,
toolbar labeled Standard, as shown in Figure 10-12. Click you’ll see a listing of the Android version. Figure 10-13
it and choose Android. You’ll get a dialog box asking you if shows the menu. If you have a later version than 2.1, you
the Android SDK is installed. Click Yes. Another dialog box might want to install the latest that your phone can run.
will pop up asking you where it is. Navigate to the Android For example, I installed the SDK Platform Android 2.3.3,
ADK folder that you just installed. The Processing editor API 10, revision 1 to work with a Nexus S phone that was
color scheme will turn green, and you’ll be in Android running version 2.3.4, and the Google APIs Android API 10,
mode. revision 2, as well.
FPO replace
Figure 10-12
Processing’s Mode button set to Standard mode.
Figure 10-13
The “About phone” menu, showing your Android version.
398 MAKING THINGS TALK
Many libraries for Standard mode do not work in Android You need to enable different permissions to get at different
mode. This will likely change as library developers adapt functions of the device. In the Android menu, you’ll see a
the useful ones to Android mode, but for the moment, it’s list of Sketch Permissions. You can set most of them from
best not to assume. this menu. This menu writes to the AndroidManifest.xml file
in the sketch directory.
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 399
Whenever possible, use the permissions menu rather than For more tips on the differences, see http://wiki.process-
editing the manifest. For everything you need in this book, ing.org/w/Android for the latest information.
you can use the permissions menu and be safe. It’s easy
to mess things up by editing it wrong—remember, XML is Now here’s a quick sketch to get you started. It reads
not forgiving. the mouse position and saves data when you pause and
resume. You’ll need to set the Sketch Permissions to
Since your sketch restarts every time you change ori- enable WRITE_EXTERNAL_STORAGE.
entation, you might want to use saveStrings() and load- X
Strings() to save and load variables that need to persist.
void setup() {
// create a font for the screen:
String[]fontList = PFont.list();
PFont androidFont = createFont(fontList[0], 24, true);
textFont(androidFont, 24);
}
void draw() {
// color theme: Sandy stone beach ocean diver by ps
// http://kuler.adobe.com:
background(#002F2F);
fill(#EFECCA);
// show the mouse X and Y and finger pressure:
text("mouseX:" + mouseX, 10, 50);
text("mouseY:" + mouseY, 10, 80);
text("motionPressure:" + motionPressure, 10, 170);
// move the ball if the person is pressing:
if (mousePressed) {
ballX = mouseX;
ballY = mouseY;
}
// draw a nice blue ball where you touch:
fill(#046380);
ellipse(ballX, ballY, 50, 50);
}
400 MAKING THINGS TALK
void resume() {
//load the data file:
String[] data = loadStrings(datafile);
// if there's a file there:
if (data != null) {
// and there are two strings, get them for X and Y:
if (data.length > 1) {
ballX = float(data[0]);
ballY = float(data[1]);
}
}
}
Figure 10-15
The Processing for Android sketch that you just wrote.
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 401
Project 31
A growing number of personal data enthusiasts are Feel free to change the sensor for whatever you want to
gathering personal biometric data for many different track yourself.
purposes, from visualizing their activity patterns in
order to improve exercise habits, to tracking sleep Figure 10-17 shows the system for this project. A micro-
patterns in order to find solutions to insomnia. Quan- controller reads the analog voltage from the sensor and
tified Self meetups (http://quantifiedself.com) are sends it serially to a Bluetooth Mate. The data is then
popping up around the world for people to share tips transmitted over Bluetooth to a mobile phone using the
and tricks on how to do this, and devices like the Serial Port Profile, or SPP, that you used in other Bluetooth
FitBit (www.fitbit.com) and the Zeo (www.myzeo. projects in this book. The phone then makes an HTTP GET
com) have come on the market to make biometric request to a PHP script on a web server. The script saves
tracking easier. the incoming data to a file. What you do with the data from
there is up to you.
This project is based on the work of ITP alumnus
Mustafa Bağdatlı, shown in Figure 10-15. Mustafa
wanted to track his Galvanic skin response (GSR) and
heart rate against his calendar, so he could see when
his mood—as reflected in his heart rate and GSR—
were affected by the events of the day. His project,
Poker Face, tracked the two biometric characteristics
on a LilyPad Arduino, transmitted them via Bluetooth
to a mobile phone, and logged the result on the Web.
You can find more on Poker Face at http://musta-
fabagdatli.com In this project, you’ll build the same,
but without the heart rate sensor to keep it simple.
Figure 10-16
Mustafa Bağdatlı wearing Poker Face, a biometric
datalogger linked to a mobile phone. Photo
courtesy of Mustafa Bağdatlı.
402 MAKING THINGS TALK
The Circuit
The circuit for this project is quite simple. To measure
Data
Galvanic skin response, all you need is a high-value file
resistor and your skin. As a test, take a multimeter and HTTP
Mobile
measure the resistance across your wrist. You’ll find that Internet over
Phone
GPRS
the resistance is high, probably in the megohm range if PHP script
your skin is cool and dry. Work up a sweat and measure
it again. You’ll see that the resistance has gone down. Web Server
When you exercise, or when you’re faced with stressful
or arousing situations (good or bad), you perspire more,
changing the conductance of your skin. That’s what this Bluetooth
project will measure.
The Construction
For this project, you’ll use iron-on conductive fabric
attached inside the pocket of a hoodie as your sensor
contacts. When you reach in your pocket, you can touch
the fabric contacts with the palm of your hand, and take
a reading on your phone with the other hand. Or, you can
let the mobile app run continually to take a reading every
two minutes.
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 403
RN-42
Connect
Stat
a2/
GND
VCC
CTS
RTS
16
RX
TX
a1/
- 15
a0/
+ 14
B G
LiPo 3.7V
3 11
On
Off
5 10
6 9
Conductive fabric
contact points
Figure 10-19
The mobile datalogger circuit. The contacts for the
sensor are conductive fabric.
AREF
Reset GND
Figure 10-20
+3.3V D13
+5V D12
The mobile datalogger circuit schematic.
Gnd D11/PWM
Pin 11 is
To Battery Ground Gnd D10/PWM acting as voltage
for sensor
To Battery +3.7V Vin D9/PWM
D8
Arduino
Module
D7
D6/PWM
Analog0 D5/PWM
A1 D4
Pin A1 is 270KΩ A2 D3/PWM
acting as ground
for sensor A3 D2
A4 Digital1/TX
A5 Digital0/RX
Conductive thread connects the fabric contacts on one Cut a hole in one side of the bottom band just below the
side of the garment to a three-wire conductive ribbon pocket to insert the microcontroller with the Bluetooth
on the other side of the garment. The microcontroller Mate and battery attached. You’ll need to be able to get
and battery will be sewn into the bottom band of the the battery in and out for charging, so finish the edges
hoodie just below the pocket, and the conductive ribbon of the hole so they won’t fray with repeated use. Iron-on
will connect them, sewn onto the inside lining of the fabric, or embroidery thread will do the job. Then add
hoodie. Figure 10-21 shows the layout on the inside of the Velcro to the inside edges to provide a closure.
garment.
Cut another small slit in the band about six inches (10cm)
Iron the conductive fabric contacts into the pocket. Space away from the large hole so you can insert the ribbon
them so they cover about the width of the heel of your through the bottom band. Figure 10-21 shows the two cuts.
palm, and contact it comfortably when you put your hand
in the pocket. Figure 10-22 shows you the inside of the Make sure the LilyPad Arduino Simple is programmed and
pocket. the circuit is fully assembled before you sew it into the
garment. The sketch is below.
Split the ends of the three-wire conductive ribbon about
an inch on either end with a pair of scissors. You need Position the ends of the ribbon on the inner lining of
enough distance between the wires to span the space the garment opposite the fabric contacts in the pocket.
between the conductive fabric contacts on one end, and Sew the conductive ribbon to the contacts through the
between two contacts of the LilyPad Arduino Simple on material with conductive thread. Use tight stitches for
the other. Tin the tips of the outside wire ends to keep a good connection. Use a meter to check connectivity
them from fraying. You’re not using the middle wire, so between the contacts and the opposite end of the ribbon
cut it out, down to the end of each split. You can also when you’ve finished your sewing. This way, you know the
embroider the two outside conductors with yarn that signal makes it from the contacts through the garment to
matches the hoodie to keep them from fraying, if you the end of the ribbon that will attach to the LilyPad.
wish. Solder one pair of the conductive ribbon’s leads to
pins 11 and A0 of the LilyPad Arduino.
Figure 10-21. The layout of the hoodie components on the inner lining: 1.
The LilyPad Arduino and the battery are actually inside the bottom band of the
garment, inserted through 2. the large cut on the right. The conductive ribbon
comes out of the bottom band through 3. the small cut, and goes to 4. the Figure 10-22. The conductive fabric
pocket contacts at the top (opposite side of the garment). contacts inside the hoodie pocket.
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 405
Tack the ribbon down to the garment’s inner lining about The Code
every inch, so it’s secure and won’t fold over itself when There are three pieces of code for this project: the PHP
worn. Don’t sew the battery in—you’ll need to remove it script, the Arduino sketch, and the Processing sketch. The
for recharging. You shouldn’t need to sew the other com- first two are relatively simple, and having them done and
ponents in either, but Velcro on the back of the LilyPad tested makes the Processing sketch easier to understand.
Arduino and in the lining of the band will secure it nicely.
The Arduino sketch listens for serial input and when a byte
At this point, the circuit should be fully functional. Test it arrives, it takes a reading, maps it to a voltage range, and
with a wired connection before going Bluetooth. To test it, sends it out.
attach a USB-to-Serial connector to the LilyPad Arduino
(which will take some creative cabling) and open the serial The PHP script accepts a request string and looks for
connection in the Serial Monitor or another serial terminal one variable, called data. It appends everything from that
program at 115200bps. Put your hand on the contacts in variable into an existing text file called datalog.txt. It returns
the pocket. Then send any byte, and you should get back a basic HTML page with the data that the client sent.
a sensor value. To see a change in the value, either work
up a sweat or lick your hand and put it on the contacts The Processing sketch checks if it’s connected to the
again. When you know it works, remove the USB-to-Serial Arduino’s Bluetooth Mate. If it’s connected, it asks for a
line, and connect the Bluetooth Mate and the battery and reading once every 10 seconds. Once every two minutes, it
turn it on. Now connect from the Serial Monitor or a serial sends the accumulated readings to the PHP script. There
terminal program via the Mate’s serial port. This will work are also two buttons: one to get a reading and another to
like it did in Chapter 2 when you added the Bluetooth Mate send the reading to the server.
to Monski Pong. X
<html>
<body>
Here's what you sent:
<?php echo $newData; ?>
</body>
</html>
Figure 10-23
What the logger script returns in a browser.
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 407
chmod o+rw datalog.txt If you do, you know everything is working and you’re ready
to write the Processing sketch.
If you’re creating the file using a GUI-based program, get X
info on the file and set the permissions that way. Figure
10-24 shows the Get Info window from BBEdit, which is
similar to many other programs. Once you’ve made this
file, call it from the browser with a query string like this:
Figure 10-24
Setting the read-write permissions for a file
from a GUI-based program.
Bluetooth Serial Library In Android mode in Processing version 1.5.1, libraries are
In order to use the Processing for Android sketch, you’ll not always imported into your sketch automatically. This
need the Bluetooth Serial (BtSerial) library. This library will be fixed in future versions so that it works like the
allows you to make serial connections over Bluetooth Standard mode. If when you try to run your sketch you get
using similar commands to those you used with the serial an error that says package cc.arduino.btserial does not
library in Processing’s Standard mode. You can download exist, make a subdirectory, code, in the sketch’s directory
it from https://github.com/arduino/BtSerial. Click the and copy the file btserial.jar from the library subdirectory of
Downloads link and pick the latest download package the btserial directory that you just installed into code. Then
(0.1.6 as of this writing). Make sure to download the try running your sketch again.
download package not the source. Unzip the file. You’ll
get a directory called btserial-0.1.6. Inside it is a directory This is not ideal, but it should be addressed by the time
called btserial. Place that in the libraries folder of your this book is in publication—the Processing team is very
Processing sketch directory, as you’ve done with other good with bug fixes.
libraries. X
408 MAKING THINGS TALK
»
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 409
8 Note that the button and text Continued from opposite page.
positions are all relative to the
screenWidth and screenHeight // try to connect to Bluetooth:
variables. This is so that they stay in connectionState = connect();
the same relation to each other and
the screen if the device is rotated. readButton = new Button(screenWidth/2 - 100, 2*screenHeight/3,
200, 60, buttonColor, buttonHighlightColor, "Get Reading");
sendButton = new Button(screenWidth/2 - 100, 2*screenHeight/3 + 80,
200, 60, buttonColor, buttonHighlightColor, "Send Reading");
}
8
The draw() method starts by void draw() {
drawing the text strings and buttons. // display data onscreen:
Then it checks to see whether the background(bgColor);
sensor reading interval has passed, or fill(textColor);
whether the updateNow variable has textAlign(LEFT);
been set (when you click the Read Now text(connectionState, 10, screenHeight/4);
button, this variable is set to true). text(getTime(), 10, screenHeight/4 + 60);
If either of these is true, the sketch text("latest reading (volts): " + thisReading, 10, screenHeight/4 + 90);
takes a reading via Bluetooth using text("Server updated at:\n" + lastSendTime, 10, screenHeight/4 + 120);
the getData() method, and adds it to a
string of readings taken since the last // draw the buttons:
time it updated the server. readButton.display();
sendButton.display();
Next, it checks whether the send
interval or sendNow has been set by a if (sendNow) {
click of the Send Now button. If either textAlign(LEFT);
of these is true, it sends the current text("sending to server, please wait...", 10, screenHeight/4 - 60);
string of readings to the server using }
the sendData() method.
// if the update interval has passed,
// or updateNow is true, update automatically:
if (abs(second() - lastRead) >= readInterval || updateNow) {
thisReading = getData();
»
// get the time two ways:
410 MAKING THINGS TALK
8 Last, the draw() method reads the Continued from previous page.
buttons, then sets their previous
states once it’s read them. This sketch lastSendTime = getTime(); // a String to print on the screen
uses a modified version of the Button lastSend = minute(); // an int for further comparison
class from the Processing RFID writer }
sketch in Chapter 9. Because the
cursor on a touchscreen (namely, // if the read button changed from not pressed to pressed,
your finger) can disappear, there’s // set updateNow, to force an update next time through the
no equivalent to the mousePressed // loop. Do the same for the send button and sendNow, right below:
and mouseReleased events, so you if (readButton.isPressed() && !readButton.getLastState()) {
have to make one up. You’re doing updateNow = true;
that in this case by having a method }
in the Button class called isPressed(), //save the state of the button for next check:
a variable called pressedLastTime, readButton.setLastState(readButton.isPressed());
and two methods that let you get and
set this variable. With these, you can if (sendButton.isPressed() && !sendButton.getLastState()) {
check the current state of the button sendNow = true;
(isPressed()), save it when you’re done }
(setLastState()), and get the state last //save the state of the button for next check:
time you checked it (getLastState()). sendButton.setLastState(sendButton.isPressed());
}
»
and pair with your Bluetooth Mate. If }
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 411
8 you don’t, the app can’t see the Continued from opposite page.
Bluetooth Mate. If your Bluetooth }
Mate isn’t the first item in the list of else {
devices, be sure to change the call to: result = "Couldn't get any paired devices";
}
bt.connect( pairedDevices[0] ); }
return result;
to match the number of your Bluetooth }
Mate in the list.
8
URL strings need to be formatted String formatData(String thisString) {
cleanly (no spaces, no newlines or // convert newlines, carriage returns, and
carriage returns, and so forth), so // spaces to HTML-safe equivalent:
sendData() calls formatData(), which String result = thisString.replaceAll(" ", "%20");
converts spaces, newlines, and returns result = result.replaceAll("\n", "%0A");
into their HTTP-safe equivalents. result = result.replaceAll("\r", "%0D");
return result;
}
8 The final method in the main // get the date and time as a String:
sketch is getTime(), which just String getTime() {
returns a formatted date/time string. Date currentDate = new Date();
return currentDate.toString();
}
»
h = thisH;
MOBILE PHONE NETWORKS AND THE PHYSICAL WORLD 413
The display() method combines the // draw the button and its text:
functions of update() and display() void display() {
from Chapter 9’s RFID Writer example, // if pressed, change the color:
both changing the color as needed and if (isPressed()) {
drawing the actual button. currentcolor = highlightcolor;
}
else {
currentcolor = basecolor;
}
fill(currentcolor);
rect(x, y, w, h);
When you run this sketch on an Android device, like they do on your computer. However, Google decided
it will try to connect. When it succeeds in doing that you might want to develop USB accessories, so they
so, it will check for new readings every 10 recently announced the Google Accessory Development
seconds. It will then attempt to send those to the server Kit, an open hardware platform for developing USB acces-
every two minutes. It doesn’t check that it got a valid sories for Android. The Accessory Development Kit is
response, however; that is left as an exercise for you. based on an Arduino Mega 2650 with a USB Host shield
(originally designed by Oleg Mazurov of www.circuitsath-
Armed with this much, there’s a lot you can do with Pro- ome.com) built into it. Circuits@Home sells a few good
cessing for Android. You’ve got the ability to contact the variants on the USB Host shield: for the standard Arduino
Internet and to contact local devices wirelessly. You can shield form and for the Mini Pro. The Arduino Store carries
also contact the built-in sensors, of course. The phone is the Arduino Mega ADK, and a Processing for Android
now your hub to connect a whole lot of things. library is in development. Several others are in the works
from different companies, so by the time you read this,
you’ll have lots of options.
What About USB? X
Android devices are normally USB end devices, not USB
hosts. So, you can’t plug an end device like a mouse, a
keyboard, or an Arduino into them and have them work
Conclusion
The connection between the Internet and mobile networks widens your options by
offering a ubiquitous connection and a variety of communication methods. Taking
advantage of it requires some creative thinking about how to hop across different inter-
faces, systems, and protocols.
These days, mobile phone networks cover almost the for the things that seem simpler and stabler—like SMS
entire planet, more than any other form of network con- and HTTP—and be prepared to shift your approach when
nection. The technology of mobile networks changes the tools change. In Chapter 11, you’ll review some of the
quickly, and many of the tools disappear almost as fast protocols you’ve seen throughout the book in order to get
as they appeared. If you’re making projects using mobile a wide view of what’s possible.
network technologies, it’s best to take a broad view. Look X
SIMbaLink, by Meredith Hasson, Ariel Nevarez, and Nahana Schelling. The SIMbaLink team developed a device that remotely
monitors the health of a solar home system and reports it back to the SIMbaLink client website via a GPRS modem. Working in
conjunction with a solar company in Ethiopia, SIMbaLink remotely monitored solar home systems outside Awassa, Ethiopia. The
systems consisted of a 10W solar panel, a battery, and four 1-watt LED lamps. This simple setup brings light to an otherwise dark
and unpowered rural home. Photos courtesy of Meredith Hasson.
Chapter 11
MAKE: PROJECTS
Protocols Revisited
One of the most valuable skills you can develop is the ability to create
graceful transitions between seemingly incompatible systems. An
understanding of different protocols is central to that skill. You've used
a number of communications protocols in this book, but by the time
you read this, the protocols you learned may have changed or become
obsolete. However, if you understand how to learn new ones, you'll do
fine. This final chapter is a view from the high ground, looking over the
landscape of protocols you've seen in this book to consider their simi-
larities and differences, how they all fit together, and how to go about
learning new ones in the future.
418 MAKING THINGS TALK
Figure 11-1. New parts for this chapter: Spark Fun Musical Instrument shield.
Protocols Revisited 419
For example, if you're dealing with a protocol that uses Know Your Options at the Physical
addresses, you can be sure that it's designed for com-
munication between more than two things. If the address
Level
is broken into several pieces, like IP addresses, you can When you start to work with a new electronic device,
assume it's probably used on a multitiered network. get familiar with what protocols it speaks. By now you're
Figure 11-2
The Arduino's communica-
tions options. Asynchronous
SS can be any free
serial ports are referred to as USB-to- I/O pin
Universal Asynchronous Receiver- UART SPI UART
Microcontroller’s Tx is
Transmitters (UARTs) in technical
controller
MISO
MOSI
USB-to-UART controller’s Rx
SCK
SS
MADE
I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
DIGITAL (PWM ~)
SoftwareSerial
can be any two free pins
-
L
USB TX
+ UNO ON
RX ARDUINO
RESET-EN
RESET ICSP
W W W.ARDU I NO. CC
Microcontroller
POWER ANALOG IN
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
SDA
SCL
I2C
420 MAKING THINGS TALK
familiar with the various protocols that the Arduino and I2C. The serial port was useful for communicating
speaks. Figure 11-2 gives you an overview of them. directly with your personal computer; the I2C option was
useful when working with the microcontroller, because it
This figure tells you something about the physical layer left the microcontroller's serial port open for programming
(which pins are used for which modes of communication) and debugging.
and the data layer (which data protocols the device can
speak). You know by now that if you're using a particular When you're planning a project, consider which of your
set of pins for its communications functions, you can't use devices' ports are used for configuring, programming, and
it for other functions. debugging, and try to leave them free when possible. On
the other hand, if the programming interface offers the
Most of the single-purpose devices you used in the book fastest and most reliable means of communication, it may
spoke only one protocol, but that's not always the case. be worthwhile to deal with having to use it for both pro-
For example, the ultrasonic ranger you used in Chapter 8 gramming and its final application.
offers three different interfaces. It has an analog voltage
output (0-5V, the one you used); an asynchronous RS-232
serial port (Tx and Rx) that sends data at 9600 bits per Picking a Serial Protocol
second; and a pulse-width output (PW), which outputs a When planning a project, picking a serial protocol may
pulse that goes from low to high to low again, changing the seem confusing: synchronous or asynchronous? TTL serial
width of the pulse with the distance of the detected object. or RS-232? I2C or SPI? USB? Most of the time, the choices
All of this is described in the ranger's datasheet, which are made for you because there's some component that
you can find online at www.maxbotix.com. These multiple you have to use—and it only speaks one protocol. But
protocols are useful when you're interfacing the sensor to when you have a choice, here are a few things to consider.
a microcontroller with no analog inputs; when you want
to talk directly to a computer that has an RS-232 serial What protocols are common to all the devices in your
port; or when you're not using a computer at all, and want system? If all of your devices speak the same protocol, it's
to control a simple circuit with a changing pulse width or probably the obvious choice.
voltage.
Do your devices need to be able to decide indepen-
The SonMicro RFID reader you used in Chapter 9 also dently when they'll send information? If so, then any
offered two different communications options: TTL serial system that combines them in a master-slave relationship,
like any of the synchronous serial protocols, won't work.
This table shows a summary, and lists the characteristics, of a few serial protocols mentioned in the book.
Synchronous Serial Protocols Asynchronous Serial Protocols Asynchronous Serial Bus Protocols
• Master-slave relationship between • No common clock, but agreement • No common clock, but agreement
devices on data rate on data rate
• Several devices share the same • Typically used for one-to-one • Often used for longer distances or
data lines communication, not networks networks
• Needs a clock line from the master • Typically differential signaling
to slaves • 3 to 4 wires: Data+, Data-, Ground,
• Distance: 1m or less Voltage (optional)
• Various voltage ranges, commonly
5V or 3.3V
Plan the Physical System and To plan a project like that, you can (and should) diagram
the flow of information between all the elements, as you
Information Flow Early saw in Figures 10-3 and 10-4, so you know what each one
When you know your physical communications protocol needs from the others. Consider what pins of your micro-
options, you can plan how things communicate before you controller are available for the various functions you need.
begin to program or configure anything. Doing so will save Decide where images and web pages are best served from,
you a lot of time. and what links and permissions are required to make it all
happen. Consider which way data flows, and who needs to
Consider the CatCam web server in Chapter 10. It involved know whose address. Decide where you'll place the server
several devices: and the camera physically, and how you will house them.
That way, you can reduce your actual production workload,
• Microcontroller and concentrate on building only what you need in code, in
• Ethernet controller circuits, and in materials.
• SD card
• Temperature sensor
• Relay control
• IP-based camera
422 MAKING THINGS TALK
Text or Binary?
One of the most confusing aspects of data communications is understanding the differ-
ence between a binary protocol and a text-encoded protocol. As you learned in Chapter
2, there is a common scheme for translating the data you send into alphanumeric char-
acters. ASCII—and its more modern cousin, Unicode—allow you to convert any stream
of text into binary information that a computer can read, and vice versa. Understanding
the difference between a protocol that is text-based and one that's not, and why you'd
make that choice, is essential to understanding how electronic things communicate.
Character 1 - 2 - 3 , g o !
Binary 00110001 00101101 00110010 00101101 00110011 00101100 01000000 01100111 01101111 01000001
What about when the messages you have to send are not text (for example, email or hypertext), encoding it as
text-based? Imagine you're sending a string of RGB pixel ASCII/Unicode makes sense. When the number of bytes
values, each ranging from 0 to 255 like this: you'd send is minimal, as with most of the sensor strings
you've sent in this book, encoding it as ASCII/Unicode
102,198,255,127,127,212,255,155,127, can help with debugging, because most serial or network
terminal programs interpret all bytes that they receive as
You know that each reading is eight bits, so in their most text, as you've seen. So:
basic form, they take up three bytes per pixel. But if you're
sending them in text form it's one byte per character, so • If there's a lot of data and it's all numeric, send as raw
the string above would be 36 bytes to send nine values. If binary.
you hadn't encoded it in text form, but just sent each value • If there's text, send as Unicode/ASCII.
as a byte, you'd have only sent nine bytes. When you start • If it's a short data string, send as whichever makes you
to send millions of pixels, that's a big difference! In cases happy.
like this, where all the data you want to send is purely
numeric (you don't need any text to describe the pixels
because you know the first byte is always red, the second
green, the third blue, and so on), sending data without
encoding it as text makes sense. When you need to send
Protocols Revisited 423
These protocols are usually written out in hexadecimal // to make a bit equal to 0:
notation, binary notation, or both. You've seen hexa- bitClear(someByte, bitNumber);
decimal or base-16 notation already in this book. Just as
hexadecimal numbers begin with 0x, binary numbers in Bit Shifting
Arduino—and by extension in C—begin with 0b, like so Sometimes it's easier to manipulate several bits at once.
0b10101010. The shift left and shift right operators in Arduino, C, and
Java allow you to just that. The shift left operator (<<)
Which digit matters most in the number below? moves bits to the left in a byte, and the shift right operator
(>>) moves them to the right:
$2,508
0b00001111 << 2; // gives 0b00111100
The 2, because it represents the largest amount, two 0b10000000 >> 7; // gives 0b0000001
thousands, or two groups of 103. It is the most significant
digit. That number was in decimal, or base-10 notation. Bit shifting is useful when you need a particular value to be
The same principle applies when you're writing in binary, in a specific part of a byte, as you'll see shortly.
or base-2. Which is the most significant bit:
Bit Masking
0b10010110 The logical operators AND, OR, and XOR allow you to
combine bits in some interesting ways.
The leftmost 1 is most significant because it represents 1
7
group of 128, or 2 . Usually when you see bits written out, AND (&): if the two bits are equal, the result is 1.
though, you care less about their decimal numeric values Otherwise, it's 0:
than their position in the byte. For example, in the project
that follows, you're going to make music using MIDI, the 1 & 1 = 1
Musical Instrument Digital Interface protocol. MIDI is a 0 & 0 = 1
binary protocol in which all bytes with a 1 in the most sig- 1 & 0 = 0
nificant bit are commands (verbs), and all bytes with a 0 in 0 & 1 = 0
the most significant bit are data bytes (nouns, adjectives,
or adverbs). A MIDI interpreter could look at the most sig- OR (|): if either bit is 1, the result is 1. Otherwise, it's 0:
nificant bit (which happens to be the first to arrive serially)
and know whether it's getting a command or not. 1 | 1 = 1
0 | 0 = 0
1 | 0 = 1
0 | 1 = 1
424 MAKING THINGS TALK
XOR (^): if the bits are not equal, the result is 1. Otherwise, Hex: What Is It Good For?
it's 0: Since you can manipulate binary protocols bit by bit,
you're probably wondering what hexadecimal notation
1 ^ 1 = 0 is good for. Hex is useful when you're working in groups
0 ^ 0 = 0 of 16, of course. For example, MIDI is grouped into banks
1 ^ 0 = 1 of instruments, with 128 instruments per bank, and each
0 ^ 1 = 1 instrument can play on up to 16 channels. So, those
command bytes you were manipulating earlier could also
Using the logical, or bitwise, operators, you can isolate one be manipulated in hex. For example. 0x9n is a Note On
bit of a byte, like so: command, where n is the channel number, from 0 to A in
hex. 0x9A means note on, channel A (or 10 in decimal).
// Check if bit 7 of someByte is 1: Similarly, 0x8A means note off, channel A. Once you
if (someByte & 0b10000000) {} know that MIDI is organized in groups of 16, it makes a
lot of sense to read and manipulate it in hexadecimal. In
In MIDI command bytes, for example, the command is the fact, many binary protocols can be grouped similarly, so
leftmost four bits, and the MIDI channel is the rightmost knowing how to manipulate them in binary or hexadecimal
four bits. So, you could isolate the MIDI channel by using is handy.
the AND operator:
The next project puts these principles in action to control a
channel = commandByte & 0b00001111; MIDI synthesizer.
X
Or, you could use bit shifting to get the command and lose
the channel:
MIDI
The Musical Instrument Digital Interface (MIDI) protocol enables real-time communica-
tion between digital musical instruments. It’s the granddaddy of digital
synthesizer protocols.
Most music synthesizers, sequencers, samplers, Microcontrollers are more frequently used as MIDI control-
keyboards, and workstations on the market today speak lers than as MIDI input devices. There are so many good
MIDI. If you plan to make music using hardware, synthesizers and samplers on the market that just need
you’re going to run across it. MIDI is a comprehensive a controller to make music, and controllers are fun and
specification covering serial communication, hardware, easy to build. For the project that follows, you'll build a very
and even the arrangement of banks of sounds in a syn- basic controller and use Spark Fun's Musical Instrument
thesizer's memory. Because it's so comprehensive, it's shield as your MIDI input device, which is a general MIDI
enabled composers and musicians to work across a wide synthesizer on a shield. The same code will work if you
range of MIDI synthesizers, samplers, and controllers for want to connect the microcontroller to any general MIDI
decades. The full protocol is detailed on the MIDI Manufac- synth, because the general MIDI specification covers not
turers' Association page at www.midi.org. only the messages, but how synthesizers organize their
banks of sounds.
MIDI is a music description protocol. MIDI messages don't
actually play notes—they describe what notes to play to a MIDI messages are divided into three or more bytes. The
synthesizer. In that sense, MIDI is to music as HTML is to first byte, a command byte, is always 128 (0x80) or greater
web pages. MIDI relies on a synthesizer to render music, in value. Its value depends on the command. The bytes
just as HTML relies on a browser to render your page. that follow it are called status bytes. All status bytes have
values of 127 (0x7F) or less.
MIDI devices are loosely grouped into controllers, or things
that generate MIDI messages, and playback devices, which There are a number of different MIDI commands. The most
receive messages and do something with them. Keyboards basic, note on and note off messages, control the playing
and other input devices fall into the first category. Syn- of notes on 16 different channels of a synthesizer. Each
thesizers, samplers, and many other devices fall into the note on or note off command contains two status bytes,
latter. specifying the pitch in a range from 0–127 (a seven-bit
range) and the velocity (how hard the note should be
The MIDI serial protocol runs at 31,250 bps. There’s a struck), which is also seven bits. Pitch value 0x45 is
standard MIDI connector, a DIN5, that you’ll find on all defined as A above middle C (A-440) by the general MIDI
MIDI gear. All the connectors on the gear are female plugs, specification. This specification also covers the instru-
and the cables all have male connectors on both ends. All ments that you’re likely to find on each channel. For a full
MIDI inputs to a device are supposed to be opto-isolated, listing of the General MIDI instrument specification, see
so there is no direct electrical connection from one device www.midi.org/techspecs/gm1sound.php.
to the next. An opto-isolator is a component containing
an LED and a phototransistor. The input turns on the LED, For more information on MIDI, see Paul D. Lehrman and
and the LED triggers the phototransistor, which turns on Tim Tully’s book MIDI for the Professional (Amsco).
the output. Figure 11-4 shows how to build a MIDI input
and output circuit if you plan to build your own. This circuit
would allow you to connect your microcontroller to any
MIDI synthesizer or controller. There are several MIDI
shields on the market if you don't want to build your own.
426 MAKING THINGS TALK
MIDI in
AREF (facing solder lugs
of socket)
+5V GND
2
Gnd D13 5 4
Figure 11-4
MIDI input and output from a micro-
controller. When you have to build
your own MIDI input or output, this is
how you do it.
MADE
I N I TA LY
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
DIGITAL (PWM ~)
-
L
1 5 10 15 20 25 30
TX
+ UNO ON
A
B
RX ARDUINO C
D
E
RESET-EN
IC
RESET ICSP
W W W.ARDUI NO.CC
F
G
H
I
J
POWER ANALOG IN
1 5 10 15 20 25 30
RESET
3.3V
A0
A1
A2
A3
A4
A5
GND
GND
Vin
5V
Protocols Revisited 427
Project 32
// note off
noteOff(thisChannel, thisNote, 0);
delay(30);
}
}
}
}
8 noteOn(), noteOff(), and sendMidi() //Send a MIDI note-on message. Like pressing a piano key
are methods to send MIDI //channel ranges from 0-15
commands. The sendMidi() method void noteOn(byte channel, byte note, byte velocity) {
just sends the three bytes you give it. sendMidi( (0x90 | channel), note, velocity);
The noteOn() and noteOff() methods }
use a bitwise OR operation to combine
the command (0x80 or 0x90) with the //Send a MIDI note-off message. Like releasing a piano key
channel into a single byte. void noteOff(byte channel, byte note, byte velocity) {
sendMidi( (0x80 | channel), note, velocity);
When you run this sketch, you should }
hear all the sounds your synth can void sendMidi(int cmd, int data1, int data2) {
make on the first bank of sounds. midi.write(cmd);
midi.write(data1);
midi.write(data2);
}
Protocols Revisited 429
MADE
I N I TA LY
AREF
GND
13
12
11
10
TX
RX
Figure 11-5
9
8
7
6
5
4
3
2
TX 1
RX 0
13
12
11
10
GND
AREF
Reset
MIDI-In
-
L
RESET ICSP
W W W. A R DU I N O. CC
Speaker
Right
- +
Power
Speaker
POWER ANALOG IN
Left
RESET
- +
3.3V
A0
A1
A2
A3
A4
A5
+3.3V
GND
GND
GND
GND
Vin
Analog In
Reset
RST
5V
+5V
VIN
5
430 MAKING THINGS TALK
8
playStinger() plays a sequence void playStinger() {
of notes with a sequence of pauses in int note[] = {43, 41, 49};
between. To do this, it calls notes from int rest[] = {70, 180, 750};
an array using noteOn() and noteOff(),
and then pauses, according to the rest // loop over the three notes:
times given by an array. for (int thisNote = 0; thisNote < 3; thisNote++) {
// Turn on note:
noteon(), noteOff(), and sendMidi() are noteOn(9, note[thisNote], 60);
the same as in the previous example, delay(rest[thisNote]);
and you can copy them from there. //Turn off the note:
noteOff(9, note[thisNote], 60);
// a little pause after the second note:
if (thisNote == 1) {
delay(50);
}
}
}
//NOTE: the noteOn(), noteOff() and sendMidi() methods from the previous
//example go here.
8
resetMidi() takes the reset from void resetMidi(int thisPin) {
the previous example out of setup() // Reset the Musical Instrument Shield:
and puts it in its own method. pinMode(thisPin, OUTPUT);
digitalWrite(thisPin, LOW);
When you've uploaded this sketch, say delay(100);
the following: digitalWrite(thisPin, HIGH);
delay(100);
"A guy walks into a bar and says }
'OUCH!'"
Figure 11-6
Tinker DMX shield, left, and Daniel Hirschmann's
Super DMX shield, right. Both allow you to commu-
nicate with DMX512-based lighting and show control
systems.
432 MAKING THINGS TALK
name=tom&age=14
Protocols Revisited 433
JSON represents each cell of the table as a name-value pair. Each line is a comma-separated list of pairs, enclosed in
curly braces. The whole table is a comma-separated list of lists, like so:
This way of formatting data is relatively simple. The punctuation that separates each element is just a single character,
so you can scan through it one character at a time and know when you're done with each element. Because it's text,
it's human-readable as well as machine-readable. Spaces, newlines, and tabs aren't considered part of the structure of
JSON, so you can reformat it for easier reading like so:
Markup languages describe the structure of the document that the element be played on loading. There aren't HTML
and how it's to be presented, but they don't tell you commands to make anything happen once the page is
anything about what's in the document. They are to text loaded. Markup languages usually rely on an outside actor,
documents what MIDI is to music: it describes the param- like the user, to prompt action.
eters of how to play a note without telling you anything
about the actual timbre of the note. In contrast, programming languages initiate action based
on their own internal logic. Programming languages are
You may have noticed that none of the transfer protocols sets of commands that make things happen. Your job as
you saw used the characters < and >. That is one reason a programmer is to structure a set of commands to make
why HTML uses these for tag markup. In parsing an HTTP things happen they way you want them to.
response, you can know that you've reached the main text
when you hit the first < character. Similarly, wiki markup Programming languages have variables and arrays to
typically uses square brackets, [ and ], to enclose tags. manage simple data, but they generally don't dictate how
This helps distinguish it from HTML or XML markup. you format complex data. The assumption is that you'll
That way, the same document can contain both types of come up with a data format or protocol, and then use
markup without causing conflict. the programming language to read it byte-by-byte and
interpret it, or to assemble it byte-by-byte. Useful pro-
The bytes that form a web page can pass through a lot of gramming languages come with libraries that can read and
programs before they reach the end, each using a different write common data formats, which you've seen through-
protocol. When each protocol is designed to take the out this book. Most of the libraries you used were designed
others into account—as you can see with HTTP, HTML, to read or write a given data format. HTML5 represents a
and wiki markup languages—it's easy for each program to good combination of a markup language (HTML and CSS)
parse the bytes that matter to it and leave the rest alone. and a programming language (JavaScript) that allows
designers and developers to create full applications in a
Most of the time, you don't need all the information you're browser.
given in a typical information transfer. Knowing the proto-
col's structure and syntax not only helps you understand By now you've noticed that programming languages can
what's said, it also helps you determine what to ignore. be somewhat unforgiving when you leave out a comma
Having to evaluate every chunk of data you receive can tax or a semicolon, or get the capitalization of a word wrong.
your system (and your patience) quite a bit. But when you This is because the text of the programming language
know what you can ignore, you win. For example, consider you write is actually a sort of markup language for the
the HTTP POST request that Twilio sends in Chapter 10. compiler. The compiler reads your text and translates it into
There's a huge amount of data there, more than 500 machine language, so the text you write has to be machine-
bytes. The only part you cared about, though, was the readable, just as markup languages and data formats do.
Digits property, so your sketch just scanned through the The challenge to designing a good programming language
incoming stream of text, not saving anything until it saw is similar to designing a good data protocol: you want it to
the string "Digits". That kind of scanning and ignoring is be efficient for the machine to read and interpret, yet still
central to good data parsing. readable by humans.
The basic idea of REST is this: there is a thing somewhere The Arduino would know that it should set digital pin 2 to
on a network. Maybe it's a database, or maybe it's a be an output, and set it high (1 =HIGH). In this scenario,
microcontroller controlling your household appliances, the Arduino is the server—serving you up representations
like you made in the previous chapter. You either want to of its state—and you're the client.
know what state it's in, or you want to change its state.
REST gives you a way to describe, or represent, the state There are three important elements to this exchange:
of the thing on the Net, and to transfer that representation
to a remote user. REST is an addressing scheme for any 1. The representation (called a resource) and its attributes
remote thing. are separated by slashes. You can think of the attributes
like the properties of an object.
You've been using REST already—it's what HTTP is all 2. The verb is the request: whether you want to get some
about. You want to know about the thing, you make a information or change the state of the thing, you start
request to GET that information or to POST changes to with the verb. The verbs are HTTP's verbs: GET, POST,
the thing. The thing responds to your request, either with PUT, and DELETE (the last two are used less often).
a representation of the state of affairs (for example, the 3. The description is technology-independent. There's no
HTML page delivered by the air conditioner controller, actual mention as to whether the resource is delivered
which included representations of the temperature and to you as an HTML page or XML from a web server, or
the state of the thermostat), or by changing the state of whether it's printed by a PHP or Ruby script on a server,
affairs (for example, by updating the thermostat setting). a C/C++ program running on an Arduino, or black
magic. It doesn't matter how the result is generated,
In RESTful thinking, URLs are nouns that describe things, you just want to know what the state of things is, and
and requests are the verbs that act on nouns. The prop- it's the server's job to do that.
erties of things are described in the URL, separated by
slashes. For example, here's a RESTful description of one The beauty of being technology-independent is that you
of an Arduino's pins: can use REST for just about any control interface. For
example, Open Sound Control, or OSC, a protocol for
/pin/A0/ musical controllers that's designed to supersede MIDI,
is RESTful. ACN, the Advanced Controller Networking
If you want to know the state of that pin, you might say to protocol designed to replace DMX512, is also RESTful. It's
the Arduino: also independent of the transport mechanism, and it can
be sent over Ethernet, serial, or any other physical data
GET /pin/A0/ transmission. REST provides a standard way of naming, or
addressing, things so that you keep using that addressing
The Arduino would then reply with the state of pin A0, scheme when you change environments, programming
a number between 0 and 1023. Or, perhaps you want to tools, or network technologies. It's simple enough that you
change the state of a digital output pin. You might do this: can read it with a limited processor, and general enough
to describe most anything you want information about or
POST /pin/D2/1/ want to control.
436 MAKING THINGS TALK
To design RESTfully on the Web, think of the site or device To see them all at once:
you're making in terms of its properties, and come up with
an addressing scheme that gives clients access to view http://mywindows.example.com/window/all
and change those properties appropriately. Practically, what
it means is that all the URLs of your site end at the /. There's To see an individual window (window number 2):
no index.html (or anything .html), and no GET query string.
Query parameters are passed using POST, and they're http://mywindows.example.com/window/2
generally the last item in the address, as you'll see below.
Following are two examples: one is a traditional website To set a window's blind halfway down:
and the other is a physical device on a network.
http://mywindows.example.com/window/2/50
http://myrun.example.com/runnerName/31/1/2012/ What the actual interface returned by the URL looks like is
distance/ up to you. You might choose to make a graphic that shows
images of the windows with blinds, or you might show the
To set the distance to 12.56km: result in text only. RESTful architecture just determines
where to find something, not what you'll find there.
http://myrun.example.com/runnerName/31/1/2012/
distance/12.56 RESTful addresses are designed to be easy for a computer
to parse. All you have to do is to separate the incoming
To set the time to 1 hour, 2 minutes, 34 seconds: request into substrings on the slashes, look at each
substring to see what it is, and act appropriately on the
http://myrun.example.com/runnerName/31/1/2012/ substrings that follow it. They're also easy for people to
time/1:02:34 read. A URL like the ones above is much more comprehen-
sible than the equivalent GET request:
Notice how you can tell a call that gets the value of a
parameter from one that sets the value: the former has http://myrun.example.com/?runnerName=George&day=
nothing following the name of the parameter. 31&month=1&year=2012&distance=12.56
Project 33
Item:
Item: myservice
Item: this
Item: is
Item: a
Item: list
Item: of
Item: restful
Item: parameters
Now that you've got anything that comes in from the client
in an array, you can do whatever you want with it. This is
where things get interesting. From here, you can write a
program to look for and act on different elements in the
list. The following is a brief example that would pull out
the distance and time parameters based on the runners'
website example above.
Protocols Revisited 439
When you combine this approach with standard Every server-side programming language has a variety of
HTML forms using HTTP POST, you have two frameworks designed to make REST easier to implement.
ways of passing in parameters, and your URLs PHP frameworks like Cake and CodeIgniter, Ruby frame-
reflect the state of the resource. It makes for a powerful works like Rails and Sinatra, and many others attempt
and flexible way to build the architecture of a web service, to make it easier for you to build applications, and their
resulting in URLs that are both machine-readable and application programming interfaces (APIs) are designed to
easier for humans to understand. encourage you to build in a RESTful way. With these, you
can often build proxy applications that take data in a more
complex format, and summarize it in a simpler format for
the more limited devices in your system.
X
440 MAKING THINGS TALK
Conclusion
By definition, networked devices don't stand alone. If you're connecting a
device to the Internet, you should take advantage of the power it offers. The
more tools and protocols you know, the easier and more fun that is. Consider
advantages offered by servers that have public addresses—and plenty of
computing horsepower to spare. Consider combinations of wired and wireless
protocols to give the things you build maximum freedom to respond to their
physical environments.
As you can see by now, the physical interfaces that are Making things talk to each other always comes back to
the most flexible are usually the ones that are the most two questions. Who are you serving in making what you're
ephemeral on the network. They get turned on and off, making? What does that person need, and how can you
they connect through private networks, and they use best give it to her?
limited processors to save size, weight, and power. They're
not always capable of doing everything that a dedicated To design a flexible network of physical things that's really
web server can do, nor are they available at all times. useful to humans, you have to think about the person's
However, these are not limitations when such devices are needs and actions first. Then, it's all about the rules of love
used in conversation with dedicated servers. and networking:
As hubs of your projects, use public, persistent servers • Listen More Than You Speak
that have public addresses and are always on the Net. • Never Assume
They can store messages for physical devices that aren't • Agree on How You Say Things
online and deliver them later. They can act as proxies • Ask Politely for Clarification
to take care of things for which simpler devices aren't
designed, like complex data management or authentica- The Internet of Things is useless if those things don't
tion. Don't be afraid to use tools and protocols in ways not improve the quality of our lives and the ways in which we
thought of by their original designers. Make the technology communicate with each other.
fit the person's needs.
Protocols Revisited 441
442 MAKING THINGS TALK
Appendix
MAKE: PROJECTS
»» 13.56MHz antenna Used in »» 2mm 5-pin socket Used in »» 4.7-kilohm resistor Used in
project: 27. projects: 25, 26. projects: 14, 27.
A C000027 SF PRT-10519 D CF14JT4K70CT-ND, J 691024,
»» SD card reader that can read »» 2mm 7-pin socket Used in F 735033, RS 707-8693
MicroSD Available at any local projects: 25, 26. »» 10-kilohm potentiometers Used
electronics or office-supply store. SF PRT-10518 in projects: 10, 11, 13, 14, 27, 29, 30.
Used in projects: 29, 30. »» 6 pin stackable header Used in J 29082, SF COM-09939,
MicroSD card Used in projects: project: 27. F 350072, RS 522-0625
29, 30. SF PRT-09280, AF 85 »» 100-kilohm resistors Used in
IP-based camera Used in projects: »» 8-conductor wire Used in project: project: 14.
29, 30. D-Link DCS-930L 27. D 100KQBK-ND, J 29997,
D AE08A-5-ND, F 1301013 F 9337695, RS 707-8940
»» Interface cable for GPS module »» 270-kilohm resistor Used in
Breakout Boards and Used in project: 19. project: 31.
Connectors SF GPS-00465, P 28146 J 691446, D P270KBACT-ND,
»» RFID breakout board Used in RS 163-921, F 1565367
»» LilyPad XBee Used in project: 14. projects: 25, 26. »» LEDs Used in projects: 7, 8, 10, 11,
SF DEV-08937 SF SEN-08423 20, 26, 29, 30.
»» XBee Explorer Regulated Used in »» 4-wire phone cable with RJ-11 D 160-1144-ND or 160-1665-ND,
project: 14. connector J 34761 or 94511, F 1015878, RS
SF WRL-09132 Used in project: 26. 247-1662 or 826-830, SF COM-
»» Gas sensor breakout board Used D A1642R-07-ND, J 115617, 09592 or COM-09590
in project: 13. F 1335141 »» RGB LED, common cathode Used
SF BOB-08891, P 1479 or 1639 »» 2-pin Screw Terminal Used in in project: 1.
»» 3-wire JST connector pigtail projects: 29, 30. D 754-1492-ND, J 2125181,
Used in project: 15. SF PRT-08432, D 732-2030-ND, SF COM-00105, F 8738661, RS
SF SEN-08733 F 1792766, RS 189-5893 713-4888
»» 9V battery clip Used in projects: »» 3-pin Screw Terminal Used in »» Infrared LED Used in project: 9.
3, 14. projects: 29, 30. J 106526, SF COM-09469,
D 2238K-ND, J 101470, SF PRT- SF PRT-08235, D 732-2031-ND, F 1716710, RS 577-538, SS
09518, F 1650675 F 1792767, RS 710-0166 MTR102A2B
»» Female power plug, 2.1mm ID, »» 5V regulator Used in project: 13,
5.5mm OD Used in project: 3. 14, 19.
D CP-024A-ND, J 159506, F 1737256 Common Components J 51262, D LM7805CT-ND,
»» Wire-wrapping wire Used in SF COM-00107, F 1860277, RS
project: 5. »» 100-ohm resistor Used in 298-8514
D K445-ND, J 22577, SF PRT- project: 8. »» 3.3V regulator Used in projects:
08031, F 150080 D 100QBK-ND, J 690620, 10, 14.
»» Wire-wrapping tool Used in F 9337660, RS 707-8625 J 242115, D 576-1134-ND, SF COM-
project: 5. »» 220-ohm resistor Used in 00526, F 1703357, RS 534-3021
J 242801, F 441089, RSH 276-1570, projects: 5, 8, 9, 11, 20, 26. »» 1µF capacitor Used in projects:
S TOL-00068 D 220QBK-ND, J 690700, 10, 14.
»» 0.1-inch male header pins Used F 9337792, RS 707-8842 J 94161, D P10312-ND, F 8126933,
in projects: 5, 10, 14, 15, 16, 19, 20, »» 1-kilohm resistor Used in projects: RS 475-9009
25, 26, 27. 5, 13, 14, 29, 30. »» 10µF capacitor Used in projects:
D A26509-20-ND, J 103377, SF PRT- D 1.0KQBK-ND, J 29663, 10, 14, 15.
0011, F 1593411 F 1735061, RS 707-8669 J 29891, D P11212-ND, F 1144605,
»» 2mm female header rows Used in »» 10-kilohm resistors Used in RS 715-1638
projects: 10, 14. projects: 2, 6, 9, 11, 12, 13, 14, 20. »» 100µF capacitor Used in projects:
J 2037747, D 3M9406-ND, F D 10KQBK-ND, J 29911, F 9337687, 13, 32.
1776193 RS 707-8906 J 158394, D P10269-ND,
F 1144642, RS 715-1657
446 MAKING THINGS TALK
»» 4700µF electrolytic capacitor »» 1N4148 diode Used in projects: »» EM-406A GPS receiver module
Used in project: 14. 29, 30. Used in project: 19.
J 199006, D P10237-ND, SF COM-08588, F 1081177, SF GPS-00465 P 28146 AF 99
F 1144683, RS 711-1526 D 1N4148TACT-ND, RS 544-3480 »» ST Microelectronics LSM303DLH
»» TIP120 Darlington NPN »» PowerSwitch Tail Alternative part digital compass Used in project:
transistor Used in project: 13. used in projects: 29, 30. 20.
D TIP120-ND, J 32993, F 9804005 SF COM-09842, AF 268 SF SEN-09810, RS 717-3723,
»» 1N4004 power diode Used in P 1250
project: 13. »» LED tactile button Used in
D 1N4004-E3 or 23GI-ND, J 35992, Sensors project: 20.
F 9556109, RS 628-9029 SF COM-10443 and BOB-10467
»» 2N3906 PNP-type transistor »» Flex Sensor resistors Used in »» Temperature sensor Used in
Used in projects: 14, 29, 30. project: 2. projects: 29, 30.
J 178618, D 2N3906D26ZCT- D 905-1000-ND, J 150551, AF 165, D TMP36GT9Z-ND,
ND, SF COM-00522, F 1459017, SF SEN-10264, AF 182, RS 708- F 1438760, RS 427-351
RS 294-328 1277, MS JM150551
»» 9V battery Used in projects: 3, 14. »» Momentary switches or
»» 9–12V DC power supply Used in pushbuttons Used in projects: 2, Miscellaneous
project: 13. 8, 9, 11.
J 170245, SF TOL-00298, AF 63, D GH1344-ND, J 315432, SF COM- »» Ping-pong ball Used in project: 1.
F 636363, P 1463 09337, F 1634684, »» Small pink monkey Used in
»» Lithium Polymer ion battery RS 718-2213, MS JM315432 projects: 2, 3.
Used in project: 31. »» Force-sensing resistors, Interlink »» cat Used in projects: 5, 29, 30.
SF PRT-00341, AF 258, RS 615- 400 series Used in project: 5. »» cat mat Used in project: 5.
2472, F 1848660 D 1027-1000-ND, J 2128260, »» thick pieces of wood or thick
»» USB LiPoly charger Used in project: SF SEN-09673 cardboard, about the size of the
31. »» web camera Used in project: 5. cat mat Used in project: 5
A 259, SF PRT-10217 »» Photocells (light-dependent »» Lighting filters Used in projects:
resistors) Used in projects: 6, 12. 6, 12.
D PDV-P9200-ND, J 202403, »» Triple-wall cardboard Used in
Specialty Components SF SEN-09088, F 7482280, RS project: 8.
234-1050 »» Velcro Used in projects: 8, 31.
»» Voltmeter Used in project: 7. »» 2-axis joystick Used in project: 8. »» Cymbal monkey Used in project:
SF TOL-10285, F 4692810, RS 244- J 2082855, SF COM-09032, 13.
890 AF 245, F 1428461 »» Conductive ribbon Used in
»» MAX8212 voltage monitor Used »» Accelerometer Used in projects: project: 31.
in project: 14. 8, 21. SF DEV-10172
D MAX8212CPA+-ND, F 1610130 J 28017, SF SEN-00692, AF 163, »» Conductive thread Used in
»» solar cell Used in project: 14. RS 726-3738, P 1247, MS MKPX7 project: 31.
SF PRT-07840, P 1691 »» Hanwei gas sensor Used in SF DEV-10120, L A304
»» 16x2 character LCD Used in project: 13. »» Shieldit Super Conductive Fabric
project: 27. SF SEN-08880, SEN-09404, or Used in project: 31.
SF LCD-00709 SEN-09405, P 1480, 1634, 1633, L A1220-14
»» Relay Control PCB Used in 1481, 1482, or 1483 »» Hoodie Used in project: 31.
projects: 29, 30. »» Sharp GP2Y0A21 infrared ranger »» Embroidery thread Used in
SF COM-09096 Used in project: 15. project: 31.
»» Relay Used in project: 29, 30. D 425-2063-ND, SF SEN-00242,
SF COM-00101, D T9AV1D12-12- RS 666-6570, P 136
ND, F 1629059 »» MaxBotix LV-EZ1 ultrasonic
ranger Used in projects: 16, 32.
SF SEN-00639, AF 172, P 726,
SS SEN136B5B
APPENDIX 447
RadioShack
Parallax Hooray! RadioShack has begun RS Online
Parallax makes the Basic Stamp to realizedthat the DIY electronics RS Online is one of Europe’s largest
family of microcontrollers. They also market in the U.S. never went away, electronics retailers. They sell
make the Propeller microcontroller, and and they’re carrying more parts again. worldwide.
a wide range of sensors, beginners’ By the time you read this, maybe www. rs-online.com
kits, robots, and other useful tools for they’ll be carrying Arduinos as well. email: [email protected]
people interested in electronics and Check the website for part numbers, ≈ 0845-850-9900
microcontroller projects. and call your local store first to see ∆ 01536-405678
www.parallax.com whether they’ve got what you need.
email: [email protected] It’ll save you time. Samtec
≈★ +1-888-512-1024 Toll-free sales www.radioshack.com Samtec makes electronic connectors.
≈ +1-916-624-8333 They have a very wide range of
Office/international connectors, so if you’re looking for
∆ +1-916-624-8003 Reynolds Electronics something odd, they probably
õ 599 Menlo Drive Reynolds Electronics makes a number make it.
Rocklin, California 95765, USA of small kits and modules for RF and www.samtec.com
infrared communications, IR remote email: [email protected]
control, and other useful add-on ≈ +1-800-SAMTEC-9
Phidgets functions for microcontroller projects.
Phidgets makes input and output www.rentron.com
modules that connect desktop and email: [email protected] Seeed Studio
laptop computers to the physical ≈ +1-772-589-8510 Seeed Studio makes a number of
world. ∆ +1-772-589-8620 useful and inventive open source elec-
www.phidgets.com õ 12300 Highway A1A tronics parts.
email: [email protected] Vero Beach, Florida, 32963, USA www.seeedstudio.com
≈ +1-403-282-7335 email: [email protected]
∆ +1-402-282-7332 ≈ +86-755-26407752
õ 2715A 16A NW õ Room 0728, Bld 5,
Calgary, Alberta T2M3R7, Canada Dong Hua Yuan,
NanHai Ave. NanShan dist.
Shenzhen 518054 China
APPENDIX 451
Mifare protocol multipath effect, 276 web page for cat cam, 99–100
about, 317 multiplexing, 191 web page for web cam, 110–111
PROJECT 27: Tweets from RFID, Murphy, Glenn, 280 Networked Pong (project 8)
329 Musical Instrument Digital Interface. anatomy of player object, 166–168
reading from tags, 343 See MIDI balance board client, 163–166
writing to tags, 335 Myers, Ryan, 72 client-side overview, 155–156
MISO (Master In, Slave Out) pin, 119, mystery radio error, 184 joystick client, 156–162
376 main server program, 168–177
mkdir command, 13 N project overview, 153
mkdir() method (SD library), 376 NADA tool, 453 server-side overview, 166
MMS (Multimedia Message Service), nameservers, 81 supplies for, 150
393 name-value pairs, 432 test chat server, 153–155
mobile phones nano editor, 14 network identification
about, 366–368 National Marine Electronics Associa- about, 301, 353–354
microcontrollers and, 366–367, tion, 278 PROJECT 28: IP Geocoding,
395 native applications for mobile phones, 355–361
native applications for, 368, 368, 396–400 network interface modules
396–400 navigational terms, 290 about, 118–119
PROJECT 29: Catcam Redux, 364, nearfield communications (NFC), 329 PROJECT 6: Hello Internet! Daylight
369–383 needlenose pliers, 6 Color Web Server, 117,
PROJECT 30: Phoning the Thermo- Negotiating in Bluetooth (project 4) 120–126
stat, 365, 386–400 project overview, 68–71 Network library
PROJECT 31: Personal Mobile Data- supplies for, 39 about, 11
logger, 365, 401–414 netmask, 80, 122 PROJECT 5: Networked Cat, 104
modems NetMedia, 449 serverEvent() method, 155, 168,
about, 64 network cameras, 384–385 172, 174
Bluetooth support, 64 network communication network location, 264–266
defined, 78 about, 37 network maps, 77–79
Hayes AT command protocol, 68 layers of agreement, 40 network protocols, 3
serial-to-Ethernet, 118 PROJECT 1: Type Brighter RGB LED network servers, 3
MOD_REWRITE module, 437 Serial Control, 38, 46–49 network stack, 118
Mok, Jin-Yo, 149, 178 PROJECT 2: Monski Pong, 39, Nevarez, Ariel, 415
Monski Pong (project 2) 50–60 Newark In One Electronics, 449
project overview, 50–60 PROJECT 3: Wireless Monski Pong, New Micros (vendor), 450
supplies for, 39 39, 64–67 New York University, 248
Monski Pong, Wireless (project 3) PROJECT 4: Negotiating in NFC (nearfield communications), 329
adjusting program, 65–66 Bluetooth, 39, 68–71 Nguyen, Tuan Anh T., 1
project overview, 64–67 PROJECT 5: Networked Cat, 76, 9-pin serial connector, 43
supplies for, 39 89–111 NMEA 0183 protocol, 278–280, 285
MOSI (Master Out, Slave In) pin, 119, as session-based, 226 node discovery, 230
376 Networked Air Quality Meter (project node identifier, 231
most significant bit, 423 7) Nordberg, J., 261, 298
most significant digit, 423 project overview, 127–139 noteOff() method (MIDI), 428
MoSync platform, 392 supplies for, 117 noteOn() method (MIDI), 428
Mouser (vendor), 449 Networked Cat (project 5) nslookup command, 134
MSP library, 452 capturing and uploading images,
Mulligan, Ryan, 288 102–106 O
Multi Camera IR Control library, final assembly, 106–111 objects
188–189 project overview, 89–98 communication considerations,
Multimedia Message Service (MMS), sending mail from the cat, 98–99 2, 4
393 supplies for, 76 interface elements and, 2
multimeters, 6 uploading files to servers, 101–102 physical tools for, 5–9
software tools for, 9–12
INDEX 463
Player object (project 8), 166–168 programming languages, 434. See PROJECT 10: Duplex Radio Transmis-
pliers, needlenose, 6 also specific languages sion
Pololu (vendor), 288, 450 PROJECT 1: Type Brighter RGB LED communication between microcon-
POP (Post Office Protocol), 88 Serial Control trollers, 204
port numbers project overview, 46–49 configuring XBee modules serially,
defined, 83 supplies for, 38 193–199
private IP addresses and, 126 PROJECT 2: Monski Pong programming microcontrollers to
position() method (SD library), 376 project overview, 50–60 user XBee module, 200–204
POST command (HTTP) supplies for, 39 project overview, 193
about, 86–87 PROJECT 3: Wireless Monski Pong supplies for, 182
multipart, 106 adjusting program, 65–66 PROJECT 11: Bluetooth Transceivers
PROJECT 5: Networked Cat, 104, project overview, 64–67 circuits, 206–207
110 supplies for, 39 commands, 207–209
PROJECT 29: Catcam Redux, 379 PROJECT 4: Negotiating in Bluetooth connecting two microcontrollers,
$_POST environment variable, 17 project overview, 68–71 215
POSTNET bar code symbology, 312 supplies for, 39 connecting two radios, 209–215
Post Office Protocol (POP), 88 PROJECT 5: Networked Cat. See project overview, 206
potentiometers also PROJECT 5: Networked supplies for, 183
common components, 8 Cat: Catcam Redux PROJECT 12: Hello, Wi-Fi!
defined, 30 capturing and uploading images, project overview, 217–218
PROJECT 11: Bluetooth Transceiv- 102–106 supplies for, 183
ers, 209 final assembly, 106–111 PROJECT 13: Reporting Toxic
PROJECT 13: Reporting Toxic project overview, 89–98 Chemicals in the Shop
Chemicals in the Shop, 238 sending mail from the cat, 98–99 circuits, 235–238
PROJECT 27: Tweets from RFID, supplies for, 76 common problems, 242
343, 347 uploading files to servers, 101–102 project overview, 232–234
purchasing, 7 web page for cat cam, 99–100 radio settings, 234–235
usage example, 33 web page for web cam, 110–111 reading XBee protocol, 238–245
power connectors, 6 PROJECT 6: Hello Internet! Daylight supplies for, 224
power supplies, 6, 344 Color Web Server PROJECT 14: Relaying Solar Cell Data
Power Switch Tail, 372 project overview, 120–126 Wirelessly
pqrcode library, 314 supplies for, 117 circuits, 248–253
preg_match() function (PHP), 132 PROJECT 7: Networked Air Quality graphing results, 254–257
print() function Meter project overvew, 248
SD library, 376 project overview, 127–139 radio settings, 248
Serial library, 54, 121 supplies for, 117 supplies for, 225
println() function PROJECT 8: Networked Pong PROJECT 15: Infrared Distance
SD library, 376 anatomy of player object, 166–168 Ranger Example
Serial library, 121 balance board client, 163–166 project overview, 268–269
private IP addresses, 81, 126 client-side overview, 155–156 supplies for, 262
Processing language. See joystick client, 156–162 PROJECT 16: Ultrasonic Distance
also specific methods main server program, 168–177 Ranger Example
about, 9–11, 453 project overview, 153 project overview, 270–271
additional information, 11 server-side overview, 166 supplies for, 263
Android apps and, 396 supplies for, 150 PROJECT 17: Received Signal
Arduino/Wiring modules and, 20 test chat server, 153–155 Strength Using XBee Radios
classes and, 166 PROJECT 9: Infrared Control of a project overview, 273–275
flow control and, 62–63 Digital Camera supplies for, 263
libraries supported, 227 project overview, 188–189
PHP language and, 17 supplies for, 182
profiles, defined, 64
INDEX 465
PROJECT 18: Reading Received Signal PROJECT 29: Catcam Redux. See pulses
Strength Using Bluetooth also Processing language: carrier waves and, 185
Radios Networked Cat communication protocols and, 2
project overview, 276 circuits, 372–373 pulse width modulation (PWM), 127,
supplies for, 263 coding, 373–383 234
PROJECT 19: Reading GPS Serial project overview, 369–371 pulse width ratio, 235
Protocol supplies for, 364 Puredata (PD) tool, 453
project overview, 278–285 PROJECT 30: Phoning the Thermo- push buttons
supplies for, 263 stat common components, 8
PROJECT 20: Determining Heading project overview, 386 PROJECT 11: Bluetooth Transceiv-
Using a Digital Compass supplies for, 365 ers, 209
project overview, 286–289 text messaging, 393–395 purchasing, 7
supplies for, 263 PROJECT 31: Personal Mobile Data- PUT command (HTTP), 86
PROJECT 21: Determining Attitude logger PuTTY program
Using an Accelerometer, circuits, 402 about, 18, 453
290–298 coding, 405–414 configuring serial connection, 19
PROJECT 22: Color Recognition Using construction, 402–405 disconnecting connection, 18
a Webcam project overview, 401 downloading, 12, 84
project overview, 306–309 supplies for, 365 PWM (pulse width modulation), 127,
supplies for, 302 PROJECT 32: Fun with MIDI 234
PROJECT 23: Face Detection Using a project overview, 427–430 Python language, 395
Webcam supplies for, 418
project overview, 310–311 PROJECT 33: Fun with REST, 437–439 Q
supplies for, 302 protocols. See also specific protocols QR code
PROJECT 24: 2D Bar Code Recogni- binary, 422–424, 431 about, 305, 312
tion Using Webcam defined, 2–3 PROJECT 24: 2D Bar Code Rec-
project overview, 313–315 good habits for, 5 ognition Using Webcam,
supplies for, 302 making connections, 419–421 313–315
PROJECT 25: Reading RFID tags in network, 3 QRcode library, 453
Processing planning physical system, 421 Quantified Self meetups, 401
project overview, 318–320 PROJECT 1: Type Brighter RGB LED querying for devices
supplies for, 302 Serial Control, 46–49 UDP support, 227–230
PROJECT 26: RFID Meets Home Auto- PROJECT 2: Monski Pong, 50–60 using 802.15.4, 230–231
mation PROJECT 32: Fun with MIDI, 418, Quicktime program, 102
project overview, 321–328 427–430
supplies for, 303 PROJECT 33: Fun with REST, R
PROJECT 27: Tweets from RFID 437–439 RabbitCore processors, 118
circuits, 329–332, 343–346 REST principle, 435–436 radio frequency (RF) shields, 191
construction, 351–352 serial, 3 Radio Shack, 450
project overview, 329 text, 422–424, 432–434 radios, purchasing, 216
saving program memory, 346–351 prototyping boards radio transceivers. See transceivers
SonMicro communications about, 156 radio transmission. See also signal
protocol, 333–335 depicted, 158 strength
supplies for, 303 used in projects, 444 about, 185, 190
troubleshooting, 350 prototyping shields, 7 digital and analog, 190
writing Mifare tags, 335 PSTN (public switched telephone node discovery, 230
PROJECT 28: IP Geocoding network), 386 node identifier, 231
mail environment variables, public IP addresses, 81, 126 PROJECT 10: Duplex Radio Trans-
357–359 public switched telephone network mission, 182, 193–205
project overview, 355–357 (PSTN), 386 PROJECT 17: Received Signal
pull-down resistors, 30 Strength Using XBee Radios,
pull-up resistors, 30 263, 273–275
466 MAKING THINGS TALK
PROJECT 18: Reading Received $_REQUEST environment variable, 17, RSSI (received signal strength), 273
Signal Strength Using 85, 406 RTS (Request to Send), 45
Bluetooth Radios, 263, 276 Request to Send (RTS), 45 RX (receive pin), 45, 215, 240
read() function (Serial library), 121 resetMidi() method (MIDI), 430 rxvt program, 12
Reading GPS Serial Protocol (project resistors
19) common components, 8 S
project overview, 278–285 PROJECT 5: Networked Cat, 89 safety goggles, 6
supplies for, 263 pull-down, 30 Samtec (vendor), 450
Reading Received Signal Strength pull-up, 30 scalar variables, 17
Using Bluetooth Radios purchasing, 7 Schelling, Nahana, 415
(project 18) REST (Representational State Schneider, Andrew, 223
project overview, 276 Transfer) screen programs
supplies for, 263 about, 435–436 closing down, 18
Reading RFID tags in Processing PROJECT 33: Fun with REST, defined, 18
(project 25) 437–439 screwdrivers, 6
project overview, 318–320 Revolution Education, 23 SD cards
supplies for, 302 Reynolds Electronics, 186, 450 best practices, 376–377
Reas, Casey, 11 RFID technology reading from, 375
received signal strength (RSSI), 273 about, 304, 315–317 writing to, 376
Received Signal Strength Using XBee bar code recognition and, 315 SD library
Radios (project 17) PROJECT 25: Reading RFID tags in about, 376
project overview, 273–275 Processing, 302, 318–320 adding, 375
supplies for, 263 PROJECT 26: RFID Meets Home begin() method, 375
receive() method (UDP library), 228 Automation, 303, 321–328 close() function, 376
receive pin (RX), 45, 215, 240 PROJECT 27: Tweets from RFID, exists() method, 376
receivers 329–350 flush() function, 376
defined, 185 testing circuits, 324 mkdir() method, 376
distance ranging and, 272 RF (radio frequency) shields, 191 peek() method, 376
Rectangle object (Java), 310 ring networks, 77 position() method, 376
relative path, 13 rising edge of the clock, 289 print() function, 376
Relaying Solar Cell Data Wirelessly RJ-11 jacks, 321 println() function, 376
(project 14) RJ-45 connectors, 431 remove() method, 376
circuits, 248–253 RMC data, 280 rmdir() method, 376
graphing results, 254–257 rm command, 15 seek() method, 376
project overvew, 248 rmdir command, 14 size() method, 376
radio settings, 248 rmdir() method (SD library), 376 write() function, 376
supplies for, 225 Rogue Robotics, 22 Seeed Studio, 34, 450
REMOTE_ADDR environment roll rotation, 290, 292 seek() method (SD library), 376
variable, 354 root directory, 13 Seidle, Nathan, 372
remove() method (SD library), 376 rotate() method (Processing), 297 send() method (UDP library), 227
Reporting Toxic Chemicals in the rotations sending messages
Shop (project 13) defined, 290 broadcast messages, 193, 226–231
circuits, 235–238 depicted in three dimensions, 292 directed messages, 246–257
common problems, 242 measuring, 290, 292 good habits for, 4
project overview, 232–234 routers HTTP commands, 86–87
radio settings, 234–235 defined, 78 packet switching and, 81–82
reading XBee protocol, 238–245 gateway addresses, 122 PROJECT 5: Networked Cat, 95–99
supplies for, 224 port numbers and, 126 PROJECT 10: Duplex Radio Trans-
Representational State Transfer Roving Networks, 69, 206, 450 mission, 193
(REST) RS-232 serial protocol, 43, 421 sessions versus, 226
about, 435–436 RS-485 protocol, 421, 431 troubleshooting, 81
PROJECT 33: Fun with REST, RS Online, 450 sendMidi() method (MIDI), 428
437–439
INDEX 467
sendPacket() method (UDP library), uploading files to, 101–102 Simple Mail Transfer Protocol
229 web browsing and, 83 (SMTP), 88, 432
sensors writing test programs for, 146 SIP (Session Initiation Protocol),
common components, 8 server-side scripts, 15 386–387
determining distance, 267 Service Discovery Protocol, 64 size() method (SD library), 376
feedback loops and, 151 Session Initiation Protocol (SIP), Sjaastad, Mosse, 301
PhoneGap platform, 392 386–387 sketches
purchasing, 7 sessionless networks defined, 9
used in projects, 446 about, 223 flow control and, 62
sentences (NMEA protocol), 279 broadcast messages, 227–231 Sketchtools NADA tool, 453
serial buffer, 62 PROJECT 13: Reporting Toxic Sklar, David, 17
serial clock pin, 289 Chemicals in the Shop, 224, Skyetek, 451
serial communication. See also asyn- 232–245 Skyhook site, 267
chronous serial communi- PROJECT 14: Relaying Solar Slave Select (SS) pin, 119
cation; synchronous serial Cell Data Wirelessly, 225, Slavin, Kevin, 312
communication 248–257 SM13X FU tool, 336
about, 3, 17, 28–30 sessions versus messages, 226 Smarthome (vendor), 322, 451
debugging methods, 140–142 sessions smartphones. See mobile phones
defined, 40 defined, 152, 226 Smith, Jared, 386
Linux environment, 18 messages versus, 226 SMRFID Mifare v1.2 diagnostic
Mac OS X environment, 18 setting the bit, 423 software, 336
NMEA 0183 protocol, 278 setup() method (Processing), 11, 20 SMS (Short Messaging Service)
picking protocols, 420–421 Setz, Sebastian, 188 about, 393–394
Windows environment, 18 SFTP library, 453 mobile phone support, 368
serial data pin, 289 shape recognition, 309 SMTP (Simple Mail Transfer Protocol),
Serial library shields. See also Ethernet shield 88, 432
about, 11 compatibility considerations, 22 sockets
available() function, 121 defined, 22 defined, 152
list() function, 296 depicted for Arduino module, 22 PROJECT 8: Networked Pong, 150,
print() function, 54, 121 making, 22 153–177
println() function, 121 used in projects, 444 software interfaces, 2, 4
read() function, 121 Wireless, 199 software objects
write() function, 54, 121 Shiffman, Daniel, 11, 313, 453 about, 2
Serial Monitor (Arduino), 31, 53, 230 shift left operator (<<), 423 interface considerations, 2, 4
Serial Peripheral Interface. See SPI shift right operator (>>), 423 software oscilloscopes, 34
Serial Port Profile (SPP), 64, 401 Short Messaging Service (SMS) SoftwareSerial library, 321, 324
serial ports about, 393–394 software tools. See also specific
about, 17 mobile phone support, 368 software
Arduino/Wiring modules, 29 signal connections, 31 list of, 452–453
closing, 18, 57 signal strength Processing tool, 9–11
releasing, 18, 57 distance ranging and, 267, 272 remote access applications, 11–12
usage considerations, 18 measuring, 275 Solaris environment, 11
Windows environment, 18 PROJECT 17: Received Signal soldering irons and solder, 6
serial-to-Ethernet modems, 118 Strength Using XBee Radios, solderless breadboards
serial-to-USB converters, 7 263, 273–275 Arduino/Wiring modules and, 30,
serverEvent() method (Network PROJECT 18: Reading Received 31
library), 155, 168, 172, 174 Signal Strength Using common components, 8
servers Bluetooth Radios, 263, 276 perf boards and, 156
defined, 82 RFID systems and, 316 purchasing, 7
making public, 383 SIM cards, 395 sonMicroEvent() method (SonMicro-
PROJECT 8: Networked Pong, SimpleDmx library, 431 Reader library), 339
166–177 SonMicroReader library, 335, 339
468 MAKING THINGS TALK
The Ultimate Microcontroller Pack includes everything You never know when you'll find yourself in a MacGyver
you need to dive right into the world of microcontollers. moment. It can happen anywhere, at any time. Wouldn't
The 100+ components allow you to complete nearly it be easier to hack those electronics with some real
any online tutorial without having to source individual components instead of a rubber band and a paper clip?
parts. Everyone from beginners to advanced users will The Mintronics: Survival Pack from the Maker Shed con-
appreciate all that the Ultimate Microcontroller Pack tains over 60 useful components for making, hacking,
has to offer. and modifying electronic circuits and repairs on the go.
The ultimate open source prototyping shield for Arduino is a tool for making computers that can sense
Arduino & compatible microcontrollers. Create your and control more of the physical world than your desk-
circuits the way you want, and easily changes without top computer!
having to solder.
Save 15%
With coupon code:
TALK
Offer expires at midnight on 12/31/2011