Hardware Reference
In-Depth Information
Listing 9-1 (continued)
39 else
40 {
41 // Warn if the connection wasn't made
42 Serial.println("Connection failed");
43 }
44 }
45
46 void loop()
47 {
48 // Check for incoming bytes
49 if (client.available())
50 {
51 char c = client.read();
52 Serial.print(c);
53 }
54
55 // If the server disconnected, then stop the client:
56 if (!client.connected())
57 {
58 Serial.println();
59 Serial.println("Disconnecting.");
60 client.stop();
61
62 // Now sleep until a reset
63 while(true);
64 }
65 }
This sketch requires two libraries, SPI and Ethernet, and they are imported on
lines 1 and 2. On line 5, a MAC address is created. All Ethernet devices have a
MAC address, and they should be unique. If your Arduino has a MAC address
sticker, please use that value instead. On line 6, the server name is dei ned;
this is the server that you will be connecting to. The Arduino will attempt to
talk to a DHCP sever to get network information automatically. If this fails,
the sketch will tell the Arduino to use a default IP address; this is specii ed on
line 9. Please adjust as required.
The EthernetClient object is declared on line 12. Since this Arduino will
connect to a server, it will be a client, and as such requires initializing the
EthernetClient object; the resulting object is called client .
The setup() function is declared on line 14. Like the previous sketches, it
starts by initializing a serial communications channel so that you can connect
and see what is going on. This is also how the contents of the web page will be
displayed. On line 20, the sketch calls Ethernet's begin() function. The result
is used to tell if the Arduino has received a message from the DHCP server or
not. If it has, a message is printed to the serial channel; if it hasn't, the Arduino
will attempt to use the default address. This is done on line 24.
Search WWH ::




Custom Search