This book is a cookbook of sorts, and this chapter covers the key ingredients. The concepts and tools you’ll use in every chapter are introduced 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.
All of the objects that you’ll encounter in this book—tangible or intangible—will have certain behaviors. Software objects will send and receive messages, store data, or both. Physical objects will move, light up, or make noise. The first question to ask about any object is: what does it do? The second is: how do I make it do what it’s supposed to do? Or, more simply, what is its interface?
An object’s interface is made up of three elements. First, there’s the physical interface. This is the stuff you touch—such as knobs, switches, keys, and other sensors—that react to your actions. The connectors that join objects are also part of the physical interface. Every network of objects begins and ends with a physical interface. Even though some objects in a network (such as software objects) have no physical interface, people construct mental models of how a system works based on the physical interface. A computer is much more than the keyboard, mouse, and screen, but that’s what we think of it as, because that’s what we see and touch. You can build all kinds of wonderful functions into your system, but if those functions aren’t apparent in the things people see, hear, and touch, they will never be used. Remember the lesson of the VCR clock that constantly blinks 12:00 because no one can be bothered to learn how to set it? If the physical interface isn’t good, the rest of the system suffers.
Second, there’s the software interface—the commands that you send to the object to make it respond. In some projects, you’ll invent your own software interface; in others, you’ll rely on existing interfaces to do the work for you. The best software interfaces have simple, consistent functions that result in predictable outputs. Unfortunately, not all software interfaces are as simple as you’d like them to be, so be prepared to experiment a little to get some software objects to do what you think they should do. When you’re learning a new software interface, it helps to approach it mentally in the same way you approach a physical interface. Don’t try to use all the functions at once; first, learn what each function does on its own. You don’t learn to play the piano by starting with a Bach fugue—you start one note at a time. Likewise, you don’t learn a software interface by writing a full application with it—you learn it one function at a time. There are many projects in this book; if you find any of their software functions confusing, write a simple program that demonstrates just that function, then return to the project.
Finally, there’s the electrical interface—the pulses of electrical energy sent from one device to another to be interpreted as information. Unless you’re designing new objects or the connections between them, you never have to deal with this interface. When you’re designing new objects or the networks that connect them, however, you have to understand a few things about this interface, so that you know how to match up objects that might have slight differences in their electrical interfaces.
In order to communicate with each other, objects use communications protocols. A protocol is a series of mutually agreed-upon standards for communication between two or more objects.
Serial protocols like RS-232, USB, and IEEE 1394 (also known as FireWire and i.Link) connect computers to printers, hard drives, keyboards, mice, and other peripheral devices. Network protocols like Ethernet and TCP/IP connect multiple computers through network hubs, routers, and switches. A communications protocol usually defines the rate at which messages are exchanged, the arrangement of data in the messages, and the grammar of the exchange. If it’s a protocol for physical objects, it will also specify the electrical characteristics, and sometimes even the physical shape of the connectors. Protocols don’t specify what happens between objects, however. The commands to make an object do something rely on protocols in the same way that clear instructions rely on good grammar—you can’t give useful instructions if you can’t form a good sentence.
One thing that all communications protocols have in common—from the simplest chip-to-chip message to the most complex network architecture—is this: it’s all about pulses of energy. Digital devices exchange information by sending timed pulses of energy across a shared connection. The USB connection from your mouse to your computer uses two wires for transmission and reception, sending timed pulses of electrical energy across those wires. Likewise, wired network connections are made up of timed pulses of electrical energy sent down the wires. For longer distances and higher bandwidth, the electrical wires may be replaced with fiber optic cables, which carry timed pulses of light. In cases where a physical connection is inconvenient or impossible, the transmission can be sent using pulses of radio energy between radio transceivers (a transceiver is two-way radio, capable of transmitting and receiving). The meaning of data pulses is independent of the medium that’s carrying them. You can use the same sequence of pulses whether you’re sending them across wires, fiber optic cables, or radios. If you keep in mind that all of the communication you’re dealing with starts with a series of pulses—and that somewhere there’s a guide explaining the sequence of those pulses—you can work with any communication system you come across.
You’ll encounter at least four different types of computers in this book, grouped according to their physical interfaces. The most familiar of these is the personal computer. Whether it’s a desktop or a laptop, it’s got a keyboard, screen, and mouse, and you probably use it just about every working day. These three elements—the keyboard, the screen, and the mouse—make up its physical interface.
The second type of computer you’ll encounter in this book, the microcontroller, has no physical interface that humans can interact with directly. It’s just an electronic chip with input and output pins that can send or receive electrical pulses. Using a microcontroller is a three-step process:
You connect sensors to the inputs to convert physical energy like motion, heat, and sound into electrical energy.
You attach motors, speakers, and other devices to the outputs to convert electrical energy into physical action.
Finally, you write a program to determine how the input changes affect the outputs.
In other words, the microcontroller’s physical interface is whatever you make of it.
The third type of computer in this book, the network server, is basically the same as a desktop computer—it may even have a keyboard, screen, and mouse. Even though it can do all the things you expect of a personal computer, its primary function is to send and receive data over a network. Most people don’t think of servers as physical things because they only interact with them over a network, using their local computers as physical interfaces to the server. A server’s most important interface for most users’ purposes is its software interface.
The fourth group of computers is a mixed bag: mobile phones, music synthesizers, and motor controllers, to name a few. Some of them will have fully developed physical interfaces, some will have minimal physical interfaces but detailed software interfaces, and most will have a little of both. Even though you don’t normally think of these devices as computers, they are. When you think of them as programmable objects with interfaces that you can manipulate, it’s easier to figure out how they can all communicate, regardless of their end function.
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. All he or she has to go on are the words you say and the actions you take. Likewise, you may know exactly what message your local computer is sending, how it’s sending it, and what all the bits mean, but the remote computer has no idea what they mean unless you program it to understand them. All it has to go on are the bits it receives. If you want reliable, clear communications (in love or networking), there are a few simple things you have to do:
Listen more than you speak.
Never assume that what you said is what they heard.
Agree on how you’re going to say things in advance.
Ask politely for clarification when messages aren’t clear.
The best way to make a good first impression, and to maintain a good relationship, is to be a good listener. Listening is more difficult than speaking. You can speak anytime you want, but since you never know when the other person is going to say something, you have to listen all the time. In networking terms, this means you should write your programs such that they’re listening for new messages most of the time, and sending messages only when necessary. It’s often easier to send out messages all the time rather than figure out when it’s appropriate, but it can lead to all kinds of problems. It usually doesn’t take a lot of work to limit your sending, and the benefits far outweigh the costs.
What you say is not always what the other person hears. Sometimes it’s a matter of misinterpretation, and other times, you may not have been heard clearly. If you assume that the message got through and continue on obliviously, you’re in for a world of hurt. Likewise, you may be inclined to first work out all the logic of your system—and all the steps of your messages before you start to connect things—then build it, and finally test it all at once. Avoid that temptation.
It’s good to plan the whole system out in advance, but build it and test it in baby steps. Most of the errors that occur when building these projects happen in the communication between objects. Always send a quick “Hello World!” message from one object to the others, and make sure that the message got there intact before you proceed to the more complex details. Keep that “Hello World!” example on hand for testing when communication fails.
Getting the message wrong isn’t the only misstep you can make. Most of the projects in this book involve building the physical, software, and electrical elements of the interface. One of the most common mistakes people make when developing hybrid projects like these is to assume that the problems are all in one place. Quite often, I’ve sweated over a bug in the software transmission of a message, only to find out later that the receiving device wasn’t even connected, or wasn’t ready to receive messages. Don’t assume that communication errors are in the element of the system with which you’re most familiar. They’re most often in the element with which you’re least familiar, and therefore, are avoiding. When you can’t get a message through, think about every link in the chain from sender to receiver, and check every one. Then check the links you overlooked.
In good relationships, you develop a shared language based on shared experience. You learn the best ways to say things so that your partner will be most receptive, and you develop shorthand for expressing things that you repeat all the time. Good data communications also rely on shared ways of saying things, or protocols. Sometimes you make up a protocol for all the objects in your system, and other times you have to rely on existing protocols. If you’re working with a previously established protocol, make sure you understand all the parts before you start trying to interpret it. If you have the luxury of making up your own protocol, make sure you’ve considered the 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.
Messages get garbled in countless ways. Perhaps you hear something that may not make much sense, but you act on it, only to find out that your partner said something entirely different from what you thought. It’s always best to ask nicely for clarification to avoid making a stupid 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 wise to check, rather than assume, that a message was sent. Saying nothing can be worse than saying something wrong. Minor problems can become major when no one speaks up to acknowledge that there’s an issue. The same thing can occur in network communications. One device may wait forever for a message from the other side, not knowing, for example, that the remote device is unplugged. When you don’t receive a response, send another message. Don’t resend it too often, and give the other party time to reply. Acknowledging messages may seem like a luxury, but it can save a whole lot of time and energy when you’re building a complex system.
If you’ve worked with electronics or microcontrollers before, chances are you have your own hand tools already. Figure 1-1 shows the ones used most frequently in this book. They’re common tools that can be obtained from many vendors. A few are listed in Table 1-1.
In addition to hand tools, there are some common electronic 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.
You’ll find a number of component suppliers in this book. I buy from different vendors depending on who’s got the best and the least expensive version of each part. Sometimes it’s easier to buy from a vendor that you know carries what you need, rather than search through the massive catalog of a vendor who might carry it for less. Feel free to substitute your favorite vendors. A list of vendors can be found in the Appendix.
Handy hand tools for networking objects.
Soldering iron Middle-of-the-line is best here. Cheap soldering irons die fast, but a mid-range iron like the Weller WLC-100 works great for small electronic work. Avoid the Cold Solder irons. They solder by creating a spark, and that spark can damage static-sensitive parts like microcontrollers. Jameco (http://jameco.com): 146595; Farnell (www.farnell.com): 1568159; RadioShack (http://radioshack.com): 640-2801 and 640-2078
Solder 21-23 AWG solder is best. Get lead-free solder if you can; it’s healthier for you. Jameco: 668271; Farnell: 419266; RadioShack: 640-0013
Desoldering pump This helps when you mess up while soldering. Jameco: 305226; Spark Fun (www.SparkFun.com): TOL-00082; Farnell: 3125646
Wire stripper, Diagonal cutter, Needle-nose pliers Avoid the 3-in-1 versions of these tools. They’ll only make you grumpy. These three tools are essential for working with wire, and you don’t need expensive ones to have good ones.
Wire stripper: Jameco: 159291; Farnell: 609195; Spark Fun: TOL-00089; RadioShack: 640-2129A
Diagonal cutter: Jameco: 161411; Farnell: 3125397; Spark Fun: TOL-00070; RadioShack: 640-2043
Mini-screwdriver Get one with both Phillips and slotted heads. You’ll use it all the time. Jameco: 127271; Farnell: 4431212; RadioShack: 640-1963
Helping hands These make soldering much easier. Jameco: 681002; Farnell: 1367049
Multimeter You don’t need an expensive one. As long as it measures voltage, resistance, amperage, and continuity, it’ll do the job. Jameco: 220812; Farnell: 7430566; Spark Fun: TOL-00078; RadioShack: 22-182
Oscilloscope Professional oscilloscopes are expensive, but the DSO Nano is only about $100 and a valuable aid when working on electronics. Spark Fun: TOL-10244 (v2); Seeed Studio (www.seeedstudio.com): (TOL114C3M; Maker SHED (www.makershed.com): MKSEEED11
9–12V DC power supply You’ll use this all the time, and you’ve probably got a spare from some dead electronic device. Make sure you know the polarity of the plug so you don’t reverse polarity on a component and blow it up! Most of the devices shown in this book have a DC power jack that accepts a 2.1mm inner diameter/5.5mm outer diameter plug, so look for an adapter with the same dimensions. Jameco: 170245 (12V, 1000mA); Farnell: 1176248 (12V, 1000mA); Spark Fun: TOL-00298; RadioShack: 273-355 (9V 800mA)
Power connector, 2.1mm inside diameter/5.5mm outside diameter You’ll need this to connect your microcontroller module or breadboard to a DC power supply. This size connector is the most common for the power supplies that will work with the circuits you’ll be building here. Jameco: 159610; Digi-Key (www.digikey.com): CP-024A-ND; Farnell: 3648102
9V Battery snap adapter and 9V battery When you want to run a project off battery power, these adapters are a handy way to do it. Spark Fun: PRT-09518; Adafruit (http://adafruit.com): 80; Digi-Key: CP3-1000-ND and 84-4K-ND; Jameco: 28760 and 216452; Farnell: 1650675 and 1737256; RadioShack: 270-324 and 274-1569
USB cables You’ll need both USB A-to-B (the most common USB cables) and USB A-to-mini-B (the kind that’s common with digital cameras) for the projects in this book. Spark Fun: CAB-00512, CAB-00598; Farnell: 1838798, 1308878
Alligator clip test leads It’s often hard to juggle the five or six things you have to hold when metering a circuit. Clip leads make this much easier. Jameco: 10444; RS (www.rs-online.com): 483-859; Spark Fun: CAB-00501; RadioShack: 278-016
Serial-to-USB converter This converter lets you speak TTL serial from a USB port. Breadboard serial-to-USB modules, like the FT232 modules shown here, are cheaper than the consumer models and easier to use in the projects in this book. Spark Fun: BOB-00718; Arduino Store (store.arduino.cc): A000014
Microcontroller module The microcontroller shown here is an Arduino Uno. Available from Spark Fun and Maker SHED (http://store.arduino.cc/ww/) in the U.S., and from multiple distributors internationally. See http://arduino.cc/en/Main/Buy for details about your region.
Voltage regulator Voltage regulators take a variable input voltage and output a constant (lower) voltage. The two most common you’ll need for these projects are 5V and 3.3V. Be careful when using a regulator that you’ve never used before. 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
TIP120 Transistor Transistors act as digital switches, allowing you to control a circuit with high current or voltage from one with lower current and voltage. There are many types of transistors, the 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
Prototyping shields These are add-on boards for the Arduino microcontroller module that have a bare grid of holes to which you can solder. You can build your own circuits on them by soldering, or you can use a tiny breadboard (also shown) to test circuits quickly. These are handy for projects where you need to prototype quickly, as well as a compact form to the electronics. Adafruit: 51; Arduino Store: A000024; Spark Fun: DEV-07914; Maker SHED: MSMS01
Breadboards for protoshields: Spark Fun: PRT-08802; Adafruit: included with board; Digi-Key: 923273-ND
Solderless breadboard Having a few around can be handy. I like the ones with two long rows on either side so that you can run power and ground on both sides. Jameco: 20723 (2 bus rows per side); Farnell: 4692810; Digi-Key: 438-1045-ND; Spark Fun: PRT-00137; RadioShack: 276-002
Spare LEDs for tracing signals LEDs are to the hardware developer what print statements are to the software developer. They let you see quickly whether there’s voltage between two points, or whether a signal is going through. Keep spares on hand. Jameco: 3476; Farnell: 1057119; Digi-Key: 160-1144-ND; RadioShack: 278-016
Resistors You’ll need resistors of various values for your projects. Common values are listed in Table 1-1.
Header pins You’ll use these all the time. It’s handy to have female ones around as well. Jameco: 103377; Digi-Key: A26509-20-ND; Farnell: 1593411
Analog sensors (variable resistors) There are countless varieties of variable resistors to measure all kinds of physical properties. They’re the simplest of analog sensors, and they’re very easy to build into test circuits. Flex sensors and force-sensing resistors are handy for testing a circuit or a program. Flex sensors: Jameco: 150551; Images SI (www.imagesco.com): FLX-01
Force-sensing resistors: Parallax (www.parallax.com): 30056; Images SI: FSR-400, 402, 406, 408
Pushbuttons There are two types you’ll find handy: the PCB-mount type, like the ones you find on Wiring and Arduino boards, used here mostly as reset buttons for breadboard projects; and panel-mount types used for interface controls for end users. But you can use just about any type you want.
PCB-mount type: Digi-Key: SW400-ND; Jameco: 119011; Spark Fun: COM-00097
Panel-mount type: Digi-Key: GH1344-ND; Jameco: 164559PS
Potentiometers You’ll need potentiometers to let people adjust settings in your project. Jameco: 29081; Spark Fun: COM-09939; RS: 91A1A-B28-B15L; RadioShack: 271-1715; Farnell: 1760793
Black, red, blue, yellow wire 22 AWG solid-core hook-up wire is best for making solderless breadboard connec- tions. Get at least three colors, and always use red for voltage and black for ground. A little organization of your wires can go a long way.
Black: Jameco: 36792
Blue: Jameco: 36767
Green: Jameco: 36821
Red: Jameco: 36856;
Yellow: Jameco: 36919
Mixed: RadioShack: 276-173
Capacitors You’ll need capacitors of various values for your projects. Common values are listed in Table 1-1.
You’re going to run across some hardware in the following chapters that was brand new when this edition was written, including the Arduino Ethernet board, the Arduino WiFi shield, wireless shield, RFID shield, USB-to-Serial adapter, and more. The distributors listed here didn’t have part numbers for them as of this writing, so check for them by name. By the time you read this, distributors should have them in stock.
D Digi-Key (http://digikey.com)
J Jameco (http://jameco.com)
R RS (www.rs-online.com)
F Farnell (www.farnell.com)
100Ω .......... D 100QBK-ND, J 690620, F 9337660, R 707-8625
220Ω .......... D 220QBK-ND, J 690700, F 9337792, R 707-8842
470Ω .......... D 470QBK-ND, J 690785, F 9337911, R 707-8659
1K .......... D 1.0KQBK, J 29663, F 1735061, R 707-8669
10K .......... D 10KQBK-ND, J 29911, F 9337687, R 707-8906
22K .......... D 22KQBK-ND, J 30453, F 9337814, R 707-8729
100K .......... D 100KQBK-ND, J 29997, F 9337695, R 707-8940
1M .......... D 1.0MQBK-ND, J 29698, F 9337709, R 131-700
T1, Green clear .......... D 160-1144-ND, J 34761, F 1057119, R 247-1662
T1, Red, clear .......... D 160-1665-ND, J 94511, F 1057129, R 826-830
2N2222A .......... D P2N2222AGOS-ND, J 38236, F 1611371, R 295-028
TIP120 .......... D TIP120-ND, J 32993, F 9804005
1N4004-R .......... D 1N4004-E3, J 35992, F 9556109, R 628-9029
3.3V zener (1N5226) .......... D 1N5226B-TPCT-ND, J 743488, F 1700785
PCB .......... D SW400-ND, J 119011, F 1555981
Panel Mount .......... D GH1344-ND, J 164559PS, F 1634684, R 718-2213
0.1µF ceramic .......... D 399-4151-ND, J 15270, F 3322166, R 716-7135
1µF electrolytic .......... D P10312-ND, J 94161, F 8126933, R 475-9009
10µF electrolytic .......... D P11212-ND, J 29891, F 1144605, R 715-1638
100µF electrolytic .......... D P10269-ND, J 158394, F 1144642, R 715-1657
various .......... D 438-1045-ND, J 20723, 20600, F 4692810
red .......... D C2117R-100-ND, J 36856, F 1662031
black .......... D C2117B-100-ND, J 36792, F 1662027
blue .......... J 36767, F 1662034
yellow .......... J 36920, F 1662032
3.3V .......... D 576-1134-ND, J 242115, F 1703357, R 534-3021
5V .......... D LM7805CT-ND, J 51262, F 1860277, R 298-8514
10K .......... D 29081
straight .......... D A26509-20-ND, J 103377, S PRT-00116
right angle .......... D S1121E-36-ND, S PRT-00553
Flex sensors .......... D 905-1000-ND, J 150551, R 708-1277
FSRs .......... D 1027-1000-ND, J 2128260
female .......... S PRT-00115
9V .......... D 2238K-ND, J 101470PS, S PRT-00091
It’s not too flashy a program, but it’s a classic. It should
Hello World! in the message
box at the bottom of the editor window. It’s that easy.
Programs in Processing are called sketches, and all the data for a sketch is saved in a folder with the sketch’s name. The editor is very basic, without a lot of clutter to get in your way. The toolbar has buttons to run and stop a sketch, create a new file, open an existing sketch, save the current sketch, or export to a Java applet. You can also export your sketch as a standalone application from the File menu. Files are normally stored in a subdirectory of your Documents folder called Processing, but you can save them wherever you like.
Every Processing program has two main routines,
setup() happens once at the beginning of
the program. It’s where you set all your initial conditions, like
the size of the applet window, initial states for variables, and so
draw() is the main loop of
the program. It repeats continuously until you close the applet
In order to use variables in Processing, you have to declare
the variable’s data type. In the preceding program, the variables
blueValue are all
float types, meaning that they’re floating
decimal-point numbers. Other common variable types you’ll use are
booleans (true or false values),
Strings of text, and
Like C, Java, and many other languages, Processing uses
C-style syntax. All functions have a data type,
just like variables (and many of them are the
void type, meaning that they don’t return
any values). All lines end with a semicolon, and all blocks of code
are wrapped in curly braces. Conditional statements (if-then
statements), for-next loops, and comments all use the C syntax as
well. The preceding code illustrates all of these except the
Processing is a fun language to play with because you can make interactive graphics very quickly. It’s also a simple introduction to Java for beginning programmers. If you’re a Java programmer already, you can include Java directly in your Processing programs. Processing is expandable through code libraries. You’ll be using two of the Processing code libraries frequently in this book: the serial library and the networking library.
For more on the syntax of Processing, see the language reference guide at www.processing.org. To learn more about programming in Processing, check out Processing: A Programming Handbook for Visual Designers and Artists, by Casey Reas and Ben Fry (MIT Press), the creators of Processing, or their shorter book, Getting Started with Processing (O’Reilly). Or, read Daniel Shiffman’s excellent introduction, Learning Processing (Morgan Kaufmann). There are dozens of other Processing books on the market, so find one whose style you like best.
One of the most effective debugging tools you’ll use when making the projects in this book is a command-line remote-access program, which gives you access to the command-line interface of a remote computer. If you’ve never used a command-line interface before, you’ll find it a bit awkward at first, but you get used to it pretty quickly. This tool is especially important when you need to log into a web server, because you’ll need the command line to work with PHP scripts that will be used in this book.
Most web hosting providers are based on Linux, BSD, Solaris, or some other Unix-like operating system. So, when you need to do some work on your web server, you may need to make a command-line connection to your web server.
If you already know how to create PHP and HTML documents and upload them to your web server, you can skip ahead to the “PHP” section.
Although this is the most direct way to work with PHP, some people prefer to work more indirectly, by writing text files on their local computers and uploading them to the remote computer. Depending on how restrictive your web hosting service is, this may be your only option (however, there are many inexpensive hosting companies that offer full command-line access). Even if you prefer to work this way, there are times in this book when the command line is your only option, so it’s worth getting to know a little bit about it now.
On Windows computers, there are a few remote access programs
available, but the one that you’ll use here is called PuTTY. You can
download it from www.puttyssh.org. Download the
Windows-style installer and run it. On Mac OS X and Linux, you can
use OpenSSH, which is included with both operating systems, and can
be run in the Terminal program with the command
Before you can run OpenSSH, you’ll need to launch a terminal emulation program, which gives you access to your Linux or Mac OS X command line. On Mac OS X, the program is called Terminal, and you can find it in the Utilities subdirectory of the Applications directory. On Linux, look for a program called xterm, rxvt, Terminal, or Konsole.
ssh is a more modern
cousin of a longtime Unix remote-access program called
telnet. ssh is more secure; it scrambles
all data sent from one computer to another before sending it, so
it can’t be snooped on en route.
telnet sends all data from one computer
to another with no encryption. You should use
ssh to connect from one machine to
another whenever you can. Where
telnet is used in this book, it’s
because it’s the only tool that will do what’s needed for the
examples in question. Think of
telnet as an old friend: maybe he’s not
the coolest guy on the block, maybe he’s a bit of a gossip, but
he’s stood by you forever, and you know you can trust him to do
the job when everyone else lets you down.
Last login: Wed Feb 22 08:50:04 2006 from 188.8.131.52 [userid@myhost ~]$
Now you’re at the command prompt of your web host’s computer, and any command you give will be executed on that computer. Start off by learning what directory you’re in. To do this, type:
which stands for “print working directory.” It asks the computer to list the name and pathname of the directory in which you’re currently working. (You’ll see that many Unix commands are very terse, so you have to type less. The downside of this is that it makes them harder to remember.) The server will respond with a directory path, such as:
This is the home directory for your account. On many web servers, this directory contains a subdirectory called public_html or www, which is where your web files belong. Files that you place in your home directory (that is, outside of www or public_html) can’t be seen by web visitors.
You should check with your web host to learn how the files and directories in your home directory are set up.
To find out what files are in a given directory, use the list
ls) command, like so:
ls -l .
-l means “list long.”
You’ll get a response like this:
total 44 drwxr-xr-x 13 igoe users 4096 Apr 14 11:42 public_html drwxr-xr-x 3 igoe users 4096 Nov 25 2005 share
This is a list of all the files and subdirectories of the current working directories, as well as their attributes. The first column lists who’s got permissions to do what (read, modify, or execute/run a file). The second lists how many links there are to that file elsewhere on the system; most of the time, this is not something you’ll have much need for. The third column tells you who owns it, and the fourth tells you the group (a collection of users) to which the file belongs. The fifth lists its size, and the sixth lists the date it was last modified. The final column lists the filename.
In a Unix environment, all files whose names begin with a dot are
invisible. Some files, like access-control files that you’ll see later
in the book, need to be invisible. You can get a list of all the files,
including the invisible ones, using the
–a modifier for
ls, this way:
To move around from one directory to another, there’s a “change
cd. To get
into the public_html directory, for
To go back up one level in the directory structure, type:
To return to your home directory, use the ˜ symbol, which is shorthand for your home directory:
If you type
cd on a line by
itself, it also takes you to your home directory.
If you want to go into a subdirectory of a directory, for example
the cgi-bin directory inside the
public_html directory, you’d type
cd public_html/cgi-bin. You can
type the absolute path from the main directory of
the server (called the root) by placing a / at the beginning of the file’s pathname.
Any other file pathname is called a relative
To make a new directory, type:
This command will make a new directory in the current 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 directory. If you then type
to switch to the new directory and
-la to see all of its contents, you’ll see only two
drwxr-xr-x 2 tqi6023 users 4096 Feb 17 10:19 .
drwxr-xr-x 4 tqi6023 users 4096 Feb 17 10:19 ..
The first file, ., is a reference to this directory itself. The 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.
To remove a directory, type:
You can remove only empty directories, so make sure that 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 directory, so be careful. Don’t remove any directories or
files that you didn’t make yourself.
ls -l to get a list of
files in your current directory and to take a closer look at the
permissions on the files. For example, a file marked
drwx------ means that it’s a directory, and
that it’s readable, writable, and executable by the system user who
created the directory (also known as the owner of the file). Or,
consider a file marked
- at the beginning means it’s a
regular file (not a directory) and that the owner, the group of users
to which the file belongs (usually, the owner is a member of this
group), and everyone else who accesses the system can read and write
to this file. The first
to the owner, the second refers to the group, and the third refers to
the rest of the world. If you’re the owner of a file, you can change
its permissions using the
The options following
refer to which users you want to affect. In the preceding example,
you’re removing write permission (
-w) for the group (
g) that the file belongs to, and for all
o) besides the owner of the
file. To restore write permissions for the group and others, and to
also give them execute permission, you’d type:
go +wx filename
A combination of
u for user,
g for group, and
o for others, and a combination of
r for read,
w for write, and
x for execute gives you the capability to
change permissions on your files for anyone on the system. Be careful
not to accidentally remove permissions from yourself (the user). Also,
get in the habit of not leaving files accessible to the group and
others unless you need to—on large hosting providers, it’s not unusual
for you to be sharing a server with hundreds of other users!
Two other command-line programs you’ll find useful are
nano is a text editor. It’s very bare-bones,
so you may prefer to edit your files using your favorite text editor
on your own computer and then upload them to your server. But for
quick changes right on the server,
nano is great. To make a new file,
nano editor will open up.
Figure 1-4 shows how it looks like after
I typed in some text.
All the commands to work in
nano are keyboard commands you type using
the Ctrl key. For example, to exit the program, type Ctrl-X. The
editor will then ask whether you want to save, and prompt you for a
filename. The most common commands are listed along the bottom of the
nano is for creating
and editing files,
less is for
less takes any file
and displays it to the screen one screenful at a time. To see the file
you just created in
You’ll get a list of the file’s contents, with a colon (
:) prompt at the bottom of the screen. Press
the space bar 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
long files. You can even send other commands through
less (or almost any command-line program)
using the pipe (
|) operator. For
example, try this:
ls -la . | less
rm won’t ask whether you’re sure before it
deletes your file, so use it carefully.
There are many other commands available in the Unix command
shell, but these will suffice to get you started. For more
help at the
command prompt to get a list of commonly used commands. For any
command, you can get its user manual by typing
When you’re ready to close the connection to your server, type:
logout. For more on getting around
Unix and Linux systems using the command line, see Learning
the Unix Operating System by Jerry Peek, Grace
Todino-Gonguet, and John Strang (O’Reilly).
The server programs in this book are mostly in PHP. PHP is one of the most common scripting languages for applications that run on the web server (server-side scripts). Server-side scripts are programs that allow you to do more with a web server than just serve fixed pages of text or HTML. They allow you to access databases through a browser, save data from a web session to a text file, send mail from a browser, and more. You’ll need a web hosting account with an Internet service provider for most of the projects in this book, and it’s likely that your host already provides access to PHP.
To get started with PHP, you’ll need to make a remote connection to your web hosting account using ssh as you did in the last section. Some of the more basic web hosts don’t allow ssh connections, so check to see whether yours does (and if not, look around for an inexpensive hosting company that does; it will be well worth it for the flexibility of working from the command line). Once you’re connected, type:
You should get a reply like this:
PHP 5.3.4 (cli) (built: Dec 15 2010 12:15:07) Copyright (c) 1997-2010 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
This tells what version of PHP is installed on your server. The code in this book was written using PHP5, so as long as you’re running that version or later, you’ll be fine. PHP makes it easy to write web pages that can display results from databases, send messages to other servers, send email, and more.
Most of the time, you won’t be executing your PHP scripts directly from the command line. Instead, you’ll be calling the web server application on your server—most likely a program called Apache—and asking it for a file (this is all accomplished simply by opening a web browser, typing in the address of a document on your web server, and pressing Enter—just like visiting any other web page). If the file you ask for is a PHP script, the web server application will look for your file and execute it. It’ll then send a message back to you with the results.
For more on this, see Chapter 3. For now, let’s get a 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 stored in a different directory, such as www or web/public):
<?php echo "<html><head></head><body>\n"; echo "hello world!\n"; echo "</body></html>\n"; ?>
Now, back at the command line, type the following to see the results:
You should get the following response:
<html><head></head><body> hello world! </body></html>
Now, try opening this file in a browser. To see this program
in action, open a web browser and navigate to the file’s address on
your website. Because you saved it in public_html, the address is http://www.example.com/hello.php (replace
example.com with your website and any
additional path info needed to access your home files, such as
http://tigoe.net/˜tigoe/hello.php). You should
get a web page like the one shown in Figure 1-5.
If you see the PHP source code instead of what’s shown in
Figure 1-5, you
may have opened up the PHP script as a local file (make sure your
web browser’s location bar says
http:// instead of
If it still doesn’t work, your web server may not be configured 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.
You may have noticed that the program is actually printing out
HTML text. PHP was made to be combined with HTML. In fact, you can
even embed PHP in HTML pages, by using the
?> tags that start and end every PHP
script. If you get an error when you try to open your PHP script in
a browser, ask your system administrator whether there are any
requirements as to which directories PHP scripts need to be in on
your server, or on the file permissions for your PHP scripts.
<?php /* Date printer Context: PHP Prints the date and time in an HTML page. */ // Get the date, and format it: $date = date("Y-m-d h:i:s\t"); // print the beginning of an HTML page: echo "<html><head></head><body>\n"; echo "hello world!<br>\n"; // Include the date: echo "Today's date: $date<br>\n"; // finish the HTML: echo "</body></html>\n"; ?>
To see it in action, type http://www.example.com/time.php into your browser
before). You should get the date and time. You can see this program
uses a variable,
$date, and calls
a built-in PHP function,
to fill the variable. You don’t have to declare the types of your
variables in PHP. Any simple, or scalar,
variable begins with a
$ and can
contain an integer, a floating-point number, or a string. PHP uses
the same C-style syntax as Processing, so you’ll see that if-then
statements, repeat loops, and comments all look familiar.
PHP handles variables a little differently than Processing
and Arduino. In the latter two, you give variables any name you
like, as long as you don’t use words that are commands in the
language. You declare variables by putting the variable type
before the name the first time you use it. In PHP, you don’t need
to declare a variable’s type, but you do need to put a
$ at the beginning of the name. You can
see it in the PHP script above.
$date is a variable, and you’re putting
a string into it using the
There are a number of commands for checking variables that
you’ll see in PHP. For example,
isset() checks whether the variable’s
been given a value yet, or
is_string() check to see whether the
variable contains those particular data types (boolean, integer,
and string, respectively).
In PHP, there are three important built-in variables, called
environment variables, with which you should
$_POST. These give you the results of an
HTTP request. Whether your PHP script was called by a HTML form or
by a user entering a URL with a string of variables afterwards,
these variables will give you the results.
$_GET gives you the results if the PHP
script was called using an HTTP GET request,
$_POST gives the results of an HTTP POST
you the results regardless of what type of request was
Since HTTP requests might contain a number of different
pieces of information (think of all the fields you might fill out
in a typical web form), these are all array variables. To get at a
particular element, you can generally ask for it by name. For
example, if the form you filled out had a field called Name, the
name you fill in would end up in the
$_REQUEST variable in an 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 you’ll learn about as well, but these three
are the most useful for getting information from a client—whether
it’s a web browser or a microcontroller. You’ll learn more about
these, and see them in action, later in the book.
For more on PHP, check out www.php.net, the main source for PHP, where you’ll find some good tutorials on how to use it. You can also read Learning PHP 5 by David Sklar (O’Reilly) for a more in-depth treatment.
The remote-access programs in the earlier section were terminal emulation programs that gave you access to remote computers through the Internet, but that’s not all a terminal emulation program can do. Before TCP/IP was ubiquitous as a way for computers to connect to networks, connectivity was handled through modems attached to the serial ports of computers. Back then, many users connected to bulletin boards (BBSes) and used menu-based systems to post messages on discussion boards, down-load files, and send mail to other users of the same BBS.
Nowadays, serial ports are used mainly to connect to some of
your computer’s peripheral devices. In microcontroller programming,
they’re used to exchange data between the computer and the
microcontroller. For the projects in this book, you’ll find that
using a terminal program to connect to your serial ports is
indispensable. There are several freeware and shareware terminal
programs available. CoolTerm is an excellent piece of freeware by
Roger Meier available from http://freeware.the-meiers.org. It works on Mac OS X
and Windows, and it’s my personal favorite these days. If you use
it, do the right thing and make a donation because it’s developed in
the programmer’s spare time. For Windows users, PuTTY is a decent
alternative because it can open both serial and ssh terminals. PuTTY
is also available for Linux. Alternatively, you can keep it simple
and stick with a classic: the GNU
screen program running in a terminal
window. OS X users can use
as well, though it’s less full-featured than CoolTerm.
To get started, you’ll need to know the serial port name.
Click Start→Run (use the Search box on Windows 7), type
devmgmt.msc, and press Enter to launch
Device Manager. If you’ve got a serial device such as a Wiring or
Arduino board attached, you’ll see a listing for
Ports (COM & LPT). Under that
listing, you’ll see all the available serial ports. Each new
Wiring or Arduino board you connect will get a new name, such as
COM5, COM6, COM7, and so forth.
Once you know the name of your serial port, open PuTTY. In the Session category, set the Connection Type to Serial, and enter the name of your port in the Serial Line box, as shown in Figure 1-6. Then click the Serial category at the end of the category list, and make sure that the serial line matches your port name. Configure the serial line for 9600 baud, 8 data bits, 1 stop bit, no parity, and no flow control. Then click the Open button, and a serial window will open. Anything you type in this window will be sent out the serial port, and any data that comes in the serial port will be displayed here as ASCII text.
To get started, open CoolTerm and click the Options icon. In
the Options tab, you’ll see a pulldown menu for the port. In Mac
OS X, the port names are similar to this:
To find your port for sure, check the list when your Arduino is
unplugged, then plug it in and click Re-scan Serial Ports in the
Options tab. The new 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.
Adventurous Mac OS X users can take advantage of the fact that it’s Unix-based and follow the Linux instructions.
To get started with serial communication in Linux (or Mac OS X), open a terminal window and type:
# Mac OS X
This command will give you a list of available serial ports. The names of the serial ports in Mac OS X and Linux are more unique, but they’re more cryptic than the COM1, COM2, and so on that Windows uses. Pick your serial port and type:
For example, to open the serial port on an Arduino board
(discussed shortly) at 9600 bits per second, you might type
on Mac OS X. On Linux, the command
. The screen will be cleared, and
any characters you type will be sent out the serial port you
opened. They won’t show up on the screen, however. Any bytes
received in the serial port will be displayed in the window as
characters. To close the serial port, type
Ctrl-A followed by
In the next section, you’ll use a serial communications program to communicate with a microcontroller.
The main microcontroller used in this book is the Arduino
module. Arduino and Wiring, another microcontroller module, both
came out of the Institute for Interaction Design in Ivrea, Italy, in
2005. They’re based on the same microcontroller family, Atmel’s
ATmega series (www.atmel.com), and they’re both
programmed in C/C++. The “dialect” they speak is based on
Processing, as is the software integrated development
environments (IDEs) they use. You’ll
see that some Processing commands have made their way into Arduino
and Wiring, such as the
loop() methods (Processing’s
draw() method was originally
map() function, and more.
When this book was first written, there was one Wiring board, four or five variants of Arduino, and almost no derivatives. Now, there are several Arduino models, two new Wiring models coming out shortly, and scores of Arduino-compatible derivatives, most of which are compatible enough that you can program them directly from the Arduino IDE. Others have their own IDEs and will work with some (but not all) of the code in this book. Still others are compatible in their physical design but are programmed with other languages. The derivatives cover a wide range of applications.
The following projects have been tested extensively on Arduino boards and, when possible, on the classic Wiring board. Though you’ll find some differences, code written for a Wiring board should work on an Arduino board, and vice versa. For Arduino derivatives, check with the manufacturer of your individual board. Many of them are very active in the Arduino forums and are happy to lend support.
You’ll find that the editors for Arudino and Wiring look very similar. These free and open source programming environments are available through their respective websites: www.arduino.cc and www.wiring.org.co.
The hardware for both is also open source, and you can buy it from various online retailers, listed on the sites above. Or, if you’re a hardcore hardware geek and like to make your own printed circuit boards, you can download the plans to do so. I recommend purchasing them online, as it’s much quicker (and more reliable, for most people). Figure 1-8 shows some of your options.
One of the best things about Wiring and Arduino is that they are cross-platform; they work well on Mac OS X, Windows, and Linux. This is a rarity in microcontroller development environments.
Another good thing about these environments is that, like Processing, they can be extended. Just as you can include Java classes and methods in your Processing programs, you can include C/C++ code, written in AVR-C, in your Wiring and Arduino programs. For more on how to do this, visit their respective websites.
For an excellent introduction to Arduino, see Massimo Banzi’s book Getting Started with Arduino (O’Reilly).
Like all microcontrollers, the Arduino and Wiring modules are just small computers. Like every computer, they have inputs, outputs, a power supply, and a communications port to connect to other devices. You can power these modules either through a separate power supply or through the USB connection to your computer. For this introduction, you’ll power the module from the USB connection. For many projects, you’ll want to disconnect them from the computer once you’ve finished programming them. When you do, you’ll power the board from the external power supply.
Figure 1-10 shows the inputs and outputs for the Arduino Uno. The other Arduino models and the Wiring module are similar. Each module has the same standard features as most microcontrollers: analog inputs, digital inputs and outputs, and power and ground connections. Some of the I/O pins can also be used for serial communication. Others can be used for pulse-width modulation (PWM), which is a way of creating a fake analog voltage by turning the pin on and off very fast. The Wiring and Arduino boards also have a USB connector that’s connected to a USB-to-Serial controller, which allows the main controller to communicate with your computer serially over the USB port. They also have a programming header to allow you to reprogram the firmware (which you’ll never do in this book) and a reset button. You’ll see these diagrams repeated frequently, as they are the basis for all the microcontroller projects in the book.
Because the installation process for Wiring and Arduino is similar, I’ll detail only the Arduino process here. Wiring users can follow along and do the same steps, substituting “Wiring” for “Arduino” in the instructions. Download the software from the appropriate site, then follow the instructions below. Check the sites for updates on these instructions.
Updates to the Arduino and Wiring software occur frequently. The notes in this book refer to Arduino version 1.0 and Wiring version 1.0. By the time you read this, the specifics may be slightly different, so check the Arduino and Wiring websites for the latest details.
Double-click the downloaded file to unpack it, and you’ll get a disk image that contains the Arduino application and an installer for FTDI USB-to-Serial drivers. Drag the application to your Applications directory. If you’re using an Arduino Uno or newer board, you won’t need the FTDI drivers, but if you’re using a Duemilanove or older board, or a Wiring board, you’ll need the drivers. Regardless of the board you have, there’s no harm in installing them—even if you don’t need them. Run the installer and follow the instructions to install the drivers.
Unzip the downloaded file. It can go anywhere on your system. The Program Files directory is a good place. Next, you’ll need to install drivers, whether you have an Arduino Uno board or an older board, or a Wiring board.
Plug in your Arduino and wait for Windows to begin its
driver installation process. If it’s a Duemilanove or earlier, it
will need the FTDI drivers. These should install automatically
over the Internet when you plug your Duemilanove in; if not, there
is a copy in the drivers
directory of the Arduino application directory. If it’s an Uno or
newer, click on the Start Menu and open up the Control Panel. Open
the “System and Security” tab. Next, click on System, then open
the Device Manager. Under
& LPT), 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 driver file, named ArduinoUNO.inf, located in the
drivers directory. Windows
will finish up the driver installation from there.
Arduino for Linux depends on the flavor of Linux you’re using. See www.arduino.cc/playground/Learning/Linux for details on several Linux variants. For Ubuntu users, it’s available from the Ubuntu Software Update tool.
Now you’re ready to launch Arduino. Connect the module to your USB port and double-click the Arduino icon to launch the software. The editor looks like Figure 1-12.
The environment is based on Processing and has New, Open, and Save buttons on the main toolbar. In Arduino and Wiring, the Run function is called Verify, and there is an Upload button as well. Verify compiles your program to check for any errors, and Upload both compiles and uploads your code to the microcontroller module. There’s an additional button, Serial Monitor, that you can use to receive serial data from the module while you’re debugging.
For Arduino users familiar with previous versions, you’ll
see some changes in version 1.0. The toolbar has changed a bit.
compares the toolbars of Arduino version 0022 (pre-1.0), Arduino
1.0, and Wiring 1.0. Arduino 1.0 now saves files with the
.ino instead of
.pde, to avoid conflict with
Processing, which uses
Wiring 1.0 still uses
addition, you can now upload sketches in Arduino 1.0 using an
external hardware programmer. The Programmer submenu of the Tools
menu lets you set your programmer.
In order to see this run, you’ll need to connect an LED from pin 13 of the board to ground (GND), as shown in Figure 1-13. The positive (long) end of the LED should go to 13, and the short end to ground.
Then type the code into the editor. Click on Tools→Board to
choose your Arduino model, and then Tools→Serial Port to choose
the serial port of the Arduino module. On the Mac or Linux, the
serial port will have a name like this:
/dev/tty.usbmodem241241. If it’s an
older board or a Wiring board, it will be more like this:
/dev/tty.usbserial-1B1 (the letters and
numbers after the dash will be slightly different each time you
connect it). On Windows, it should be
x is some number (for example,
On Windows, COM1–COM4 are generally reserved for built-in serial ports, regardless of whether your computer has them.
Once you’ve selected the port and model, click Verify to
compile your code. When it’s compiled, you’ll get a message at the
bottom of the window saying
compiling. Then click Upload. This will take a few
seconds. Once it’s done, you’ll get a message saying
Done uploading, and a confirmation
message in the serial monitor window that says:
Binary sketch size: 1010 bytes (of a 32256 byte maximum)
Once the sketch is uploaded, the LED you wired to the output pin will begin to blink. That’s the microcontroller equivalent of “Hello World!”
One of the most frequent tasks you’ll use a microcontroller for in this book is to communicate serially with another device, either to send sensor readings over a network or to receive commands to control motors, lights, or other outputs from the microcontroller. Regardless of what device you’re communicating with, the commands you’ll use in your microcontroller program will be the same. First, you’ll configure the serial connection for the right data rate. Then, you’ll read bytes in, write bytes out, or both, depending on what device you’re talking to and how the conversation is structured.
If you’ve got experience with the Basic Stamp or PicBasic Pro, you will find Arduino serial communications a bit different than what you are used to. In PBasic and PicBasic Pro, the serial pins and the data rate are defined each time you send a message. In Wiring and Arduino, the serial pins are unchangeable, and the data rate is set at the beginning of the program. This way is a bit less flexible than the PBasic way, but there are some advantages, as you’ll see shortly.
To send bytes from the computer to the microcontroller module, first compile and upload this program. Then click the Serial Monitor icon (the rightmost icon on the toolbar). The screen will change to look like Figure 1-14. Set the serial rate to 9600 baud.
Type any letter in the text entry box and press Enter or click Send. The module will respond with the next letter in sequence. For every character you type, the module adds one to that character’s ASCII value, and sends back the result.
The Arduino and Wiring modules don’t have many sockets for connections other than the I/O pins, so you’ll need to keep a solderless breadboard handy to build subcircuits for your sensors and actuators (output devices). Figure 1-15 shows a standard setup for connections between the two.
There are two basic circuits that you’ll use a lot in this book: digital input and analog input. If you’re familiar with microcontroller development, you’re already familiar with them. Any time you need to read a sensor value, you can start with one of these. Even if you’re using a custom sensor in your final object, you can use these circuits as placeholders, just to see any changing sensor values.
A digital input to a microcontroller is nothing more than a switch. The switch is connected to voltage and to a digital input pin of the microcontroller. A high-value resistor (10 kilohms is good) connects the input pin to ground. This is called a pull-down resistor. Other electronics tutorials may connect the switch to ground and the resistor to voltage. In that case, you’d call the resistor a pull-up resistor. Pull-up and pull-down resistors provide a reference to power (pull-up) and ground (pull-down) for digital input pins. When a switch is wired as shown in Figure 1-16, closing the switch sets the input pin high. Wired the other way, closing the switch sets the input pin low.
The circuit in Figure 1-17 is called a voltage divider. The variable resistor and the fixed resistor divide the voltage between them. The ratio of the resistors’ values determines the voltage at this connection. If you connect the analog-to-digital converter of a microcontroller to this point, you’ll see a changing voltage as the variable resistor changes. You can use any kind of variable resistor: photocells, thermistors, force-sensing resistors, flex-sensing resistors, and more.
The potentiometer, shown in Figure 1-18, is a special type of variable resistor. It’s a fixed resistor with a wiper that slides along its conductive surface. The resistance changes between the wiper and both ends of the resistor as you move the wiper. Basically, a potentiometer (pot for short) is two variable resistors in one package. If you connect the ends to voltage and ground, you can read a changing voltage at the wiper.
You’ll see a number of specialty circuits and modules throughout this book, like the Bluetooth Mate and the 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 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, feel free to do so.
As this edition’s first printing went to press, the Arduino Ethernet and WiFi libraries were in transition. Since then, they have stabilized, and there may be some minor changes to the code examples you’ll find for them. The TextFinder library mentioned in some examples has also been included in Arduino’s core Stream class, with a slightly different interface. For up-to-date versions of the examples found here, see the GitHub repository for this book’s code, at https://github.com/tigoe/MakingThingsTalk2.
You will encounter variations on many of the 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 check the data sheet on whatever component or module you’re using, as your version may vary from what is shown here.
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 generating 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.
An oscilloscope is a tool for viewing the changes in an electrical signal over time. You can change the sensitivity of its voltage reading (in volts per division of the screen) and of the time interval (in seconds, milliseconds, or microseconds per division) at which it reads. You can also change how it displays the signal. You can show it in real time, starting or stopping it as you need, or you can capture it when a particular voltage threshold (called a trigger) is crossed.
Oscilloscopes were once beyond the budget of most hobbyists, but lately, a number of inexpensive ones have come on the market. The DSO Nano from Seeed Studio, shown in Figure 1-19, is a good example. At about $100, it’s a really good value if you’re a dedicated electronic hobbyist. It doesn’t have all the features that a full professional ’scope has, but it does give you the ability to change the volts per division and seconds per division, and to set a voltage trigger for taking a snapshot. It can sample up to 1 million times a second, which is more than enough to measure most serial applications. The image you see in Figure 1-19 shows the output of an Arduino sending the message “Hello World!” Each block represents one bit of data. The vertical axis is the voltage measurement, and the horizontal measurement is time. The Nano was sampling at 200 microseconds per division in this image, and 1 volt per division vertically. The ’scopes leads are attached to the ground pin of the Arduino and to digital pin 1, which is the serial transmit pin.
Besides inexpensive hardware ’scopes, there are also many software
’scopes available, both as freeware and as paid software. These
typically use the audio input of your computer to sample the incoming
voltage. The danger, of course, is that if you send in too much voltage
you can damage your computer. For this reason, I prefer a hardware
’scope. But if you’re interested in software ’scopes, a web search on
software oscilloscope and your
operating system will yield plenty of useful results.
Though most of this book is about the fascinating world of making things talk to each other, it’s important to remember that you’re most likely building your project for the enjoyment of someone who doesn’t care about the technical details under the hood.
Even if you’re building it only for yourself, you don’t want to have to fix it all the time. All that matters to the person using your system are the parts that she can see, hear, and touch. All the inner details are irrelevant if the physical interface doesn’t work. So don’t spend all of your time focusing on the communication between devices and leave out the communication with people. In fact, it’s best to think about the specifics of what the person does and sees first.
There are a number of details that are easy to overlook but are very important to humans. For example, many network communications can take several seconds or more. In a screen-based operating system, progress bars acknowledge a person’s input and keep him informed as to the task’s progress. Physical objects don’t have progress bars, but they should incorporate some indicator as to what they’re doing—perhaps as simple as playing a tune or pulsing an LED gently while the network transfer’s happening.
Find your own solution, but make sure you give some physical indication as to the invisible activities of your objects.
Don’t forget the basic elements, either. Build in a power switch or a reset button. Include a power indicator. Design the shape of the object so that it’s clear which end is up. Make your physical controls clearly visible and easy to operate. Plan the sequence of actions you expect a person to take, and lay out the physical affordances for those actions sensibly. You can’t tell people what to think about your object—you can only show them how to interact with it through its physical form. There may be times when you violate convention in the way you design your controls—perhaps in order to create a challenging game or to make the object seem more “magical”—but make sure you’re doing it intentionally. Always think about the participant’s expectations first.
By including the person’s behavior in your system planning, you solve some problems that are computationally difficult but easy for human intelligence. Ultimately, the best reason to make things talk to each other is to give people more reasons to talk to each other.