Connecting an Arduino using Wifi

Contents

Connecting an Arduino using Wifi#

Requirements

  1. An Arduino (We used an UNO)

  2. A Wifi shield (We just used and UNO R4 Wifi)

  3. Somewhere to send http requests

../../_images/Ard_wifi.jpg

Code#

Connecting over Wifi has some security implications, it is advised that you try not to save your passwords in your main code

//Libraries that are required
#include <WiFiS3.h> //Wifi libraries for R4 Wifi
#include "arduino_secrets.h"  //header with connection details best not shared

// WiFi credentials - these come from the the arduin_secrets.h
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;

// Server details
char server[] = SECRET_IP; // Use the IP address of your computer running your server
int port = SECRET_PORT; // Default port

WiFiClient client;  //the client to manage the wifi

The arduino_secrets.h looks like this

#define SECRET_SSID "Name of the wifi"
#define SECRET_PASS "wifi password"
#define SECRET_IP "IP address of server"
#define SECRET_PORT <port number>
#define SECRET_URL "URL on server to connect to"

Then in the set up function we attempt to connect to the Wifi

void setup() {
  Serial.begin(9600);   //connect to local serial (if present)
  while (!Serial);
 
  // Attempt to connect to WiFi network
  while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    delay(10000); // Retry every 10 seconds if connection fails
  }
  Serial.println("Connected to WiFi");
}

If the connection succeeds then the programme continues

How data is sent over the wifi depends on how you have set things up. Assuming you have a server which will accept a post request

// Prepare HTTP request
  String url = SECRET_URL; // The endpoint where you want to send data
  String data = "Build String with your data here"; // Construct data payload
 
  // Make a HTTP POST request
  if (client.connect(server, port)) {
    Serial.println("Connected to server");
    client.println("POST " + url + " HTTP/1.1");
    client.println("Host: " + String(server));
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.println(data);
    delay(1000); // delay to ensure the server processes the request
    //get and print response
    while (client.connected()) {
      if (client.available()) {
        // read an incoming byte from the server and print it to serial monitor:
        char c = client.read();
        Serial.print(c);
      }
    }

    client.stop();
    Serial.println("Data sent");
  } else {
    Serial.println("Connection to server failed");
  }
 
  delay(10000); // Post data every 10 seconds (adjust as needed)