If you want your Arduino projects to be even cooler, connecting them to a WiFi network is a must. In this tutorial, we will learn how to connect an Arduino to a WiFi network using the WiFiNINA library.

To get started, make sure your Arduino board has WiFi connectivity. For example, you can use the Arduino MKR WiFi 1010 or the Arduino Uno WiFi Rev2.

First, include the necessary libraries in your Arduino sketch:

#include <SPI.h>
#include <WiFiNINA.h>

The SPI library is required by the WiFiNINA library, so make sure to load it as well. SPI stands for Serial Peripheral Interface.

Next, let’s focus on the setup() function. This is the main function we need to implement in our Arduino sketch:

void setup() {

}

Inside the setup() function, we need to define two strings: the network name (SSID) and the network password. If you are using Arduino Create, you can use constants stored in the Secret tab:

char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;

To enable serial communication between the Arduino and Arduino Create, initialize the Serial interface:

Serial.begin(9600);

Wait until the serial communication is ready with:

while (!Serial);

Now, we want to connect to the WiFi network using WiFi.begin(). Wrap it inside a loop that checks for a return value of WL_CONNECTED. If the connection is not established, retry every 2 seconds:

int status = WL_IDLE_STATUS;
while (status != WL_CONNECTED) {
  Serial.print("Connecting to ");
  Serial.println(ssid);
  status = WiFi.begin(ssid, pass);
  delay(2000);
}

Before continuing, retrieve the device’s IP address using WiFi.localIP() and print it to the serial monitor:

Serial.print("IP address: ");
Serial.println(WiFi.localIP());

Here’s the complete code:

#include <SPI.h>
#include <WiFiNINA.h>

void setup() {
  char ssid[] = SECRET_SSID;
  char pass[] = SECRET_PASS;

  Serial.begin(9600);
  while (!Serial);

  int status = WL_IDLE_STATUS;
  while (status != WL_CONNECTED) {
    Serial.print("Connecting to ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    delay(5000);
  }

  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {

}

With the Arduino successfully connected to the WiFi network, you can now perform other tasks. For example, you can get the network SSID using WiFi.SSID() and the signal strength with WiFi.RSSI():

Serial.print("Signal strength in dBm: ");
Serial.print(WiFi.RSSI());

Additionally, you can check if a NINA firmware upgrade is available by adding the following code:

if (WiFi.firmwareVersion() < WIFI_FIRMWARE_LATEST_VERSION) {
  Serial.println("Firmware upgrade available");
}

If an upgrade is available, you can use the Arduino IDE to update the firmware. Simply connect to the board, load the File -> Examples -> WiFiNINA -> Tools -> FirmwareUpdater example sketch, and update the firmware using the Tools -> WiFi101 / WiFiNINA Firmware Updater menu.

Tags: Arduino, WiFi, Networking, Internet of Things, IoT