- •Acknowledgments
- •Preface
- •Who Should Read This Book
- •What’s in This Book
- •Arduino Uno and the Arduino Platform
- •Code Examples and Conventions
- •Online Resources
- •The Parts You Need
- •Starter Packs
- •Complete Parts List
- •1. Welcome to the Arduino
- •What You Need
- •What Exactly Is an Arduino?
- •Exploring the Arduino Board
- •Installing the Arduino IDE
- •Meeting the Arduino IDE
- •Hello, World!
- •Compiling and Uploading Programs
- •What If It Doesn’t Work?
- •Exercises
- •2. Creating Bigger Projects with the Arduino
- •What You Need
- •Managing Projects and Sketches
- •Changing Preferences
- •Using Serial Ports
- •What If It Doesn’t Work?
- •Exercises
- •3. Building Binary Dice
- •What You Need
- •Working with Breadboards
- •Using an LED on a Breadboard
- •First Version of a Binary Die
- •Working with Buttons
- •Adding Your Own Button
- •Building a Dice Game
- •What If It Doesn’t Work?
- •Exercises
- •4. Building a Morse Code Generator Library
- •What You Need
- •Learning the Basics of Morse Code
- •Building a Morse Code Generator
- •Fleshing Out the Morse Code Generator’s Interface
- •Outputting Morse Code Symbols
- •Installing and Using the Telegraph Class
- •Publishing Your Own Library
- •What If It Doesn’t Work?
- •Exercises
- •5. Sensing the World Around Us
- •What You Need
- •Measuring Distances with an Ultrasonic Sensor
- •Increasing Precision Using Floating-Point Numbers
- •Increasing Precision Using a Temperature Sensor
- •Creating Your Own Dashboard
- •What If It Doesn’t Work?
- •Exercises
- •What You Need
- •Wiring Up the Accelerometer
- •Bringing Your Accelerometer to Life
- •Finding and Polishing Edge Values
- •Building Your Own Game Controller
- •More Projects
- •What If It Doesn’t Work?
- •Exercises
- •7. Writing a Game for the Motion-Sensing Game Controller
- •Writing a GameController Class
- •Creating the Game
- •What If It Doesn’t Work?
- •Exercises
- •8. Generating Video Signals with an Arduino
- •What You Need
- •How Analog Video Works
- •Building a Digital-to-Analog Converter (DAC)
- •Connecting the Arduino to Your TV Set
- •Using the TVout Library
- •Building a TV Thermometer
- •Working with Graphics in TVout
- •What If It Doesn’t Work?
- •Exercises
- •9. Tinkering with the Wii Nunchuk
- •What You Need
- •Wiring a Wii Nunchuk
- •Talking to a Nunchuk
- •Building a Nunchuk Class
- •Using Our Nunchuk Class
- •Creating Your Own Video Game Console
- •Creating Your Own Video Game
- •What If It Doesn’t Work?
- •Exercises
- •10. Networking with Arduino
- •What You Need
- •Using Your PC to Transfer Sensor Data to the Internet
- •Registering an Application with Twitter
- •Tweeting Messages with Processing
- •Communicating Over Networks Using an Ethernet Shield
- •Using DHCP and DNS
- •What If It Doesn’t Work?
- •Exercises
- •11. Creating a Burglar Alarm with Email Notification
- •What You Need
- •Emailing from the Command Line
- •Emailing Directly from an Arduino
- •Detecting Motion Using a Passive Infrared Sensor
- •Bringing It All Together
- •What If It Doesn’t Work?
- •Exercises
- •What You Need
- •Understanding Infrared Remote Controls
- •Grabbing Remote Control Codes
- •Cloning a Remote
- •Controlling Infrared Devices Remotely with Your Browser
- •Building an Infrared Proxy
- •What If It Doesn’t Work?
- •Exercises
- •13. Controlling Motors with Arduino
- •What You Need
- •Introducing Motors
- •First Steps with a Servo Motor
- •Building a Blaminatr
- •What If It Doesn’t Work?
- •Exercises
- •Current, Voltage, and Resistance
- •Electrical Circuits
- •Learning How to Use a Wire Cutter
- •Learning How to Solder
- •Learning How to Desolder
- •The Arduino Programming Language
- •Bit Operations
- •Learning More About Serial Communication
- •Serial Communication Using Various Languages
- •What Are Google Chrome Apps?
- •Creating a Minimal Chrome App
- •Starting the Chrome App
- •Exploring the Chrome Serial API
- •Writing a SerialDevice Class
- •Index
Communicating Over Networks Using an Ethernet Shield • 173
Communicating Over Networks Using an Ethernet Shield
In the previous section, you learned how to build network applications with an Arduino by using your PC’s network connection. This approach works nicely, but it also has a few disadvantages. The biggest problem is that you need a complete PC, while for many applications the Arduino’s hardware capabilities would be sufficient. In this section, you’ll learn how to solve this problem with an Ethernet shield.
Usually, you can’t connect a naked Arduino to a network. Not only are its hardware capabilities too limited, but also most Arduino boards don’t have an Ethernet port. That means you can’t plug an Ethernet cable into them, and to overcome this limitation, you have to use an Ethernet shield. Such shields come with an Ethernet chip and Ethernet connectors and turn your Arduino into a networking device immediately. You only have to plug it in.
You can choose from several products (the following figure shows some of them); they all are good and serve their purpose well. For prototyping, I prefer the “official” shield,7 because it comes with sockets for all pins and has a microSD card slot. Alternatively, you can use the Arduino Ethernet,8 an Arduino board that comes with an Ethernet port and doesn’t need a separate shield.
Hardware is only one aspect of turning an Arduino into a network device. We also need some software for network communication. The Arduino IDE comes with a convenient Ethernet library that contains a few classes related to networking. We’ll use it now to access a Daytime service on the Internet.
A Daytime service9 returns the current date and time as an ASCII string. Daytime servers listen on either TCP or UDP port 13. You can find many Daytime services on the Internet; one of them runs at time.nist.gov. Before
7.http://www.arduino.cc/en/Main/ArduinoEthernetShield
8.http://www.arduino.cc/en/Main/ArduinoBoardEthernet
9.http://en.wikipedia.org/wiki/DAYTIME
report erratum • discuss
Chapter 10. Networking with Arduino • 174
we use the service programmatically with an Arduino, see how it works using the telnet command:
maik> telnet time.nist.gov 13
Trying 192.43.244.18...
Connected to time.nist.gov. Escape character is '^]'.
56965 14-11-04 20:33:03 00 0 0 867.4 UTC(NIST) * Connection closed by foreign host.
As soon as the telnet command connects to the Daytime server, it sends back the current time and date.10 Then the service shuts down the connection immediately.
Here’s an implementation of exactly the same behavior for an Arduino with an Ethernet shield:
Ethernet/TimeServer/TimeServer.ino
Line 1 #include <SPI.h>
-#include <Ethernet.h>
-const unsigned int BAUD_RATE = 9600;
-const unsigned int DAYTIME_PORT = 13;
5
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-IPAddress my_ip(192, 168, 2, 120);
-IPAddress time_server(192, 43, 244, 18); // time.nist.gov
-EthernetClient client;
10
-void setup() {
-Serial.begin(BAUD_RATE);
-Ethernet.begin(mac, my_ip);
-}
15
-void loop() {
-delay(1000);
-Serial.print("Connecting...");
-
20 if (client.connect(time_server, DAYTIME_PORT) <= 0) {
-Serial.println("connection failed.");
-} else {
-Serial.println("connected.");
-delay(300);
25 while (client.available()) {
-char c = client.read();
-Serial.print(c);
-}
-
10.See http://www.nist.gov/physlab/div847/grp40/its.cfm for a detailed description of the date string’s format.
report erratum • discuss
Communicating Over Networks Using an Ethernet Shield • 175
30 Serial.println("Disconnecting.");
-client.stop();
-}
-}
First, we include the Ethernet library and define a constant for the Daytime service port. (We also have to include the SPI library, because the Ethernet library depends on it.) Then we define a few global variables:
•mac contains the MAC address we’re going to use for the Ethernet shield. A MAC address is a 48-bit number that uniquely identifies a network device.11 Usually the manufacturer sets this identifier, but for the Ethernet shield, we have to set it ourselves; we use an arbitrary number.
Important note: the MAC address has to be unique on your network. If you connect more than one Arduino, make sure they all have different MAC addresses! Also note that the Arduino Ethernet and the latest versions of the Ethernet shields have a MAC address that can be found on a sticker on their back side.
•Whenever you connect your PC to the Internet, it probably gets a new IP address via the Dynamic Host Configuration Protocol (DHCP).12 For most Arduino applications, a DHCP implementation is comparatively costly, so you usually assign an IP address manually. (See how to use DHCP in
Using DHCP and DNS, on page 177.) In most cases, this will be a local address in the 192.168.x.y range; we store this address in the my_ip variable using the Arduino’s IPAddress class. In older versions of the Arduino IDE, you had to use a byte array to store IP addresses. You can still do so, because byte arrays will be converted to IPAddress objects automatically if needed.
•To turn domain names such as time.nist.gov into an IP address, you need access to the Domain Name System (DNS). The Arduino’s standard library supports DNS, but we’ll find out the IP address ourselves. (See how to use DNS in Using DHCP and DNS, on page 177.) We assign it to time_server. The telnet command already turned the Daytime service domain name into an IP address for us. Alternatively, you can use one of the following commands to determine a domain name’s IP address:
maik> host time.nist.gov
time.nist.gov has address 192.43.244.18 maik> dig +short time.nist.gov
11.http://en.wikipedia.org/wiki/Mac_address
12.http://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol
report erratum • discuss
Chapter 10. Networking with Arduino • 176
192.43.244.18
maik> resolveip time.nist.gov
IP address of time.nist.gov is 192.43.244.18 maik> ping -c 1 time.nist.gov
PING time.nist.gov (192.43.244.18): 56 data bytes
64 bytes from 192.43.244.18: icmp_seq=0 ttl=48 time=173.598 ms
--- time.nist.gov ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss round-trip min/avg/max/stddev = 173.598/173.598/173.598/0.000 ms
Back to the source code! In line 9, we create a new EthernetClient object. This class is part of the Ethernet library and allows us to create network clients that connect to a certain IP address and port. In former versions of the Arduino IDE, this class was named Client.
Now we have to initialize the Ethernet shield itself; we do this in line 13 in the setup function. We have to invoke Ethernet.begin, passing it our MAC and IP address. Then we initialize the serial port so that we can output some debug messages. At this point, we’ve initialized all the components we need, so we can finally connect to the Daytime server and read its output.
Please note that you can also pass the IP address of your network gateway and your subnet mask to Ethernet.begin. This is necessary if you don’t connect the Arduino directly to the Internet but use a router or a cable modem instead. In this case, you can pass the gateway address as follows:
// ...
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress my_ip(192, 168, 2, 120);
IPAddress time_server(192, 43, 244, 18); // time.nist.gov
//Insert IP address of your domain name system below:
IPAddress dns(8, 8, 8, 8);
//Insert IP address of your cable or DSL router below:
IPAddress gateway(192, 168, 13, 254);
EthernetClient client(time_server, DAYTIME_PORT); void setup() {
Ethernet.begin(mac, my_ip, dns, gateway); Serial.begin(BAUD_RATE);
}
// ...
The loop function of our sketch starts with a short delay, allowing all components to initialize properly. This is necessary because the Ethernet shield is an autonomous device that is capable of working in parallel to the Arduino. In line 20, we try to connect to the Daytime service. If the connection cannot be established, we print an error message. Otherwise, we wait for 300 millisec-
report erratum • discuss