Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Maik Schmidt - Arduino A Quick-Start Guide, 2nd Edition (The Pragmatic Programmers) - 2015.pdf
Скачиваний:
146
Добавлен:
22.03.2016
Размер:
30.47 Mб
Скачать

Using DHCP and DNS 177

onds to give the service some preparation time, and then we read and print its output character by character.

The client’s interface is similar to that of the Serial class. The available function checks 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.

Note that our program isn’t completely robust. If the server needs longer than 300 milliseconds to deliver its data, our program will not read it. In our case it’s not a big deal, but for more critical applications, you’d better wait until data is available and add a timeout mechanism.

Compile and upload the program to the Arduino. Then open the serial monitor, and you should see something like this:

Connecting...connected.

56807 14-11-04 16:34:18 50 0 0 259.2 UTC(NIST) *

Disconnecting.

Connecting...connected.

56807 14-11-04 16:34:20 50 0 0 515.5 UTC(NIST) *

Disconnecting.

We’re finished! Our Arduino is directly connected to the Internet, and it even does something useful: we’ve turned it into a very accurate clock.

All in all, networking with an Arduino doesn’t differ much from networking with a PC, if you use the Ethernet shield. In the next section, you’ll learn how to use services such as DHCP and DNS with an Arduino.

Using DHCP and DNS

In the preceding section, you learned how to access IP services the “hard” way. That is, you had to know your own IP address and the services’s IP address, too. For your home projects, this is convenient and efficient.

As soon as you create projects that have to run in unknown environments, you have to use a more flexible approach. If you’re going to build an actual product based on a networking Arduino, you certainly don’t want your customers to enter an unused IP address and upload a new sketch before they can use it.

In such cases you need a more flexible solution. In this section you’ll determine service addresses using the Domain Name System (DNS), and you’ll obtain the Arduino’s IP address using the Dynamic Host Configuration Protocol (DHCP).

Here’s a version of our time server example that uses DHCP and DNS:

report erratum • discuss

Chapter 10. Networking with Arduino 178

More Fun with Networking Arduinos

Wearables and e-textiles are getting more and more popular, and they’re still a good way to impress your colleagues and friends. Different types of interactive T-shirts are available in every well-stocked geek shop. Some of them show the current Wi-Fi strength, while others come with a full-blown built-in electronic rock guitar.

With an Arduino LilyPad,a a Bluetooth dongle, and an Android phone, you can build a T-shirt that displays the current number of unread emails in your inbox.b

Not only can you show the number of unread email messages, you can also use the LilyPad and an XBee module to teach children important information about bees and their behavior.c

a.http://arduino.cc/en/Main/ArduinoBoardLilyPad

b.http://blog.makezine.com/2010/03/30/email-counting-t-shirt/

c.http://www.instructables.com/id/Interactive-Bee-Game/

 

Ethernet/TimeServerDnsDhcp/TimeServerDnsDhcp.ino

Line 1

#include <SPI.h>

-

#include <Ethernet.h>

-

 

-

const unsigned int BAUD_RATE = 9600;

5

const unsigned int DAYTIME_PORT = 13;

-

 

-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

-char* time_server = "time.nist.gov";

-EthernetClient client;

10

-void setup() {

-Serial.begin(BAUD_RATE);

-if (Ethernet.begin(mac) == 0) {

-for (;;) {

15 Serial.println("Could not obtain an IP address using DHCP.");

-delay(1000);

-}

-} else {

-print_ip_address(Ethernet.localIP());

20

}

-

}

-

 

-

 

-

void loop() {

25

delay(1000);

-Serial.print("Connecting...");

-if (client.connect(time_server, DAYTIME_PORT) <= 0) {

-Serial.println("connection failed.");

-} else {

30 Serial.println("connected.");

report erratum • discuss

Using DHCP and DNS 179

-delay(300);

-

-while (client.available()) {

-char c = client.read();

35 Serial.print(c);

-}

-

-Serial.println("Disconnecting.");

-client.stop();

40

}

-

}

-

 

-void print_ip_address(IPAddress ip) {

-const unsigned int OCTETS = 4;

45 Serial.print("We've got the following IP address: ");

-for (unsigned int i = 0; i < OCTETS; i++) {

-Serial.print(ip[i]);

-if (i != OCTETS - 1)

-Serial.print(".");

50 }

-Serial.println();

-}

This program does the same as the program in the previous section, but it doesn’t contain any explicit IP addresses. Apart from that, it doesn’t differ much from the original version. The first difference is in line 8. Here we no longer declare the variable time_server as an IPAddress object but as a string. The string contains the name of the server we’re going to connect to.

In line 13, we no longer pass our own IP address to Ethernet’s begin method. In this case, begin tries to obtain an unique IP address using a DHCP server in the local network. If it cannot obtain an IP address, we start an endless loop that prints an error message every second. Otherwise, we print the IP address we’ve got, using a small helper function named print_ip_address.

Eventually, in line 27, we pass our time_server string to the connect method. Note that we didn’t change the line; we’ve only changed the type of the time_server variable. If connect gets a string and not an IPAddress object, it tries to look up the IP address belonging to the server name stored in the string using DNS.

Run the program, and you’ll see output similar to the following:

We've got the following IP address: 192.168.2.113

Connecting...connected.

56807 14-11-04 16:34:18 50 0 0 259.2 UTC(NIST) *

Disconnecting.

report erratum • discuss

Chapter 10. Networking with Arduino 180

You might ask yourself why you shouldn’t enjoy the convenience of DHCP and DNS all the time. First of all, DHCP and DNS are two more things that can go wrong. Debugging embedded systems is hard enough already, so you shouldn’t make it harder by using services that you don’t absolutely need. For most applications, hardwired IP addresses will do the job.

Another reason is code size. DHCP and DNS support will increase significantly the size of the resulting binary file. Adding DHCP support to our time service program increased its size by nearly 3,500 bytes. Still, DHCP and DNS are useful tools for certain applications, and it’s great that they’re now part of the Arduino’s standard library.

In the next chapter, you’ll learn how to implement another important network protocol: you will send emails using an Arduino.

Alternative Networking Technologies

Ethernet is one of the most popular and most powerful networking technologies. Using an Ethernet shield, you can easily connect your Arduino to the Internet both as a client and as a server.

Depending on your project’s needs, it’s sometimes better to use a wireless connection. With a Wi-Fi shield,a you can easily turn your Arduino into a wireless networking device.

But often you don’t need the full power of Ethernet, especially if you need only shortrange communication in a personal area network. You can choose from a variety of options, but Bluetooth and ZigBeeb are probably the most popular. Excellent solutions for both of them are available for the Arduino.

Finally, you can even participate in cellular networks with your Arduino. Plug in a GSM shieldc and your SIM card, and you are ready to go.

a.http://arduino.cc/en/Main/ArduinoWiFiShield

b.http://en.wikipedia.org/wiki/Zigbee

c.http://arduino.cc/en/Main/ArduinoGSMShield

What If It Doesn’t Work?

Networks are complex and complicated beasts, and many things can go wrong when trying the examples in this chapter. The most common problems are the following:

You have chosen the wrong serial port in the Processing application. By default, the application uses the first serial port it can find. It might be that you have connected your Arduino to another port. In this case, you

report erratum • discuss

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]