Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Arduino Networking

You're reading from   Arduino Networking Connect your projects to the Web using the Arduino Ethernet library

Arrow left icon
Product type Paperback
Published in Aug 2014
Publisher
ISBN-13 9781783986866
Length 118 pages
Edition 1st Edition
Languages
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Marco Schwartz Marco Schwartz
Author Profile Icon Marco Schwartz
Marco Schwartz
Arrow right icon
View More author details
Toc

Testing your connection

Now that the hardware is ready, we can write our first sketch to test the Ethernet shield and the connection to the Web. Note that the pieces of code shown in this section are only the most important parts of the code, and you can find the complete code inside the GitHub repository of the book.

Start the Arduino sketch by including the following required libraries to use the shield:

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

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Then, we have to define the MAC address of the Ethernet shield. This address is located just behind the shield, and you should have noted it down already. You have to enter it in the following format:

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xFE, 0x40 };

We also need to define where we are going to connect to test the connection. You can use any web page you want, or even perform a search on Google, but for this first test, I want to use a simple page.

I found this website with a simple test page that we'll try to grab while making a request later in the sketch. You can also set up your own page if you have a web server online, for example, if you have a blog hosted somewhere.

The website address is stored in a char variable:

char server[] = "www.brainjar.com";

Note that you can also use other pages here, for example http://www.example.com/hello.

The Ethernet shield will then automatically get the IP address of this website.

To get an IP address for the Ethernet shield itself, we'll use DHCP to automatically get one from the router we are connected to. However, if DHCP fails, we need to assign a default address to the shield.

This is stored in an IPAddress variable. Note that you can put anything you want inside this variable. As for this first project, we really need DHCP to work to get connected to the Web. However, it is a good practice to specify an IP address in the same subnet as your router, so the shield can at least connect to your local network. For example, the IP address of my computer was 192.168.1.100, so I specified a similar IP address for the shield:

IPAddress ip(192,168,1,50);

We can now create the instance for the Ethernet client with the following code:

EthernetClient client;

Now, in the setup() function of the sketch, we will try to get an IP address using DHCP. If you're connected to a router, there is no reason it would fail. However, if it does indeed fail, we will automatically set the default IP address for the shield:

if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    Ethernet.begin(mac, ip);
}

Then, we will print out the IP address on the Serial port for debugging reasons:

Serial.begin(115200);
Serial.print("IP address: ");
Serial.println(Ethernet.localIP());

Now, in the loop() function of the sketch, we will actually connect to the server. It starts by calling the connect function and checks whether we are indeed connected. If that's the case, we print it out on the Serial monitor for debugging purposes:

if (client.connect(server, 80)) {
    if (client.connected()) {
      Serial.println("connected");

Now that we are connected, we can set the GET request for the test page we want to access:

client.println("GET /java/host/test.html HTTP/1.1");
client.println("Host: www.brainjar.com");
client.println("Connection: close");
client.println();

After the request is sent, we will read the data that is coming back from the server, to check whether everything went fine. We will also print out this data on the Serial monitor:

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

Finally, when we are sure that the client is not connected anymore, we will print the information on the Serial monitor and call the close() function on the Ethernet client:

if (!client.connected()) {
  Serial.println();
  Serial.println("disconnecting.");
  client.stop();
}

Finally, we don't want to continuously do this action, but only repeat it every five seconds. This is done with a delay() function:

delay(5000);

It's now time to test the sketch.

Note

The complete code for this first chapter can be found the GitHub repository of the book:

https://github.com/openhomeautomation/arduino-networking/tree/master/chapter1

Make sure that the Ethernet cable is plugged in your shield and your router, and upload the sketch to the Arduino board. You can now also open the Serial Monitor, and select the correct Serial speed (115200 for the Arduino sketch of this chapter); that's the first thing you should see, which is the IP address of your board:

IP address: 192.168.1.103

Then, the Arduino board should connect to the server:

Connecting...

If this is successful, the output will show that it is indeed connected:

connected

Now, the Arduino board will send the GET request to the server in order to grab the content of the test page. The server will answer with an HTTP 200 OK status if the request was successful, along with the contents of the page:

HTTP/1.1 200 OK
Content-Length: 308
Content-Type: text/html
Last-Modified: Tue, 27 May 2003 15:17:04 GMT
Accept-Ranges: bytes
ETag: "6291ea76324c31:5897"
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Date: Thu, 15 May 2014 17:35:40 GMT
Connection: close

Inside this long answer, you should see many HTML tags, such as <html> and <head> tags. Inside the answer, you should also get the content of the page inside a <p> tag as follows:

<p>This is a very simple HTML file.</p>

If you can see this, congratulations! Your Ethernet shield is working correctly! Finally, the Arduino board will also display that the Ethernet shield has been disconnected from the remote server:

disconnecting

If everything worked correctly, it means that your Ethernet shield is working correctly, and it can connect without any problems to your local network and to the Web.

If something didn't work as expected, there are several things you can check. First, make sure that all connections are correctly made, and that the Ethernet cable is correctly plugged between the shield and your router.

If the DHCP fails at the beginning of the sketch and your shield can't get an IP address, please check whether DHCP is activated without limitations on the MAC addresses in the configuration panel of your router.

Finally, if the Arduino board can't connect to the remote server, first check whether the server itself is working by entering the URL of the test page manually in your browser.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime