Friday, November 22, 2024

Connecting Arduino To The Internet

If you’re new to Arduino and connecting Arduino to the internet, the process might seem complicated at first. Many beginners face challenges when it comes to internet connectivity while coding with Arduino. Without a user-friendly interface and built-in debugging tools, it can be difficult to identify and rectify errors. In this article, we will provide a comprehensive guide on connecting your Arduino board to the internet, including the necessary code.

When I first began playing around with my Arduino Uno, I was very proud of making LEDs blink and sensors beep. But I soon realized that the true potential of an Arduino can only be achieved once you connect it to the internet.

You can check the innovative Arduino Projects.

- Advertisement -

Pretty much any intermediate to advanced level Arduino project will require you to connect to the internet for various reasons, be it logging data on the cloud such as weather data, or passing on real-time commands to your device remotely such as via an app on your phone.

In this tutorial, we are going to look at how to connect your Arduino device to the internet comprehensively. Everything—from the hardware to the circuit and code—will be covered.

- Advertisement -

Connecting Arduino to the Internet with Ethernet

The first option for connecting your Arduino to the internet is via an Ethernet cable. If you are using an Arduino board that comes with a built-in Ethernet port such as an Arduino Yún, you can skip the ‘Hardware requirements’ section and the circuit design description given below. Just connect the Ethernet cable to your device and start coding.

However, if, like most people, you own a simpler version of Arduino such as Arduino Uno that does not have a built-in Ethernet port, you will have to buy a separate device, called an Ethernet shield, to attach to your Arduino.

Hardware Requirements

You will require an Ethernet cable with the internet, an Arduino Uno board, and an
Ethernet Shield. Here’s how to connect them:

  1. Connect the Ethernet shield on top of the Arduino Uno.
  2. Connect the Ethernet cable to the Ethernet shield.
Arduino and Ethernet Shield
Fig. 1: Arduino and Ethernet Shield

Fig. 1 shows Arduino Uno and its Ethernet shield. After connecting the two, your Arduino Uno should look like the one in Fig. 2.

Arduino with Ethernet Shield
Fig. 2: Arduino with Ethernet Shield

Arduino Code for Connecting to the Internet via Ethernet

Before getting started with the code for connecting Arduino to the internet, we need to include an external library for use in the program. This library will help us establish a connection and send/receive data over the internet.

Note: This library should come preinstalled with your IDE. If for some reason you run into errors, please download this library from the official GitHub repository of the Arduino Project.

#include <Ethernet.h>

In the next step, we will be defining some constants and variables required for this program.

First, we need the MAC address. This is often printed on a sticker on the Ethernet shield. Next, we need to define a static IP address.

Make sure that the IP address that you are adding isn’t being used by any other user. Lastly, we shall define the EthernetClient variable.

byte mac[] = { oxDE, oxAD, oxBE, oxEF, 
oxFE, oxED };
IPAddress staticIP(10, 0, 0, 20);
EthernetClient client;

We can now write the method for connecting to the internet. There are two steps here. First, we try to get an IP via the DHCP (dynamic host configuration protocol), i.e., try to fetch your dynamic IP. If that step fails, then we fall back to the static IP that we have defined above.

void connectToInternet()
{
// Step 1 - Try connecting
with DHCP
If (Ethernet.begin(mac) == 0)
{
Serial.print(“[ERROR]
Failed to connect via DHCP”);
Ethernet.begin(mac,
staticIP); // Connect via static IP
defined earlier
}
// Add a delay for initialization
delay(1000);
Serial.println(“[INFO] Connection
Successful”);
Serial.print(“”);
printConnectionInformation(); // Custom
method
Serial.print
ln(“---------------------------------”);
Serial.println(“”);
}

As you can see in the code above, we used a custom method printConnectionInformation() for displaying the connection information. So let us go ahead and write the code for that.

void printConnectionInformation()
{
    // Print IP Address
    Serial.print(“[INFO] IP Address: ”);
    Serial.println(Ethernet.localIP());	
    // Print Subnet Mask
Serial.print(“[INFO] Subnet Mask: ”);
    Serial.println(Ethernet.
subnetMask());
    // Print Gateway
    Serial.print(“[INFO] Gateway: ”);
    Serial.println(Ethernet.gatewayIP());
    // Print DNS
    Serial.print(“[INFO] DNS: ”);
    Serial.println(Ethernet.
dnsServerIP());
}

Finally, we shall write the standard functions for the program, i.e. setup() and loop().

void setup()
{
    Serial.begin(9600);
    // Connect to the internet
    connectToInternet();
}
void loop()
{
    // Nothing much to do here.
}

If everything checks out, you should be seeing an output similar to Fig. 3 on the serial monitor window.

Connecting Arduino to the Internet via Ethernet
Fig. 3: Successful Arduino connection to the Internet via Ethernet

Connecting Arduino to the Internet via Wi-Fi

The second option is to connect your Arduino to the internet wirelessly via Wi-Fi. If, like most people, you own an Arduino Uno or any other Arduino board that does not have a built-in Wi-Fi capability, you will have to buy a wireless shield separately, like the Ethernet shield.

If you own an Arduino Yún or any other Arduino board with built-in wireless capability, you can skip the ‘Hardware requirements’ and the description on the next page and get started with the code right away.

Arduino Uno and its wireless shield
Fig. 4: Arduino Uno and its wireless shield

Hardware Requirements

You will need an Arduino Uno and a wireless shield. Here’s how to connect them:

  1. Connect the wireless shield on top of the Arduino Uno.
  2. Connect the Arduino Uno to your computer via the USB port.

Fig. 4 shows the Arduino Uno and the wireless shield. If everything is connected properly, your Arduino Uno board should look like the one in Fig. 5.

Wireless shield attached to Arduino Uno
Fig. 5: Wireless shield attached to Arduino Uno

Arduino Code for Connecting to the Internet via Wi-Fi

When connecting to the internet via Ethernet, we used the external library. Similarly, for connecting to the internet wirelessly, we shall be using the external library.

Note: This library should come preinstalled with your IDE. If for some reason you run into errors, please download this library from the official GitHub repository of the Arduino Project.

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

Next, we shall define the constants and variables required for connecting wirelessly. For connecting with the Wi-Fi, we require the ssid and password of the Wi-Fi that we shall be using. We shall also create a WiFiClient variable for connecting to the internet.

char ssid[] = “Write WiFi SSID here”;
char pass[] = “Write WiFi password 
here”;
int keyIndex - 0;
int status = WL_IDLE_STATUS;
WiFiClient client;

Now we shall define some custom methods for connecting and sending/receiving data over the Internet. First, let us create the method connectToInternet() for connecting with the Internet.

void connectToInternet()
{
   status = WiFi.status();
   if (status == WL_NO_SHIELD)
   {
     Serial.println(“[ERROR] WiFi Shield 
Not Present”);
     while (true);
}
while ( status != WL_CONNECTED)
{
   Serial.print(“[INFO] Attempting 
Connection - WPA SSID: ”);
   Serial.println(ssid);
   status = WiFi.begin(ssid, pass);
}
Serial.print(“[INFO] Connection 
Successful”);
Serial.print(“”);
printConnectionInformation();
Serial.print
ln(“-------------------------”);
Serial.println(“”);
}

As you can see in the code above, we have called the custom method printConnectionInformation() to display the information about our Wi-Fi connection. So let us go ahead and write that method:

void printConnectionInformation()
{
   Serial.print(“[INFO] SSID: ”);
   Serial.println(WiFi.SSID());
   // Print Router’s MAC address
   byte bssid[6];
   WiFi.BSSID(bssid);
   Serial.print(“[INFO] BSSID: ”);
   Serial.print(bssid[5], HEX);
   Serial.print(“:”);
   Serial.print(bssid[4], HEX);
   Serial.print(“:”);
   Serial.print(bssid[3], HEX);
   Serial.print(“:”);
   Serial.print(bssid[2], HEX);
   Serial.print(“:”);
   Serial.print(bssid[1], HEX);
   Serial.print(“:”);
   Serial.println(bssid[0], HEX);
   // Print Signal Strength 
   long rssi = WiFi.RSSI();
   Serial.print(“[INFO] Signal Strength 
   (RSSI) : ”);
   Serial.println(rssi);
   // Print Encryption type
   byte encryption = WiFi.encryption
   Type();
   Serial.print(“[INFO] Encryption Type 
: ”);
   Serial.println(encryption, HEX);
   // Print WiFi Shield’s IP address
   IPAddress ip = WiFi.localIP();
   Serial.print(“[INFO] IP Address : ”);
   Serial.println(ip);
   // Print MAC address
   byte mac[6];
   WiFi.macAddress(mac);
   Serial.print(“[INFO] MAC Address: ”);
   Serial.print(mac[5], HEX);
   Serial.print(“:”);
   Serial.print(mac[4], HEX);
   Serial.print(“:”);
   Serial.print(mac[3], HEX);
   Serial.print(“:”);
   Serial.print(mac[2], HEX);
   Serial.print(“:”);
   Serial.print(mac[1], HEX);
   Serial.print(“:”);
   Serial.println(mac[0], HEX);	
}

Finally, let us write down the standard functions, i.e. setup() and loop():

void setup()
{
    Serial.begin(9600);
    // Connect to the internet
    connectToInternet();
}
void loop()
{
    // Nothing to do here
}

Hurray! We are done with the Arduino code for connecting to the internet via Wi-Fi. In case there are no errors, the output on your serial monitor window should look like the output in Fig. 6.

Successful Arduino connection to the internet via Wi-Fi
Fig. 6: Successful Arduino connection to the Internet via Wi-Fi

This article was first published in the December 2022 issue of Open Source For You magazine.

Mir H.S. Quadri is a research analyst with a specialization in artificial intelligence and machine learning. He is the founder of Arkinfo, which focuses on the research and development of tech products using new-age technologies. He shares a deep love for analysis of technological trends and understanding their implications. Being a FOSS enthusiast, he has contributed to several open-source projects

SHARE YOUR THOUGHTS & COMMENTS

EFY Prime

Unique DIY Projects

Electronics News

Truly Innovative Electronics

Latest DIY Videos

Electronics Components

Electronics Jobs

Calculators For Electronics