ESP32, et websocket pour controller un Relay

SDR-05VDC-SL-C

Relay

PIN DESCRIPTION RANG
GND Ground-liée au GND de la carte 0V
+5V +5V-Liée à la pin +5v de la carte 5v
Signal Pin TTL de controle:
-Si 1 NO=COM et NC=0v
-Si 0 NO=0V et NC=COM
de 0 à 5V
COM C'est à la tension a controler 24V maximum (à vérifier selon constructeur)
NO Délivre la tension COM quand Signal = 1 0=> bouton clos
1=> bouton ouvert
NC Délivre la tension COM quand Signal = 0 0=> bouton clos
1=> bouton ouvert

Code ESP32 -IDE ARduino

#include <WiFi.h>
#include <SPIFFS.h>
#include <ESPAsyncWebServer.h>
#include <WebSocketsServer.h>

// Constants
const char *ssid = "ESP32-AP";
const char *password =  "j2geek.com";
const int dns_port = 53;
const int http_port = 80;
const int ws_port = 1337;
const int relay_pin = 26;

// Globals
AsyncWebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(1337);
char msg_buf[10];
int relay_state = 0;

/***********************************************************
   Functions
*/

// Callback: receiving any WebSocket message
void onWebSocketEvent(uint8_t client_num, WStype_t type, uint8_t * payload, size_t length)
{
  switch (type) {

    // Client has disconnected
    case WStype_DISCONNECTED:
      Serial.printf("[%u] Disconnected!\n", client_num);
      break;
    // New client has connected
    case WStype_CONNECTED:
      {
        IPAddress ip = webSocket.remoteIP(client_num);
        Serial.printf("[%u] Connection from ", client_num);
        Serial.println(ip.toString());
      }
      break;

    // Handle text messages from client
    case WStype_TEXT:

      // Print out raw message
      Serial.printf("[%u] Received text: %s\n", client_num, payload);

      // Toggle relay
      if ( strcmp((char *)payload, "ON") == 0 ) {
        relay_state = 1;
        digitalWrite(relay_pin, relay_state);

      } else if ( strcmp((char *)payload, "OFF") == 0 ) {
        relay_state = 0;
        digitalWrite(relay_pin, relay_state);
      } else {
        Serial.println("[%u] Message not recognized");
      }
      break;

    // For everything else: do nothing
    case WStype_BIN:
    case WStype_ERROR:
    case WStype_FRAGMENT_TEXT_START:
    case WStype_FRAGMENT_BIN_START:
    case WStype_FRAGMENT:
    case WStype_FRAGMENT_FIN:
    default:
      break;
  }
}

// Callback: send homepage
void onIndexRequest(AsyncWebServerRequest *request) 
{
  IPAddress remote_ip = request->client()->remoteIP();
  Serial.println("[" + remote_ip.toString() +"] HTTP GET request of " + request->url());
  request->send(SPIFFS, "/index.html", "text/html");
}
// Callback: send style sheet
void onCSSRequest(AsyncWebServerRequest *request) {
  IPAddress remote_ip = request->client()->remoteIP();
  Serial.println("[" + remote_ip.toString() +"] HTTP GET request of " + request->url());
  request->send(SPIFFS, "/style.css", "text/css");
}

// Callback: send 404 if requested file does not exist
void onPageNotFound(AsyncWebServerRequest *request) 
{
  IPAddress remote_ip = request->client()->remoteIP();
  Serial.println("[" + remote_ip.toString() +"] HTTP GET request of " + request->url());
  request->send(404, "text/plain", "Not found");
}

/*******************************Main*****************************/
void setup() {
  // Init relay and turn off
  pinMode(relay_pin, OUTPUT);
  digitalWrite(relay_pin, LOW);
  // Start Serial port
  Serial.begin(115200);
  // Make sure we can read the file system
  if ( !SPIFFS.begin()) 
  {
    Serial.println("Error mounting SPIFFS");
    while (1);
  }

  // Start access point
  WiFi.softAP(ssid, password);

  // Print our IP address
  Serial.println();
  Serial.println("AP running");
  Serial.print("My IP address: ");
  Serial.println(WiFi.softAPIP());
  // On HTTP request for root, provide index.html file
  server.on("/", HTTP_GET, onIndexRequest);
  // On HTTP request for style sheet, provide style.css
  server.on("/style.css", HTTP_GET, onCSSRequest);
  // Handle requests for pages that do not exist
  server.onNotFound(onPageNotFound);
  // Start web server
  server.begin();
  // Start WebSocket server and assign callback
  webSocket.begin();
  webSocket.onEvent(onWebSocketEvent);
}
void loop() {
  webSocket.loop();
}

Code ESP32

<!DOCTYPE html>
<html>
    <head>
        <style>
            body{background:lightgray;background-image:url("back.png");}
            div
            { 
                background:white;display: block;position: absolute;
                width:50%;height:50%;left:25%;top:25%;
                border:3px solid #ff5400;border-radius: 100px;
            }
            button
            { 
                display:block;position:absolute;border:3px solid #ff5400;border-radius:100px;
                width:40%;height:40%;left:30%;top:30%;background:black;
                color:#ff5400;font-size:43px;font-weight:bolder;cursor:pointer;
            }
        </style>
        <script>
            var url = "ws://192.168.4.1:1337/";
            var buton;
            function  init()
            {
                bouton = document.getElementById("control");
                wsCnx(url);
            }
            function wsCnx()
            {
                wsk = new WebSocket(url);
                wsk.onopen = function (evt){ onOpen(evt)};
                wsk.onclose = function (evt){ onClose(evt)};
                wsk.onmessage = function (evt){ onMessage(evt)};
                wsk.onerror = function (evt){ onError(evt)};           
            }
            ///////lancer  à la cnx du socket 
            function onOpen()
            {
                console.log("Connecte!!");
            }
            ////////////////////////////////////////////////////////////////
            function onClose()
            {
                console.log("Deconnecte!!");
            }
            ////////////////////////////////////////////////////////////////
            function onError()
            {
                console.log("Erreur:"+evt.data);
            }
            ////////////////////////////////////////////////////////////////
            function onMessage()
            {
                console.log("Received: " + evt.data);
            }
            ////////////////////////////////////////////////////////////////
            function Envoi(msg)
            {
                msg=document.getElementById("control".value);
                console.log("Envoi:"+msg);
                wsk.send(msg);
            }
            ////////////////////////////////////////////////////////////////
            function toggolMe()
            {
                switch(document.getElementById("control").innerHTML)
                {
                    case "Relay Ouvert":
                        fermer();
                        break;
                    case "Relay Ferme":
                        ouvrir();
                        break;
                }
            }
            ////////////////////////////////////////////////////////////////
            function fermer()
            {
                 document.getElementById("control").innerHTML="Relay Ferme";
                 document.getElementById("control").value="OFF";
                 wsk.send("OFF");
            }
            ////////////////////////////////////////////////////////////////
            function ouvrir()
            {
                 document.getElementById("control").innerHTML="Relay Ouvert";
                 document.getElementById("control").value="ON";
                 wsk.send("ON");
            }
            window.addEventListener("load", init, false);

        </script>
    </head>
    <body>
        <div>
            <button id="control" onClick="toggolMe();">Relay Ouvert</button>
        </div>

    </body>
</html>

Montage

Les frais de transport ne sont pas inclus

Composant Quantité Prix(DTN TTC)
Esp32 1 45
Cable connexion femelle femelle (10) 1 0.2
Relai oneWay 1 7.800
Totale 53.000 DTN TTC
Reduction 5% -2.650
A payer 50.350 DTN TTC

Smart Innovation