• Worldwide Shipping

  • 24/7 Customer Support

  • FAQ
  • Worldwide Shipping

  • 24/7 Customer Support

  • FAQ

HUM: ARDUINO ETHERNET SHIELD WITH THE W5100

You are a beginner with Croduino. Or electronics? A specific module caught your eye, but you do not know how to use it? Do not worry, HUM is here for you! How to Use Module (HUM) is a blog tutorials series by e-radionica where you will find all you need in order to begin working with your favorite module. Tutorials include: technical characteristics, work principle, instructions on how to connect the module with Croduino and the basic code. Everything else is left to your imagination.

Introduction

In this tutorial, we will show you how to use the Ethernet Shield based on the W5100 integrated circuit. This integrated circuit is the "brain" of this whole module as it is responsible for overall communication with the Internet, sending and receiving data, i.e. packing and unpacking packets that come or go from it. This module can be used if we want to connect our Croduino to the Internet using wires while retrieving data such as air temperature in our city or posting some of our own measurements (air temperature, air humidity, air pressure, wind speed, etc.) on a web site (e.g. ThingSpeak service) or we want to do some kind of home automatization, so we want to set some parameters using our local network (e.g. adjusting the central heating temperature by accessing Croduino via our mobile phone that is connected to the same router to which the Croduino is connected). But, in the beginning, let us find out a bit more about our module.

 

How does the module work

Module characteristics:

• Power supply voltage: 5V i 3.3V

• Current: max 183 mA

• Supported Ethernet connection speeds: 10Base-T (10 Mbit/s) i 100Base-Tx (100 Mbit/s)

• The type of communication with Croduino: SPI (only via ICSP headers and it is used for the SD card and W5100)

• W5100 CS pin: Digital pin 10

• SD Card CS pin: Digital pin 4
For the beginning, let us get acquainted with some basic terms such as Ethernet, IP and MAC addresses, TCP and UDP protocol, HTTP and HTML.

