Table of Contents

To avoid repeating Wi-Fi connection code, we can abstract the connection process into a separate function and save it in a separate file.

On the right side of the current tab view, click the and select New Tab. Name the new file “WiFiHelper.ino”.

Move all the Wi-Fi related code into the “WiFiHelper.ino” file.

#include <WiFi.h>

const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";

void connectToWiFi() {
    Serial.println("Connecting to Wi-Fi...");
    WiFi.begin(ssid, password);

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting...");
    }

    Serial.println("Wi-Fi connected!");
    Serial.print("Local IP: ");
    Serial.println(WiFi.localIP());
}

In the original file, the code can be simplified like this:

void setup() {
    Serial.begin(115200);
    connectToWiFi();
}

void loop() {
}

Save the Arduino code if you haven’t already. When saving, Arduino will automatically create a folder and an .ino file using the name you specify. In that folder, you will find the WiFiHelper.ino file. If you need to access Wi-Fi functionality in other Arduino sketches, simply copy this file into the corresponding folder and use the connectToWiFi() function.

Categorized in:

WiFi,

Tagged in: