Skip to main content

Code

int LED_PIN = 2;

void setup() {
  // put your setup code here, to run once:
  pinMode(LED_PIN,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(100);
  digitalWrite(LED_PIN,HIGH);  // turn the LED on (HIGH is the voltage level)
  delay(100);
  digitalWrite(LED_PIN,LOW);  // turn the LED off by making the voltage LOW
}

Connecting to Wifi with LED

#include <HTTPClient.h>
#include <WiFi.h>
#include <WebServer.h>

const char* WIFI_STA_NAME = "test_wifi";
const char* WIFI_STA_PASS = "test_password";

int LED_WIFI_STATUS = 2;
char IP_ADDRESS[15];
// Note: Your IP Address: 8.8.8.8

bool disablePrint = false;

// GPIO 27
int LED_PIN = 27;

WebServer server(80);

void setup() {
  Serial.begin(115200);
  pinMode(LED_WIFI_STATUS, OUTPUT);

  // Connect to Wifi
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_STA_NAME, WIFI_STA_PASS);

  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("Connecting...");
    delay(500);
    digitalWrite(LED_WIFI_STATUS, LOW);
  }

  for (int i = 0; i < sizeof(IP_ADDRESS); ++i) {
    IP_ADDRESS[i] = WiFi.localIP().toString().charAt(i);
  }

  digitalWrite(LED_WIFI_STATUS, HIGH);
  pinMode(LED_PIN,OUTPUT);

  // Start the server
  server.on("/", handleRoot);
  server.on("/on", ledOn);
  server.on("/off", ledOff);
  server.begin();
}

void loop() {
  if (!disablePrint) {
    delay(500);
    printWifiInfo();
  }

  // Open connection
  server.handleClient();
}

void printWifiInfo() {
  // print IP_ADDRESS
  Serial.print("Your IP Address is: ");
  for (int i = 0; i < sizeof(IP_ADDRESS); ++i) {
    Serial.print(IP_ADDRESS[i]);
  }
  Serial.println();
}

void handleRoot() {
  disablePrint = true;
  // return message for testing
  server.send(200, "text/plain", "Hello from ESP32!");
}

void ledOn() {
  disablePrint = true;
  digitalWrite(LED_PIN,HIGH);
  Serial.println("The light is on!");
  // return light status to client
  server.send(200, "text/plain", "The light is on!");
}

void ledOff() {
  disablePrint = true;
  digitalWrite(LED_PIN,LOW);
  Serial.println("The light is off!");
  // return light status to client
  server.send(200, "text/plain", "The light is off");
}