Ethernet is a network communication technology that is highly praised for its robustness, simplicity, and speed. The first versions of Ethernet technology did not use the Ethernet cable we know today (and that is the UTP - Unshielded Twisted Pair and the STP - Shielded Twisted Pair, and even optics), but rather a coaxial cable, that is nowadays used to connect the antenna and the radio device. Due to the high attenuation at longer distances, limited signal transfer rates, one-way communication at a given time, it was quickly rejected and the Ethernet cable we are familiar with today was developed. (The picture shows today's Ethernet cable [top] and the coaxial Ethernet cable [bottom]).

Ethernet technology uses the CSMA/CD protocol for data transfer, and one of the most important characteristics of this protocol is collision detection (when two devices try to send data at the same time on the same line).

After we have learned something about the physical medium through which the data is sent, we can move on to IP addresses. The IP address is an address that consists of 4 numbers that are separated by full stops. One of the best-known addresses is the popular 192.168.1.1 using which you can access your home router. The address has the purpose of routing the packets through the network, that is, each node in the network has an address of its own, and to know where the data packet needs to be delivered, it is necessary to know the exact IP address of the destination. Also, it is necessary to know the address of the source so that, if unsuccessful packet delivery occurs, the source could be notified. That's exactly what the TCP protocol does. TCP (Transmission Control Protocol) is a type of protocol used in networks, and its task is to break a large packet into smaller parts (because it is not desirable to send a packet of several gigabytes at once), number each packet, assign a destination address to each packet, and finally, at the destination, return everything to the way it was, and if it comes to a loss of the packet, tell the source to resend this packet. This method of sending a packet is called sending a packet with a confirmation or reliable packet sending. There is another method where the packet is only divided into smaller parts and sent through the network without checking whether the packet has arrived. This protocol is called UDP (User Datagram Protocol). When it comes to MAC address (Media Access Control), it consists of 6 numbers separated by a colon, and they are usually written in a hexadecimal record. Then it accurately defines the device (hardware) it wants to communicate with since there may be more devices on one IP address and it is necessary to know to which device it should forward the received data. The first three numbers signify the manufacturer, while the other three signify the device itself. Now that we know how to receive, route, and send packets, we will deal with how to use these components to open a Web site. To open a Web site, first, we need to make a file request (which is essentially our Web site), which is performed using the HTTP (Hyper Text Transfer Protocol) protocol. It is composed of the requests and responses to these requests, so when we connect to a particular web address and we want to access the web site, we make a GET request after which we have the link to what we want (or if we just want the home page of that address, we write /, and in the end comes a version of HTTP (HTTP 1.0 or HTTP 1.1) . If the server has received it, it responds with 200 OK, which means that our request is received and if it is correct, it sends us what we asked for. If this does not happen, we receive a popular error 404 Not found.

Now that we have received data (a web page in our example), it is necessary to know how it is compiled and in which language it is written. For Websites, the most commonly used language is HTML (HyperText Markup Language), which is actually more a kind of descriptive language than a typical programming language such as C. The HTML code always starts with <html> and ends with </ html> and the HTML code is written in between. Sometimes HTML itself is not enough to create an interactive Web site, so we use a combination of HTML with JavaScript and CSS or PHP. Here, we will focus on HTML, and in one example we will show how to use CSS with HTML in order to create a more complex page with a simple graphical display.

How to connect

Connecting Croduino and Ethernet Shield is simple, but you should bear a couple of things in mind. Although the pins 10, 11, 12 and 13 on the Croduino are pins used for SPI communication, on this Shield, they are not. On the contrary, SPI communication is made through the ICSP headers on the Shield. The pins on the Shield are 5V tolerant, which means that Croduino and Shield are connected without lever converters.

For the second example of the code, we need LEDs. For the third and last DHT11 or DHT22 sensor, depending on what you currently have, just keep in mind that if you are using DHT22, it should also be set in the program code.

Arduino code

In this part of the tutorial, we will show some examples of the code for the module to retrieve a website (HTML file of the website), how the module should act as a Web server using which we can, e.g. turn the LEDs on or off, and how, with the help of ThingSpeak service, we can send data to our site as well as make a request for parsing the website (parsing is a procedure that extracts the specific part that we are interested in, from the entire website, e.g. a text).
For these examples, it is not necessary to install an Ethernet Shield library because it is already installed with the Arduino IDE, but you just need to check if the latest version of the library is installed by selecting Sketch from the upper menu in the Arduino IDE -> Include Library -> Manage Libraries, find the Arduino Ethernet library and see if you have an Update offered. For the DHT sensor, you will need to install a library that you can find here. If you do not know how to install the library, read our tutorial.
The first example shows how to retrieve a web page (in this case a weather forecast from the pages of the State Hydrometeorological Institute - DHMZ). It should be kept in mind that the HTML file of the default Web site will be displayed.

#include "SPI.h" //Attach the library for SPI communication (using which W5100 Ethernet and Croduino communicate)
#include "Ethernet.h" //Attach the library for controlling the W5100 Ethernet Shield that contains all important functions for opening Web pages, connecting to the Internet, sending requests, etc.
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //Ethernet Shield's MAC address (some Shields have labels with printed MAC addresses, enter that address instead of this one).
IPAddress ip(192, 168, 0, 177); //Set the static IP address if the DHCP does not succeed
IPAddress myDns(192, 168, 0, 1);
EthernetClient client; //Initialization of the library that executes all the functions related to connecting to the Web page, Internet, sending and receiving data, etc.
void setup() {
Serial.begin(115200); //Serial communication initialization between Croduino and the computer. (115200 Baud).
Ethernet.init(10); //Defining the CS (Chip Select) pin of our W5100 Ethernet on the Croduino. In our case, it is the pin 10.
Serial.println(F("Ethernet initialization using the DHCP..."));
if (Ethernet.begin(mac) == 0) {
Serial.println(F("Unsuccessful Ethernet setup using the DHCP."));
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println(F("W5100 Ethernet not found. Check whether the W5100 Ethernet is connected properly.."));
do {
//Infinite loop, it does not make sense to go on with the program if W5100 Ethernet has not been found.
} while (true);
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println(F("Ethernet cable is not connected! Connect the Ethernet cable to W5100 Ehternet and restart it."));
do {
//Infinite loop, it does not make sense to go on with the program if Ethernet is not connected to anything.
} while (true);
}
Ethernet.begin(mac, ip, myDns); //If everything is fine, but it is not possible to assign the DHCP, work with a static IP address.
} else {
Serial.print(F("Successfully assigned dynamic IP address using the DHCP: ")); //If it is possible, assign a dynamic IP address via DHCP and print it.
Serial.println(Ethernet.localIP());
}
delay(1000); //Wait a moment for the Ethernet to initialize to the new IP address.
//Let us try to open a certain Web page, e.g. weather forecast from www.meteo.hr
Serial.println(F("Trying to connect to www.meteo.hr ..."));
if (client.connect("www.meteo.hr", 80)) { //Let us try to connect to meteo.hr, since we want the Web page (which is http), in this case we look for port 80 (it can also be 88, 8080 or 8008)
client.println(F("GET /index.php?tab=prognoza&it=sutra HTTP/1.1")); //Since we want to open a Web page, we will make a GET request in order to retrieve it and we want the HTTP version to be 1.1
client.println(F("Host: www.meteo.hr")); //It is necessary to state who is the host
client.println(F("Connection: close")); //And after the host sends the Web page, end the connection.
client.println();
} else {
Serial.println(F("Unsuccessful connection to www.meteo.hr :(")); //If we were not able to connect to the desired Web page, notify the user.
}
while(client.connected()) { //As long as the host (i.e. the server where the Web page is located) is connected to us, save and print what it sends to us
while(client.available()) { //As long as there is data, save them to the buffer
uint8_t buf[100]; //Since Croduino has small RAM memory, we can not save all the data sent by the server (in this case, HTML site) at once, we have to do it piece by piece
int n = client.available(); //Checking how many characters/data is left to be received
if(n>100) n = 100; //If it exceeds the size of our buffer, limit the number to the dimension of our buffer (in this case 100 characters)
client.read(buf, 100); //Save data/characters to our buffer
Serial.write(buf, 100); //Display it on the Serial Monitor
}
}
client.stop(); //After everything is received, end the connection with the server / Web page host
}
void loop() {
// put your main code here, to run repeatedly:
}

