Wireless relay

The pieces

To have a wireless relay you need an ESP32 board and a High Level Triggered relay. Refer to the “what to buy” article if you are unsure what you need.

 

ESP32 & Relay fritzing diagram
ESP32 & Relay fritzing diagram

 

ESP32 & Relay fritzing schematic
ESP32 & Relay fritzing schematic
Two Channel High Level Relay connected to an ESP32 board
Two Channel High Level Relay connected to an ESP32 board

The Sketch.

After uploading the sketch with the Arduino IDE to the ESP32 board, you can trigger the relay with a http request. For example, if the ip address given by the router to the board is the 192.168.2.15, then following http request are available.

  • http://192.168.2.15: returns a json object with the current status of the relay.
  • http://192.168.2.15/H: sets the state of the relay to High and returns the same json object as before.
  • http://192.168.2.15/L: sets the state of the relay to Low and returns the same json object as before.

To know the Ip address of the ESP32 board, take a look with the serial console from the Arduino IDE after uploading the sketch to the board.

 

/*
   Smart Pi Thermostat by Roque Campos
    Sketch to siwtch on/of a relay with an ESP32
   Complete Project Details https://www.smart-pi-thermostat.com
*/



#include 

//Adjust the configuration of your network here.
const char* ssid     = "ssid";
const char* password = "password";
const String nodeName = "Main Relay";
//End network configuration
const String sketchVersion = "2";
const String nodeType = "Relay";
unsigned long lastReceivedRelayCommandMilis;
const unsigned int TIMEOUT_REICEIVED_COMMANDS_MILIS = 1000 * 60 * 2; //Two minutes
String relayError = "";

const int relayPin = 18;
const int ONBOARD_LED_PIN = 2;

WiFiServer server(80);

void setup()
{
  Serial.begin(115200);
  pinMode(ONBOARD_LED_PIN, OUTPUT);
  pinMode(relayPin, OUTPUT);      // set the Relay pin mode

  delay(10);

  setUpWifi();

  lastReceivedRelayCommandMilis = millis();

}

void setUpWifi() {

  //WiFi.config(ip,dns,gateway,subnet);

  // attempt to connect to Wifi network:
  int counter = 0;
  while (WiFi.status() != WL_CONNECTED) {
    WiFi.disconnect();
    WiFi.begin(ssid, password);
    int counter = 0;
    while (WiFi.status() != WL_CONNECTED) {
      delay(1000);
      Serial.print(".");
      counter++;
      if (counter > 10) {
        break;
      }
    }
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.print("MAC: ");
  Serial.println(WiFi.macAddress());

  server.begin();
}
void turnRelayOffIfTimeout() {
  unsigned long now = millis();
  long elapsed = now - lastReceivedRelayCommandMilis;
  if (elapsed > TIMEOUT_REICEIVED_COMMANDS_MILIS) {
    digitalWrite(relayPin, LOW);
    relayError = "Thermostat command timeout...";
  }
}

void loop() {


  turnRelayOffIfTimeout();

  if (WiFi.status() != WL_CONNECTED) {
    setUpWifi();
  }

  WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,
    digitalWrite(ONBOARD_LED_PIN, HIGH);
    Serial.println("New Client.");           // print a message out the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        if (c == '\n') {                    // if the byte is a newline character

          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {

            client.println("HTTP/1.1 200 OK");
            client.println("Content-Type: application/json");
            client.println();
            client.println("{");
            client.println();
            client.println("\"nodeType\":\"" + nodeType + "\",");
            client.println("\"name\":\"" + nodeName + "\",");
            client.println("\"version\":\"" + sketchVersion + "\",");
            client.println("\"relayError\":\"" + relayError + "\",");
            client.println("\"mac\":\"" + WiFi.macAddress() + "\",");
            int currentStatus = digitalRead(relayPin);

            String statusAsString = (currentStatus == 1) ? "true" : "false";

            client.print("\"status\":\"" + statusAsString);
            client.println("\"");

            client.println();
            client.println("}");
            client.println();
            break;

          } else {    // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }

        if (currentLine.endsWith("GET /H")) {
          lastReceivedRelayCommandMilis = millis();
          digitalWrite(relayPin, HIGH);
          relayError = "";
        }
        if (currentLine.endsWith("GET /L")) {
          lastReceivedRelayCommandMilis = millis();
          digitalWrite(relayPin, LOW);
          relayError = "";
        }
      }
    }
    // close the connection:
    client.stop();
    Serial.println("Client Disconnected.");
    digitalWrite(ONBOARD_LED_PIN, LOW);
  }
}