Building Arduino Projects for the Internet of Things

(Steven Felgate) #1
CHAPTER 2 ■ INTERNET CONNECTIVITY

Listing 2-6. External Libraries


#include <SPI.h>
#include <WiFi.h>


Internet Connectivity (Wireless)


The second section of the code defines variables, constants, and functions that are going
to be used for connecting to the Internet.
To connect Arduino to your wireless router, set the ssid and password ( pass ) of your
wireless network, as provided in Listing 2-7. Also create a WiFiClient variable that will be
used for Internet connectivity.


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


char ssid[] = " YOUR_SSID ";
char pass[] = " YOUR_PASSWORD ";


int keyIndex = 0;
int status = WL_IDLE_STATUS;


WiFiClient client;


Listing 2-8 provides code for wireless connectivity setup. The connectToInternet()
function first checks if the WiFi shield is attached. Next, the code keeps attempting
to connect to the wireless network. The loop and the function end once Arduino
successfully connects to the wireless network.


Listing 2-8. Code for Connecting to the Internet Using WiFi


void connectToInternet()
{
status = WiFi.status();


// Check for the presence of the shield
if (status == WL_NO_SHIELD)
{
Serial.println("[ERROR] WiFi Shield Not Present");
// Do nothing
while (true);
}


// Attempt to connect to WPA/WPA2 Wifi network
while ( status != WL_CONNECTED)
{
Serial.print("[INFO] Attempting Connection - WPA SSID: ");
Serial.println(ssid);


status = WiFi.begin(ssid, pass);
}

Free download pdf