The second example shows us how Croduino can be used as a small Web server that can be accessed within a local network, with the help of Ethernet Shield. After connecting the Ethernet Sheild to the network, on a computer or mobile phone, it is connected to the same network as Croduino, it is necessary to open the Web browser and enter the IP address from the example code. A Web site that allows the LEDs connected to the Croduino to turn on or off should open.

#include "SPI.h" //Attach the library for SPI communication (using which W5100 Ethernet and Croduino communicate)
#include "Ethernet.h" //Attach the library for controlling the W5100 Ethernet Shield that contains all important functions for opening Web pages, connecting to the Internet, sending requests, etc.
#define LED_C 3 //Pin on the Croduino to which the red LED will be connected
#define LED_Z 5 //Pin on the Croduino to which the green LED will be connected
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //Ethernet Shield's MAC address (some Shields have labels with printed MAC addresses, enter that address instead of this one.
IPAddress ip(192, 168, 1, 10); //Our Croduino Web server's IP address
EthernetServer server(80); //Initialization of the library that executes all the functions related to Web server (receiving requests, processing requests and sending data)
//80 within the brackets signifies the port of our Web page (web page, i.e. HTTP always has the port 80)
void setup() {
pinMode(LED_C, OUTPUT);
pinMode(LED_Z, OUTPUT);
Serial.begin(115200); //Serial communication initialization between Croduino and the computer. (115200 Baud).
Ethernet.init(10); //Defining the CS (Chip Select) pin of our W5100 Ethernet on the Croduino. In our case, it is the pin 10.
Ethernet.begin(mac, ip); //Initialize the library and Ethernet with the given MAC address and IP address
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println(F("W5100 Ethernet not found. Check whether the W5100 Ethernet is connected properly."));
do {
//Infinite loop, it does not make sense to go on with the program if W5100 Ethernet has not been found.
} while (true);
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println(F("Ethernet cable is not connected! Connect the Ethernet cable to W5100 Ehternet and restart it."));
do {
//Infinite loop, it does not make sense to go on with the program if Ethernet is not connected to anything.
} while (true);
}
server.begin(); //Let the server begin working
Serial.print(F("Server is active on the IP address ")); //Print the IP address using which we can access our server
Serial.print(Ethernet.localIP());
Serial.println(F(". Enter this address to your web browser to open the Web server."));
Serial.println(F("NOTE! The device using which we access the Web server and the Croduino Web server itself must be connected to the same network in order for them to be able to access each other!"));
}
void loop() {
EthernetClient client = server.available(); //Checking the server's state, if we have someone who has connected to it
if (client) { //If we do, notify us via Serial Monitor
Serial.println(F("New user connected to the server!"));
char req[100]; //String to which we save the user's request (more precise, a part of the request, because we only want to know which URL it wants to read in order to turn the LEDs on or off depending on what is sent)
char led1[7]; //String to which we save the state of the red LED
char led2[7]; //String to which we save the state of the green LED
while (client.connected()) { //If a user has connected to our server, read his request
if (client.available()) { //As long as he is connected, read the request and send the respond which is actually our Web page written in HTML
client.read(req, 100); //Save the user's request to string (we will need it later to know which LED the user wants to turn on or off)
Serial.println(F("User's request")); //On the Serial Monitor, display what the user's (client's) HTTP request is
Serial.write(req, 100);
Serial.println();
client.println(F("HTTP/1.1 200 OK")); //Respond together with the Web page in the HTML
client.println(F("Content-Type: text/html"));
client.println(F("Connection: close"));
client.println();
client.println(F("<!DOCTYPE HTML>"));
client.println(F("<html>"));
client.println(F("Croduino web server :)"));
client.println(F("<title>Croduino Web server</title><form action='/stanje'><fieldset><legend>Crvena LEDica</legend><input type='radio' name='led1' value='0' checked> Ugašena<br><input type='radio' name='led1' value='1'> Upaljena<br>"
"</fieldset><fieldset><legend>Zelena LEDica</legend><input type='radio' name='led2' value='0' checked> Ugašena<br><input type='radio' name='led2' value='1'> Upaljena<br></fieldset><input type='submit' value='Podesi'></form>"));
client.println(F("</html>"));
delay(1); //Wait for the user's mobile phone or computer to receive the Web page
client.stop(); //End the connection with the user/client
Serial.println(F("User disconnected"));
strncpy(led1, strstr(req, "led1="), 6); //From this whole request, extract the part that says whether the LED is turned on or off and save it to string
strncpy(led2, strstr(req, "led2="), 6);
if (led1[5] == '1') { //Read which number follows the "led1="(sixth character in the string), if it is one, then the LED must be on, if it is zero, the LED must be turned off
digitalWrite(LED_C, HIGH);
} else if (led1[5] == '0') {
digitalWrite(LED_C, LOW);
}
if (led2[5] == '1') { //Read which number follows the "led2="(sixth character in the string), if it is one, then the LED must be on, if it is zero, the LED must be turned off
digitalWrite(LED_Z, HIGH);
} else if (led1[5] == '0') {
digitalWrite(LED_Z, LOW);
}
}
}
}
}

