If you have recently got hands on brand new nodemcu microcontroller, then you must be thinking "Well how to connect this thing to wifi? 🤔", if it is then this blog is for you!
If you don't want to understand the whole source code and just get started, here is the source code.
#include <stdio.h>
#include <ESP8266WebServer.h>
#define HTTP_REST_PORT 80
#define WIFI_RETRY_DELAY 500
#define MAX_WIFI_INIT_RETRY 50
const char* wifi_ssid = "your_wifi_name";
const char* wifi_passwd = "wifi_pass";
ESP8266WebServer http_rest_server(HTTP_REST_PORT);
int init_wifi() {
int retries = 0;
Serial.println("Connecting to WiFi ...");
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_ssid, wifi_passwd);
// check the status of WiFi connection to be WL_CONNECTED
while ((WiFi.status() != WL_CONNECTED) && (retries < MAX_WIFI_INIT_RETRY)) {
retries++;
delay(WIFI_RETRY_DELAY);
Serial.print(".");
// Dots will print to show still connecting...
}
return WiFi.status(); // return the WiFi connection status
}
void setup(void) {
Serial.begin(9600);
if (init_wifi() == WL_CONNECTED) {
Serial.println("WIFI Connected");
Serial.print(wifi_ssid);
Serial.print("--- IP: ");
Serial.println(WiFi.localIP());
} else {
Serial.print("Error connecting to: ");
Serial.println(wifi_ssid);
}
}
void loop(void) {
// loop
}