The ESP32 is a low cost micro made by Espressif, which supports Arduino libraries and can connect to WiFi networks. Connecting to a WiFi network is pretty easy. Just call: WiFi.begin("SSID", "Password");
with your network credentials: the network’s SSID and password.
You’ll need to come up with a way to let end-users enter their network credentials when it comes time to release your product. But for prototyping it is much easier to just include the SSID and password in your code.
Easier, but not very safe. With the password in the code, you might accidentally share it when copying code into your website or pushing to Github. Oops.
A Safer Way to Store Network Credentials
A custom Arduino library is a simple, safer way to store network credentials. It is also a bit easier since you don’t have to remember them for each new program. Of course, anyone who has access to your computer could find your network password but that could be okay in private networks.
Creating your own library for network settings is as simple as adding a folder and file to your local Arduino library. On Windows, you’ll normally find the local Arduino library in MyDocuments\Arduino\libraries
.
Add a folder and call it something like Configuration
. Use a text editor, like Notepad, to create a file named WiFiConfig.h
in the new Configuration
folder. In your WiFiConfig.h
file put, replacing Your SSID and Your Password with the configuration for your network:
1 2 |
const char *SSID = "Your SSID"; const char *WiFiPassword = "Your Password"; |
Using the Credentials Library
Like any other Arduino library, simply #include "WiFiConfig.h"
at the top of your Arduino sketch.
Now we can create a function to setup the WiFi connection in a new Arduino program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include "WiFi.h" // ESP32 WiFi include #include "WiFiConfig.h" // My WiFi configuration. void ConnectToWiFi() { WiFi.mode(WIFI_STA); WiFi.begin(SSID, WiFiPassword); Serial.print("Connecting to "); Serial.println(SSID); uint8_t i = 0; while (WiFi.status() != WL_CONNECTED) { Serial.print('.'); delay(500); if ((++i % 16) == 0) { Serial.println(F(" still trying to connect")); } } Serial.print(F("Connected. My IP address is: ")); Serial.println(WiFi.localIP()); } |
ConnectToWiFi()
function gets called from the setup function:
1 2 3 4 5 6 |
void setup() { Serial.begin(9600); ConnectToWiFi(); } |