The following example is somewhat more complicated. It uses DHT11 or DHT22 humidity and temperature sensor. The measurements made on the sensor can be accessed via Croduino Web server (program code) in a way similar to the previous example, namely that the Croduino and Ethernet Shield are connected to the local network, and that the device that is also in the local network accesses Croduino Web server via Web browser on the computer or mobile phone by entering the IP address specified in the code. It is important to note that this code has two versions of the website; the one that uses CSS for display and the one that uses pure HTML. The one using CSS can graphically display data via bargraph, and the one that uses pure HTML displays the measured values as plain text. The pages themselves are refreshed every 3 seconds while displaying new measured data.

#include "SPI.h" //Attach the library for SPI communication (using which W5100 Ethernet and Croduino communicate)
#include "Ethernet.h" //Attach the library for controlling the W5100 Ethernet Shield that contains all important functions for opening Web pages, connecting to the Internet, sending requests, etc.
#include "DHT.h"
#define DHTPIN 2 //Pin on the Croduino that will be connected to the DHT
#define DHTTYPE DHT11 //Defining which DHT sensor model we use (in this case, DHT11)
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //Ethernet Shield's MAC address (some Shields have labels with printed MAC addresses, enter that address instead of this one).
IPAddress ip(192, 168, 1, 10); //Our Croduino Web server's IP address
DHT dht(DHTPIN, DHTTYPE); //Initialization of the library with the default DHT sensor model and pin to which the DHT is connected to Croduino
float t, h; //Variables to which we save air temperature and humidity values that were measured using the DHT11 sensor
EthernetServer server(80); //Initialization of the library that executes all the functions related to Web server (receiving requests, processing requests and sending data)
//80 within the brackets signifies the port of our Web page (web page, i.e. HTTP always has the port 80)
void setup() {
dht.begin(); //Initialization of the library and the DHT sensor beginning to work
Serial.begin(115200); //Serial communication initialization between Croduino and the computer. (115200 Baud).
Ethernet.init(10); //Defining the CS (Chip Select) pin of our W5100 Ethernet on the Croduino. In our case, it is the pin 10.
Ethernet.begin(mac, ip); //Initialize the library and Ethernet with the given MAC address and IP address
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println(F("W5100 Ethernet not found. Check whether the W5100 Ethernet is connected properly."));
do {
//Infinite loop, it does not make sense to go on with the program if W5100 Ethernet has not been found.
} while (true);
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println(F("Ethernet cable is not connected! Connect the Ethernet cable to W5100 Ehternet and restart it."));
do {
//Infinite loop, it does not make sense to go on with the program if Ethernet is not connected to anything.
} while (true);
}
server.begin(); //Let the server begin working
Serial.print(F("The server is active on the IP address")); //Print the IP address using which we can access our server
Serial.print(Ethernet.localIP());
Serial.println(F(". Enter this address to your web browser to open the Web server."));
Serial.println(F("NOTE! The device using which we access the Web server and the Croduino Web server itself must be connected to the same network in order for them to be able to access each other!"));
}
void loop() {
EthernetClient client = server.available(); //Checking the server's state, if we have someone who has connected to it
if (client) { //If we do, notify us via Serial Monitor
Serial.println(F("New user connected to the server!"));
char req[100]; //String to which we save the user's request
while (client.connected()) { //If a user has connected to our server, read his request
if (client.available()) { //As long as he is connected, read the request and send the respond which is actually our Web page written in HTML and CSS
client.read(req, 100); //Save the user's request to string
h = dht.readHumidity(); //Read temperature off the DHT11 sensor and save it to this variable
t = dht.readTemperature(); //Read humidity off the DHT11 sensor and save it to this variable
Serial.println(F("User's request")); //On the Serial Monitor, display what the user's (client's) HTTP request is
Serial.write(req, 100);
Serial.println();
client.println(F("HTTP/1.1 200 OK")); //Respond together with the Web page in the HTML
client.println(F("Content-Type: text/html"));
client.println(F("Connection: close"));
client.println();
client.println(F("<!DOCTYPE HTML>"));
client.println(F("<html>"));
client.println(F("<meta http-equiv='refresh' content='3'><title>Croduino Web server</title><\html>")); //Set the Web page to refresh every 3 seconds and for the Web page to have its title
client.println(F("Croduino web server :)"));
//The following part of the code is the Web page itself made using the HTML and CSS, and it refreshes every 3 seconds. If this is too complicated for the beginners, comment this whole code, and uncomment the lower part
//which is a simple Web page written in pure HTML. This is merely an example that something more complicated can be made, if you use the CSS too. :)
client.print(F("<style>.bargraph {list-style: none; padding-top: 20px; width:560px; }"
"ul.bargraph li.temp {background: #B40404; width:"));
client.print(t / 2, 0);
client.print(F("%; height: 35px; color: white; text-align: left; font-style: italic; font-weight:bolder; font-size: 14px; line-height: 35px; padding: 0px 20px; margin-bottom: 5px; }"
"ul.bargraph li.vlaga { background: #0000FF; width:"));
client.print(h, 0);
client.print(F("%; height: 35px; color: white; text-align: left; font-style: italic; font-weight:bolder; font-size: 14px; line-height: 35px; padding: 0px 20px; margin-bottom: 5px; }"
"</style> <html> DHT11 Senzor <ul class='bargraph'>Air temperature: "));
client.print(t, 0);
client.print(F("°C<li class='temp'></li><br>Air humidity: "));
client.print(h, 0);
client.println(F("%<li class='vlaga'></li> </ul> </html>"));
//A more simple Web page written with pure HTML. You need to uncomment this, and previously comment if you want to use a simpler Web page. This one also has the ability to automatically refresh after 3 seconds.
// client.print(F("<html>"));
// client.print(F("<br>Temperature: "));
// client.print(t, 0);
// client.print(F("°C<br>Humidity: "));
// client.print(h, 0);
// client.println(F("%</html>"));
delay(1); //Wait for the user's mobile phone or computer to receive the Web page
client.stop(); //End the connection with the user/client
Serial.println(F("User disconnected"));
}
}
}
}

