Today we will talk about little different type of content than usual one. We will have some fun with ESP boards and a relay connected.
Steps to control a relay with ESP32/ESP8266:
- Connect IN pin of relay module to GPIO (e.g., GPIO5)
- Power module from 3.3V (with transistor if needed)
- Set GPIO HIGH/LOW in code to open/close relay
- Upload code and test switching
We will configure ESP to connect to WIFI, bring up a basic webserver and then create a route to toggle our relay and get relay status so sketch is the following one:
// Load libraries
#ifdef ESP32
#include <WiFi.h>
#include <AsyncTCP.h>
#else
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#endif
#include <ESPAsyncWebServer.h>
// Declare WIFI and relay pin vars
const char* ssid = "WIFI_NAME";
const char* password = "WIFI_PASSWORD";
int relayPin = 4;
// Configure webserver port
AsyncWebServer server(80);
void setup(){
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, LOW);
// Configure serial communication
Serial.begin(115200);
// Start WIFI
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Configure route to toggle relay
server.on("/toggle", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(200, "text/plain","ok");
digitalWrite(relayPin, !digitalRead(relayPin));
});
// Configure route to get relay state
server.on("/status", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(200, "text/plain", String(digitalRead(relayPin)));
});
// Start webserver
server.begin();
}
void loop(){}
Looking to integrate IoT devices into centralized monitoring or automation?
→ Check out our Infrastructure Services
0 Comments