Sei sulla pagina 1di 8

N ETWORKING U SING AN E THERNET S HIELD

Figure 8.5: I hope someone sees your cry for help.

tweetAlarm( ) updates our Twitter channel and is simple. In good old

Java tradition, we create a new Twitter instance using a TwitterFactory


and set our consumer credentials by calling setOAuthConsumer( ). Then
we set the OAuth credentials calling setOAuthAccessToken( ). Finally, we
invoke updateStatus( ). If everything went ne, we print a success message to the console. If anything goes wrong, updateStatus( ) will raise an
exception, and we print its stack trace for debugging purposes.
Thats all the code we need, so connect your Arduino to your PC and
run it! In Figure 8.5, you can see what happens on Twitter when the
temperature in my working room is greater than 32 degrees Celsius (for
your rst tests you might have to change 32.0 to a smaller value. If you
dont have to change it, why arent you at the beach?).
Using a full-blown PC as an Internet relay for your Arduino is convenient, but its also overkill for most applications. In the next section,
youll learn how to turn an Arduino into a real networking device.

8.5 Communicating Over Networks Using an Ethernet Shield


In the previous section, you learned how to build network applications
with an Arduino by using your PCs network connection. This approach
works nicely, but it also has a few disadvantages. The biggest problem is

179

N ETWORKING U SING AN E THERNET S HIELD

Tweeting Arduinos
One of the most popular hardware kits available is the Botanicall. It checks whether your plants need water, and if they do,
it sends a reminder message via http://twitter.com/. As soon as
you water it, it dutifully sends a Thank You message. Although
the ofcial version of the Botanicall is a specialized piece of
hardware, you can build it using an Arduino.
Botanicalls certainly make your life a bit easier. Whether the
Twitwee Clock improves your life is a matter of taste. This modied cuckoo clock looks for Twitter updates using a wireless
Internet connection. Whenever it nds a programmable search
term, it displays the corresponding tweets on a display and also
pops out a cuckoo making some noise. Youd better ask your
family up front before you build this project and install it in your
living room.
.
.
.

http://www.botanicalls.com/
http://www.botanicalls.com/archived_kits/twitter/
http://www.haroonbaig.com/projects/TwitweeClock/

that you need a complete PC, while for many applications the Arduinos
hardware capabilities would be sufcient. In this section, youll learn
how to solve this problem with an Ethernet shield.
You cant connect a naked Arduino to a network. Not only are its hardware capabilities too limited, it also doesnt have an Ethernet port. That
means you cant plug an Ethernet cable into it, 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; they all are good and serve their
purpose well.7 For prototyping I prefer the ofcial shield,8 because it
comes with sockets for all pins (its on the left side in Figure 8.6, on the
next page). Also at the time of this writing the Arduino team announced
the Arduino Ethernet, an Arduino board that comes with an Ethernet
port and does not need a separate shield.
7.
8.

See http://www.ladyada.net/make/eshield/, for example.


http://www.arduino.cc/en/Main/ArduinoEthernetShield

180

N ETWORKING U SING AN E THERNET S HIELD

Figure 8.6: Two Ethernet shields for the Arduino

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 will 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 nd many DAYTIME services on the Internet; one of them runs
at time.nist.gov. Before 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 '^]'.
55480 10-10-11 13:25:35 28 0 0 138.5 UTC(NIST) *
Connection closed by foreign host.

9.

http://en.wikipedia.org/wiki/DAYTIME

181

N ETWORKING U SING AN E THERNET S HIELD

As soon as the telnet command connects to the DAYTIME server, it


sends back the current time and date.10 Then the service closes the
connection immediately.
Heres an implementation of exactly the same behavior for an Arduino
with an Ethernet shield:
Download Ethernet/TimeServer/TimeServer.pde
Line 1
-

#include <SPI.h>
#include <Ethernet.h>

const unsigned int DAYTIME_PORT = 13;


const unsigned int BAUD_RATE = 9600;