The following code is based on the ThingSpeak service. The ThingSpeak service is specifically intended for IoT (Internet on Things) for the service to perform some of the more complicated tasks, and then return only the results to us. In this example, we will show you how to parse the web page and extract only one part of the text from it. We will use a weather forecast for tomorrow from the Croatian National Hydrometeorological Institute's website. First, you need to create an account on ThingSpeak (which is free). Then, from the top menu, select Apps, then ThingHTTP. After opening, click on New Thing. A new page that creates a new overview in which we can adjust what, how and from where we want to parse, opens. But let's start from the beginning, more precisely from the name, for example, forecast_for_tomorrow, under the URL we enter the address of the web page from where we want to download the text (for this example http://meteo.hr/index.php?tab=prognoza&it=sutra), the Method must be set to GET, and HTTP Version to 1.1. In the end, we have the Parse String field left. This field specifies which part of the page is to be extracted. This can be done in a way that in the Chrome browser, when browsing the desired Web site, you right click on the part of the text that you want to extract and select Check. An additional window opens with a highlighted piece of code that we are interested in (marked in blue). Right click on it, Copy, and then Copy Xpath. Then paste it into Parse String (/html/body/section [3]/div[1]/div/div[3]/p for our example) and click on Save ThingHTTP to save the settings. In the upper right part, there is a link, which leads us to the extracted text. If we enter it to our browser and try to open it, we will see that from the whole Web page, only the text we are interested in remains and which is easier to be manipulated on Croduino. Now, what follows is the code that we will insert into Croduino in order for it to open our Web page using ThingSpeak and display the content of that Web page on the Serial Monitor.

#include <SPI.h> //Attach the library for SPI communication (using which W5100 Ethernet and Croduino communicate)
#include <Ethernet.h> //Attach the library for controlling the W5100 Ethernet Shield that contains all important functions for opening Web pages, connecting to the Internet, sending requests, etc.
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //Ethernet Shield's MAC address (some Shields have labels with printed MAC addresses, enter that address instead of this one).
IPAddress ip(192, 168, 0, 177); //Set the static IP address if the DHCP does not succeed
IPAddress myDns(192, 168, 0, 1);
EthernetClient client; //Initialization of the library that executes all the functions related to connecting to the Web page, Internet, sending and receiving data, etc.
void setup() {
Serial.begin(115200); //Serial communication initialization between Croduino and the computer. (115200 Baud).
Ethernet.init(10); //Defining the CS (Chip Select) pin of our W5100 Ethernet on the Croduino. In our case, it is the pin 10.
Serial.println(F("Ethernet initialization using the DHCP..."));
if (Ethernet.begin(mac) == 0) {
Serial.println(F("Unsuccessful Ethernet setup using the DHCP."));
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println(F("W5100 Ethernet not found. Check whether the W5100 Ethernet is connected properly."));
do {
//Infinite loop, it does not make sense to go on with the program if W5100 Ethernet has not been found.
} while (true);
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println(F("Ethernet cable is not connected! Connect the Ethernet cable to W5100 Ehternet and restart it."));
do {
//Infinite loop, it does not make sense to go on with the program if Ethernet is not connected to anything.
} while (true);
}
Ethernet.begin(mac, ip, myDns); //If everything is fine, but it is not possible to assign the DHCP, work with a static IP address.
} else {
Serial.print(F("Successfully assigned dynamic IP address using DHCP: ")); //If it is possible, assign a dynamic IP address via DHCP and print it.
Serial.println(Ethernet.localIP());
}
delay(1000); //Wait a moment for the Ethernet to initialize to the new IP address.
//Let us try to open the Web page using ThingSpeak
Serial.println(F("Trying to connect to api.thingspeak.com ..."));
if (client.connect("api.thingspeak.com", 80)) { //Let us try to connect to api.thingspeak.com, since we want the Web page (which is http), in this case we look for port 80 (it can also be 88, 8080 ili 8008)
//Here, it is necessary to paste the link you get from ThingSpeak, more precise ThingHTTP (API key). Otherwise this code will NOT work!
client.println(F("GET https://api.thingspeak.com/apps/thinghttp/send_request?api_key=XXXXXXXXXXXXXXXX HTTP/1.1"));
client.println(F("Host: api.thingspeak.com")); //It is necessary to state who is the host
client.println(F("Connection: close")); //And after the host sends the Web page, end the connection.
client.println();
} else {
Serial.println(F("Unsuccessful connection to api.thingspeak.com :(")); //If we weren't able to connect to the desired Web page, notify the user.
}
while(client.connected()) { //As long as the host (i.e. the server where the Web page is located) is connected to us, save and print what it sends to us
while(client.available()) { //As long as there is data, save them to the buffer
uint8_t buf[100]; //Since Croduino has small RAM memory, we can not save all the data sent by the server (in this case, HTML site) at once, we have to do it piece by piece
int n = client.available(); //Checking how many characters/data is left to be received
if(n>100) n = 100; //If it exceeds the size of our buffer, limit the number to the dimension of our buffer (in this case 100 characters)
client.read(buf, 100); //Save data/characters to the buffer
Serial.write(buf, 100); //Display it on the Serial Monitor
}
}
client.stop(); //After everything is received, end the connection with the server / Web page host
}
void loop() {
}

