Relé inalámbrico

Las piezas

Para tener un relé inalámbrico necesitarás un microcontrolador ESP32, y un relé High Level Triggered de un canal (aunque en los esquemas salga un relé de dos canales, no es necesario). Consulta la sección “que comprar” si tienes dudas o pregunta en el foro.

Las conexiones son las siguientes:

 

ESP32 & Relay fritzing diagram
ESP32 & Relay fritzing diagram

 

ESP32 & Relay fritzing schematic
ESP32 & Relay fritzing schematic

El sketch

Tras instalar el sketch en el ESP32, puedes probar el funcionamiento del relé con una peticion http en tu navegador. Por ejemplo, si la ip asignada por el router a tu ESP32 es la 192.168.2.15, las siguientes peticiones http estan disponibles:

  • http://192.168.2.15: devuelve un objeto json con el status actual del relé.
  • http://192.168.2.15/H: establece el estado del relé a High, es decir, cierra el circuito.
  • http://192.168.2.15/L: establece el estado del relé a Low, es decir, abre el circuito.

Recuerda que tienes que modificar las líneas de la 15 a la 18 y proporcionarle al sketch el nombre de tu wifi (SSID), y la contraseña. Opcionalmente puedes asignarle un nombre al nodo.

 

/*
   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);
  }
}