NodeMCU WiFi Connection Guide

website·Indexed 30 days ago

https://blog-nee.vercel.app

Technical instructions and source code for connecting a NodeMCU device to a WiFi network.

Tokens
337
Snippets
1
Records
1
Agent score
25%

What's inside NodeMCU

  1. Connect NodeMCU to WiFi using Arduino IDE

    To connect a NodeMCU to a WiFi network, use the ESP8266WiFi library (implied by WiFi class usage). The process involves setting the WiFi mode to Station (WIFI_STA), initiating the connection with a SSID and password using WiFi.begin(), and polling WiFi.status() until it returns WL_CONNECTED or reaches a maximum retry limit.
    #include <ESP8266WiFi.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);
      
      // Poll status until connected or max retries reached
      while ((WiFi.status() != WL_CONNECTED) && (retries < MAX_WIFI_INIT_RETRY)) {
        retries++;
        delay(WIFI_RETRY_DELAY);
        Serial.print(".");
      }
      return WiFi.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
    }