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”.
![[Pasted image 20250125225958.png]]
Move all the Wi-Fi related code into the “WiFiHelper.ino” file.
```cpp
#include
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:
```cpp
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.
![[Pasted image 20250125230922.png]]
Code Refactoring
RELATED ARTICLES
Photoresistor Sensor
Project - Temperature Measurement
NTC Temperature Sensor
Project - IR Sender
Project - IR Receiver
Remote infrared Sensor
Project - Motion Detection Alarm
- Choosing a selection results in a full page refresh.