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 compo-
nents 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-
Chapter 10. Networking with Arduino • 176
report erratum • discuss
www.it-ebooks.info