And the last code we have here shows how to post some data on the Internet, using ThingSpeak (e.g. air temperature and humidity measurements). Open ThingSpeak and from the top menu, select Channels, and then My Channels. Since we do not have one yet, we have to make it, so click on a New Channel. A new page, where we set up our new channel into which we will enter data from Croduino on the Internet, opens. Under the Name, we enter the name of the channel (e.g. Air temperature and humidity), then we enter the description under Description, what type of data is displayed, why that data exactly and the like. (e.g. Air temperature and humidity measurement using Croduino Basic, DHT11 Sensor, and Ethernet W5100 Shield). In the following fields, we enter the names of certain data we measure (e.g. in Field 1, we enter Temperature, and in Field 2, Humidity). After that, go to the bottom of the page and click Save Channel. Then select the API keys from the current channel menu. These are the keys (combinations of numbers and letters) using which we can add new data. API keys must be confidential, otherwise, anyone can replace our data). By opening this page, on the right, there is a URL above which says Update a Channel Feed. This link is required in the Arduino code in order to be able to send the desired data. Below this text, there is a code that is set on the Croduino.

#include "SPI.h" //Attach the library for SPI communication (using which W5100 Ethernet and Croduino communicate)
#include "Ethernet.h" //Attach the library for controlling the W5100 Ethernet Shield that contains all important functions for opening Web pages, connecting to the Internet, sending requests, etc.
#include "DHT.h" //Attach the library for communication with the DHT air temperature and humidity sensor
#define DHTPIN 2 //Pin on the Croduino that will be connected to the DHT
#define DHTTYPE DHT11 //Defining which DHT sensor model we use (in this case, DHT11)
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //Ethernet Shield's MAC address (some Shields have labels with printed MAC addresses, enter that address instead of this one).
IPAddress ip(192, 168, 0, 177); //Set the static IP address if the DHCP does not succeed
IPAddress myDns(192, 168, 0, 1);
EthernetClient client; //Initialization of the library that executes all the functions related to connecting to the Web page, Internet, sending and receiving data, etc.
DHT dht(DHTPIN, DHTTYPE); //Initialization of the library with the default DHT sensor model and pin to which the DHT is connected to Croduino
float t, h; //Variables to which we save air temperature and humidity values that were measured using the DHT11 sensor
void setup() {
Serial.begin(115200); //Serial communication initialization between Croduino and the computer. (115200 Baud).
Ethernet.init(10); //Defining the CS (Chip Select) pin of our W5100 Ethernet on the Croduino. In our case, it is the pin 10.
Serial.println(F("Ethernet initialization using the DHCP..."));
if (Ethernet.begin(mac) == 0) {
Serial.println(F("Unsuccessful Ethernet setup using the DHCP."));
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println(F("W5100 Ethernet not found. Check whether the W5100 Ethernet is connected properly."));
do {
//Infinite loop, it does not make sense to go on with the program if W5100 Ethernet has not been found.
} while (true);
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println(F("Ethernet cable is not connected! Connect the Ethernet cable to W5100 Ehternet and restart it."));
do {
//Infinite loop, it does not make sense to go on with the program if Ethernet is not connected to anything.
} while (true);
}
Ethernet.begin(mac, ip, myDns); //If everything is fine, but it is not possible to assign the DHCP, work with a static IP address.
} else {
Serial.print(F("Successfully assigned dynamic IP address using DHCP: ")); //If it is possible, assign a dynamic IP address via DHCP and print it.
Serial.println(Ethernet.localIP());
}
delay(1000); //Wait a moment for the Ethernet to initialize to the new IP address.
}
void loop() {
//Let us try to open the Web page using ThingSpeak
Serial.println(F("Trying to connect to api.thingspeak.com ..."));
if (client.connect("api.thingspeak.com", 80)) { //Let us try to connect to api.thingspeak.com
h = dht.readHumidity(); //Read temperature off the DHT11 sensor and save it to this variable
t = dht.readTemperature(); //Read air humidity off the DHT11 sensor and save it to this variable
//Here, it is necessary to paste the link you get from ThingSpeak, more precise ThingHTTP (API key). Otherwise this code will NOT work!
client.print(F("GET https://api.thingspeak.com/update?api_key=xxxxxxxxxxxxxxxx&field1=")); //After filed1= follows the value we want to enter into our channel's Field 1 (air temperature)
client.print(t, 0);
client.print(F("&field2=")); //Then the value we want to enter to Field 2 (in our case, air humidity)
client.print(h, 0);
client.println(F("HTTP/1.1"));
client.println(F("Host: api.thingspeak.com")); //It is necessary to state who is the host
client.println(F("Connection: close")); //And after the host sends the Web page, end the connection.
client.println();
client.stop(); //After everything is received, end the connection with the server / Web page host
Serial.println(F("New air temperature and humidity value is added to ThingSpeak!"));
} else {
Serial.println(F("Unsuccessful connection to api.thingspeak.com :(")); //If we weren't able to connect to the desired Web page, notify the user.
}
delay(10000); //10 second pause. It is not necessary to post new data on the Internet so often!
}

 

Leave a Reply