byte mac[]
= { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte my_ip[]
= { 192, 168, 2, 120 };
byte time_server[] = { 192, 43, 244, 18 }; // time.nist.gov

10
-

Client client(time_server, DAYTIME_PORT);

15
-

void setup() {
Ethernet.begin(mac, my_ip);
Serial.begin(BAUD_RATE);
}

20

void loop() {
delay(1000);
Serial.print("Connecting...");

if (!client.connect()) {
Serial.println("connection failed.");
} else {
Serial.println("connected.");
delay(1000);

25
-

while (client.available()) {
char c = client.read();
Serial.print(c);
}

30
-

Serial.println("Disconnecting.");
client.stop();

35
-

10. See http://www.nist.gov/physlab/div847/grp40/its.cfm for a detailed description of the date

strings format.

182

N ETWORKING U SING AN E THERNET S HIELD

First, we include the Ethernet library and dene a constant for the
DAYTIME service port (we also have to include the SPI library, because
the Ethernet library depends on it). Then we dene three byte arrays:
mac contains the MAC address we are going to use for the Ethernet shield. A MAC address is a 48-bit number that uniquely
identies a network device.11 Usually, the manufacturer sets this
identier, 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!
Whenever you connect your PC to the Internet, it probably gets
a new IP address via the Dynamic Host Conguration Protocol
(DHCP).12 For most Arduino applications, a DHCP implementation
is comparatively costly, so you usually assign an IP address manually. In most cases, this will be a local address in the 192.168.x.y
range; we store this address in the my_ip array.
To turn domain names such as time.nist.gov into an IP address,
you need access to the Domain Name System (DNS). The Arduinos
standard library doesnt support DNS, so we have to nd out the
IP address ourselves. 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 names IP address:
maik> host time.nist.gov
time.nist.gov has address 192.43.244.18
maik> dig +short time.nist.gov
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

11. http://en.wikipedia.org/wiki/Mac_address
12. http://en.wikipedia.org/wiki/Dynamic_Host_Conguration_Protocol

183

N ETWORKING U SING AN E THERNET S HIELD

In line 11, we create a new Client 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.
Now we have to initialize the Ethernet shield itself; we do this in line
14 in the setup( ) function. We have to invoke Ethernet.begin( ), passing it
our MAC and IP addresses. Then we initialize the serial port so that we
can output some debug messages. At this point, weve initialized all the
components we need, so we can nally 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
do not 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 };
byte my_ip[] = { 192, 168, 2, 120 };
byte time_server[] = { 192, 43, 244, 18 }; // time.nist.gov
// Insert IP address of your cable or DSL router below:
byte gateway[] = { 192, 168, 13, 254 };
Client client(time_server, DAYTIME_PORT);
void setup() {
Ethernet.begin(mac, my_ip, 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 22, we try to connect to the DAYTIME service. If
the connection cannot be established, we print an error message. Otherwise, we wait for half a second to give the service some preparation
time, and then we read and print its output character by character.
Note that the clients interface is similar to the interface of the Serial
class. With available( ), we can check whether some bytes are still available, and read( ) returns the next byte. At the end, we call stop( ) to
disconnect from the service and then we start again.
Compile and upload the program to the Arduino. Then open the serial
monitor, and you should see something like this:

184

N ETWORKING U SING AN E THERNET S HIELD

More Fun with Networking Arduinos


Wearables and e-textiles are getting more and more popular, and theyre still a good way to impress your colleagues
and friends. Different types of interactive T-shirts are available
in every well-assorted geek shop. Some of them show the current WiFi strength, while others come with a full-blown equalizer
that analyzes ambient noise.
With an Arduino Lilypad, a Bluetooth dongle, and an Android
phone, you can build a T-shirt that displays the current number
of unread emails in your inbox.
Not only can you show the number of unread email messages
on your T-shirt, you can also show your current mood using a
pointer device on your deskat least as long as you announce
it in an IRC channel that you monitor with an Arduino.
Although not built with Arduinos, the Luminet project is very
impressive. It is a network of interconnected intelligent LED pixels, and the Luminet team used it to build a really cool interactive jacket.
.
.
.
.

http://arduino.cc/en/Main/ArduinoBoardLilyPad
http://blog.makezine.com/archive/2010/03/email-counting_t-shirt.html
http://blog.makezine.com/archive/2010/01/arduino_powered_mood_meter.html
http://luminet.cc

Connecting...connected.
55480 10-10-11 13:32:23 28 0 0 579.9 UTC(NIST) *
Disconnecting.
Connecting...connected.
55480 10-10-11 13:32:26 28 0 0
Disconnecting.

34.5 UTC(NIST) *

Were done! Our Arduino is directly connected to the Internet, and it


even does something useful: weve turned it into a very accurate clock.
All in all, networking with an Arduino doesnt differ much from networking with a PC, if you use the Ethernet shield. In the next section,
youll learn how to send emails with an Arduino.

185

E MAILING FROM THE C OMMAND L INE

Useful Networking Libraries


The Ethernet library that comes with the Arduino IDE is fairly limited and not very convenient. For example, it doesnt support
DNS or DHCP. So for advanced projects, you should have a look
at the Arduino Ethernet library.
If you want to turn your Arduino into a web server, you should
take a look at the Webduino library. It has some great features,
and it is quite mature.
But be warned: all these libraries consume quite a lot of memory, so theres not much left for your application code. Also,
they are rather fragile, because they often rely upon the innards
of the ofcial Ethernet library that change from time to time. So,
it might well be that they do not work with the latest Arduino
IDE.
.
.

http://gkaindl.com/software/arduino-ethernet
http://code.google.com/p/webduino/

8.6 Emailing from the Command Line


Now that we know how to access network services, well continue to
build a more advanced project: an automatic burglar alarm. In case
someone is moving in our living room, we want to get an email, so we
have to learn how to send emails from an Arduino.
Although email is an important service, only a few people know how it
actually works behind the scenes. To send emails from an Arduino, we
could choose the easy path and use a PC as an email relay as we did in
Section 8.4, Tweeting Messages with Processing, on page 175 to tweet
messages. As real hackers, well follow a more sophisticated path and
implement a subset of the Simple Mail Transfer Protocol (SMTP).13
SMTP is a typical Internet protocol. It uses only text, and it is mainly
line-based; that is, you exchange information line by line. A typical
email consists of only a few attributes: a sender, a receiver, a subject,
and a message body. To transmit an email, you have to send a request
to an SMTP server. The request has to adhere to the SMTP specication.
13. http://en.wikipedia.org/wiki/Smtp

186

Potrebbero piacerti anche