Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 2 ■ INTERNET CONNECTIVITY


External Libraries


First section of the code as provided in Listing 2-1 includes all external libraries required
to run the code. Since you are connecting to the Internet using Ethernet, the main
dependency of code is on <Ethernet.h>. Your Arduino IDE should already have the
Ethernet library installed, but for any reason it is missing, you can download it from:




  • : https://github.com/arduino/Arduino/tree/
    master/libraries/Ethernet


Listing 2-1. Code for Including External Dependencies


#include <Ethernet.h>


Internet Connectivity (Ethernet)


The second section of the code defines variables, constants, and functions that are going
to be used for connecting to the Internet.
As provided in Listing 2-2 , first you need to define the MAC address in the mac[]
variable. For newer Ethernet shields, the MAC address might be printed on a sticker.
You will also need to set a static IP address of Arduino for cases where it fails to get
a dynamic IP from DHCP (Dynamic Host Configuration Protocol). Make sure the IP
address you use is free, i.e., not currently in use by some other device on the network.
Define the EthernetClient variable that will be used for connectivity.


Listing 2-2. Constants and Variables for Connecting to the Internet Using Ethernet


byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress staticIP( 10, 0, 0, 20 );
EthernetClient client;


Listing 2-3 provides the code for the Ethernet connectivity setup. The
connectToInternet() function first attempts to connect to Ethernet with DHCP. If DHCP
fails to assign a dynamic IP address to Arduino, it will attempt connection to Ethernet
with the static IP you defined.


Listing 2-3. Code for Connecting to the Internet Using Ethernet


void connectToInternet()
{
// Attempt to connect to Ethernet with DHCP
if (Ethernet.begin(mac) == 0)
{
Serial.print("[ERROR] Failed to Configure Ethernet using DHCP");

Free download pdf