ESP 32 dc motor with schedule

Good evening,
I have write this code with chat gpt and a bit of kwowlege :


```cpp
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebSrv.h>
#include <TimeLib.h>
#include <WiFiUdp.h>
#include <NTPClient.h>

#define MOTOR_PIN_DIR 16
#define MOTOR_PIN_PWM 17
#define LIMIT_SWITCH_PIN1 18
#define LIMIT_SWITCH_PIN2 19

const char* ssid = "";
const char* password = "";


AsyncWebServer server(80);
AsyncWebSocket ws("/ws");

const char* htmlHomePage PROGMEM = R"HTMLHOMEPAGE(
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body {
      background-color: white;
      padding: 10px;
    }
    h1, h2 {
      color: teal;
      text-align: center;
    }
    .clock-container {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 20px;
    }
    .clock {
      background-color: teal;
      color: white;
      font-size: 20px;
      padding: 10px 20px;
      border-radius: 5px;
      box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
    }
    .btn-container {
      display: flex;
      justify-content: space-around;
      margin-top: 20px;
    }
    .btn {
      background-color: black;
      color: white;
      font-size: 18px;
      padding: 10px 20px;
      border-radius: 5px;
      box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
    }
    .noselect {
      -webkit-touch-callout: none; /* iOS Safari */
      -webkit-user-select: none; /* Safari */
      -khtml-user-select: none; /* Konqueror HTML */
      -moz-user-select: none; /* Firefox */
      -ms-user-select: none; /* Internet Explorer/Edge */
      user-select: none; /* Non-prefixed version, currently supported by Chrome and Opera */
    }
  </style>
</head>
<body class="noselect">

<h1>Finestra casetta</h1>
<h2>Usare con maniera</h2>

<div class="clock-container">
  <div class="clock">
    <label for="startTime1">Orario di apertura:</label>
    <br>
    <input type="time" id="startTime1">
  </div>
</div>
<div class="clock-container">
  <div class="clock">
    <label for="startTime2">Orario di chiusura:</label>
    <br>
    <input type="time" id="startTime2">
  </div>
</div>

<div class="btn-container">
  <button class="btn" ontouchstart="openWindow()" ontouchend="stopAction()">Apri</button>
  <button class="btn" ontouchstart="closeWindow()" ontouchend="stopAction()">Chiudi</button>
</div>

<script>
  var webSocketUrl = "ws:\/\/" + window.location.hostname + "/ws";
  var websocket;

  function initWebSocket() {
    websocket = new WebSocket(webSocketUrl);
    websocket.onopen = function (event) {};
    websocket.onclose = function (event) {
      setTimeout(initWebSocket, 2000);
    };
    websocket.onmessage = function (event) {
      if (event.data === "stop") {
        stopAction();
      }
    };
  }

  // Aggiunta delle seguenti funzioni

function openWindow() {
  var startTime1 = document.getElementById("startTime1").value;
  webStartTime1 = startTime1;
  websocket.send("1#" + startTime1);
}


function closeWindow() {
  var startTime2 = document.getElementById("startTime2").value;
  webStartTime2 = startTime2;
  websocket.send("2#" + startTime2);
}

  function stopAction() {
    websocket.send("0");
  }

  window.onload = initWebSocket;
</script>
)HTMLHOMEPAGE";

String webStartTime1 = "";
String webStartTime2 = "";


int motor1StartHour = 8;
int motor1StartMinute = 0;
int motor2StartHour = 17;
int motor2StartMinute = 30;
int velocita_motore = 100;

bool limitSwitch1State = false;
bool limitSwitch2State = false;
bool windowMoving = false;
int windowDirection = 0; // 0: Stop, 1: Opening, 2: Closing

void rotateMotor(int motorDirection) {
  if (motorDirection == 1) {
    digitalWrite(MOTOR_PIN_DIR, HIGH);
    analogWrite(MOTOR_PIN_PWM, velocita_motore);
  } else if (motorDirection == 2) {
    digitalWrite(MOTOR_PIN_DIR, LOW);
    analogWrite(MOTOR_PIN_PWM, velocita_motore);
  } else {
    digitalWrite(MOTOR_PIN_DIR, LOW);
    analogWrite(MOTOR_PIN_PWM, 0);
  }
}

void processWindowAction(String action, int startHour, int startMinute) {
  if (action == "1") {
    motor1StartHour = webStartTime1.substring(0, 2).toInt();
    motor1StartMinute = webStartTime1.substring(3).toInt();
    rotateMotor(1); // Apri la finestra
    windowMoving = true;
    windowDirection = 1;
  } else if (action == "2") {
    motor2StartHour = webStartTime2.substring(0, 2).toInt();
    motor2StartMinute = webStartTime2.substring(3).toInt();
    rotateMotor(2); // Chiudi la finestra
    windowMoving = true;
    windowDirection = 2;
  } else {
    rotateMotor(0); // Ferma il motore
    windowMoving = false;
    windowDirection = 0;
  }
}


void handleRoot(AsyncWebServerRequest* request) {
  request->send_P(200, "text/html", htmlHomePage);
}

void handleNotFound(AsyncWebServerRequest* request) {
  request->send(404, "text/plain", "File Not Found");
}

void onWebSocketEvent(AsyncWebSocket* server,
                      AsyncWebSocketClient* client,
                      AwsEventType type,
                      void* arg,
                      uint8_t* data,
                      size_t len) {
  switch (type) {
    case WS_EVT_CONNECT:
      Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
      break;
    case WS_EVT_DISCONNECT:
      Serial.printf("WebSocket client #%u disconnected\n", client->id());
      processWindowAction("0", 0, 0);
      break;
    case WS_EVT_DATA:
      AwsFrameInfo* info;
      info = (AwsFrameInfo*)arg;
      if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
        std::string myData = "";
        myData.assign((char*)data, len);

        String action = String(myData.c_str()).substring(0, 1);
        String startTime = String(myData.c_str()).substring(2);
        int startHour = startTime.substring(0, 2).toInt();
        int startMinute = startTime.substring(3).toInt();
        processWindowAction(action, startHour, startMinute);
      }
      break;
  }
}

void setup() {
  Serial.begin(115200);

  pinMode(MOTOR_PIN_DIR, OUTPUT);
  pinMode(MOTOR_PIN_PWM, OUTPUT);
  pinMode(LIMIT_SWITCH_PIN1, INPUT_PULLUP);
  pinMode(LIMIT_SWITCH_PIN2, INPUT_PULLUP);

  rotateMotor(0); // Ferma il motore

  WiFi.softAP(ssid, password);

  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);

  server.on("/", HTTP_GET, handleRoot);
  server.onNotFound(handleNotFound);

  ws.onEvent(onWebSocketEvent);
  server.addHandler(&ws);

  server.begin();
}

void loop() {
  ws.cleanupClients();

  int currentHour = hour();
  int currentMinute = minute();

  if (currentHour == motor1StartHour && currentMinute == motor1StartMinute && windowMoving && windowDirection == 1) {
    rotateMotor(0); // Ferma il motore
    windowMoving = false;
    windowDirection = 0;
  } else if (currentHour == motor2StartHour && currentMinute == motor2StartMinute && windowMoving && windowDirection == 2) {
    rotateMotor(0); // Ferma il motore
    windowMoving = false;
    windowDirection = 0;
  }

  bool newLimitSwitch1State = digitalRead(LIMIT_SWITCH_PIN1);
  bool newLimitSwitch2State = digitalRead(LIMIT_SWITCH_PIN2);

  if (newLimitSwitch1State != limitSwitch1State && newLimitSwitch1State == HIGH) {
    if (windowMoving && windowDirection == 1) {
      rotateMotor(2); // Inverti la direzione del motore
      windowDirection = 2;
    }
  }

  if (newLimitSwitch2State != limitSwitch2State && newLimitSwitch2State == HIGH) {
    if (windowMoving && windowDirection == 2) {
      rotateMotor(1); // Inverti la direzione del motore
      windowDirection = 1;
    }
  }

  limitSwitch1State = newLimitSwitch1State;
  limitSwitch2State = newLimitSwitch2State;

  delay(100);
}

The web interfaces is good, i like to add some features but it's ok, why the schedule does not work? If Ipress one button dc motor goes forward and backward but if Iuse the time i doesn't work.

the connection are correct because with button it work so the problem is in the code.
Thank you so much

Please point out the lines that are meant to handle the scheduled events part that isn't working yet.

Hhave you printed out curretnHour and curretnMinjte to see if they are plausible? If this is what you mean by time failing, if statements aren't getting executed perhaps.

a7

You are comparing hour and minute which must equal to exact numbers

me personal I prefer to calculate minutesOfDay = hours * 60 + minutes
and then compare equal or greater >=

For analysing I would printout the values of the variables itself and if you do calculations
the results of the calculations
with each inbetween results that is one calculation-step

you are using

  int currentHour = hour();
  int currentMinute = minute();

have you ever checked to what values hour() and minute() are set?

You are including several libraries

but the code seem to not use them.

I guess 99,9% chatGPT and 0,1% knowledge

I guess this is because you used chatGPT and your prompt to describe the wanted functionality was not precise enough.

If your prompt to chatGPT is too foggy
this will happen:

Good evening, if you didn't want to explain or help me, just don't answer, my knowledge of arduino is very limited due to limited time, having the need for this project, I thought that gpt chat could help me and in the meantime learn, I tried and tried again to vary the code and enter it on chat but I didn't get good results. Even if we were to stop at 2018 to open a window up to an endstop, I think that's enough. Anyway I will try again thanks for your invaluable help.

I think the part of the code that doesn'n work is that:

In my idea the window have to open in the set time but nothing happen. I read the code and I think is good, the function should be correct.
Thanks for your answer

I'm sure that checking this

by printing the values to the serial monitor
is worth the effort.

This version does print the values

  int currentHour = hour();
  int currentMinute = minute();
  Serial.print("currentHour=");
  Serial.print(currentHour);
  Serial.print("  currentMinute=");
  Serial.println(currentMinute);

all the time repeatedly to the serial monitor

```cpp
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebSrv.h>
#include <TimeLib.h>
#include <WiFiUdp.h>
#include <NTPClient.h>

#define MOTOR_PIN_DIR 16
#define MOTOR_PIN_PWM 17
#define LIMIT_SWITCH_PIN1 18
#define LIMIT_SWITCH_PIN2 19

const char* ssid = "MARTIN ROUTER KING";
const char* password = "Francescomonicamarino1999";


AsyncWebServer server(80);
AsyncWebSocket ws("/ws");

const char* htmlHomePage PROGMEM = R"HTMLHOMEPAGE(
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body {
      background-color: white;
      padding: 10px;
    }
    h1, h2 {
      color: teal;
      text-align: center;
    }
    .clock-container {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 20px;
    }
    .clock {
      background-color: teal;
      color: white;
      font-size: 20px;
      padding: 10px 20px;
      border-radius: 5px;
      box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
    }
    .btn-container {
      display: flex;
      justify-content: space-around;
      margin-top: 20px;
    }
    .btn {
      background-color: black;
      color: white;
      font-size: 18px;
      padding: 10px 20px;
      border-radius: 5px;
      box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
    }
    .noselect {
      -webkit-touch-callout: none; /* iOS Safari */
      -webkit-user-select: none; /* Safari */
      -khtml-user-select: none; /* Konqueror HTML */
      -moz-user-select: none; /* Firefox */
      -ms-user-select: none; /* Internet Explorer/Edge */
      user-select: none; /* Non-prefixed version, currently supported by Chrome and Opera */
    }
  </style>
</head>
<body class="noselect">

<h1>Finestra casetta</h1>
<h2>Usare con maniera</h2>

<div class="clock-container">
  <div class="clock">
    <label for="startTime1">Orario di apertura:</label>
    <br>
    <input type="time" id="startTime1">
  </div>
</div>
<div class="clock-container">
  <div class="clock">
    <label for="startTime2">Orario di chiusura:</label>
    <br>
    <input type="time" id="startTime2">
  </div>
</div>

<div class="btn-container">
  <button class="btn" ontouchstart="openWindow()" ontouchend="stopAction()">Apri</button>
  <button class="btn" ontouchstart="closeWindow()" ontouchend="stopAction()">Chiudi</button>
</div>

<script>
  var webSocketUrl = "ws:\/\/" + window.location.hostname + "/ws";
  var websocket;

  function initWebSocket() {
    websocket = new WebSocket(webSocketUrl);
    websocket.onopen = function (event) {};
    websocket.onclose = function (event) {
      setTimeout(initWebSocket, 2000);
    };
    websocket.onmessage = function (event) {
      if (event.data === "stop") {
        stopAction();
      }
    };
  }

  // Aggiunta delle seguenti funzioni

function openWindow() {
  var startTime1 = document.getElementById("startTime1").value;
  webStartTime1 = startTime1;
  websocket.send("1#" + startTime1);
}


function closeWindow() {
  var startTime2 = document.getElementById("startTime2").value;
  webStartTime2 = startTime2;
  websocket.send("2#" + startTime2);
}

  function stopAction() {
    websocket.send("0");
  }

  window.onload = initWebSocket;
</script>
)HTMLHOMEPAGE";

String webStartTime1 = "";
String webStartTime2 = "";


int motor1StartHour = 8;
int motor1StartMinute = 0;
int motor2StartHour = 17;
int motor2StartMinute = 30;
int velocita_motore = 100;

bool limitSwitch1State = false;
bool limitSwitch2State = false;
bool windowMoving = false;
int windowDirection = 0; // 0: Stop, 1: Opening, 2: Closing

void rotateMotor(int motorDirection) {
  if (motorDirection == 1) {
    digitalWrite(MOTOR_PIN_DIR, HIGH);
    analogWrite(MOTOR_PIN_PWM, velocita_motore);
  } else if (motorDirection == 2) {
    digitalWrite(MOTOR_PIN_DIR, LOW);
    analogWrite(MOTOR_PIN_PWM, velocita_motore);
  } else {
    digitalWrite(MOTOR_PIN_DIR, LOW);
    analogWrite(MOTOR_PIN_PWM, 0);
  }
}

void processWindowAction(String action, int startHour, int startMinute) {
  if (action == "1") {
    motor1StartHour = webStartTime1.substring(0, 2).toInt();
    motor1StartMinute = webStartTime1.substring(3).toInt();
    rotateMotor(1); // Apri la finestra
    windowMoving = true;
    windowDirection = 1;
  } else if (action == "2") {
    motor2StartHour = webStartTime2.substring(0, 2).toInt();
    motor2StartMinute = webStartTime2.substring(3).toInt();
    rotateMotor(2); // Chiudi la finestra
    windowMoving = true;
    windowDirection = 2;
  } else {
    rotateMotor(0); // Ferma il motore
    windowMoving = false;
    windowDirection = 0;
  }
}


void handleRoot(AsyncWebServerRequest* request) {
  request->send_P(200, "text/html", htmlHomePage);
}

void handleNotFound(AsyncWebServerRequest* request) {
  request->send(404, "text/plain", "File Not Found");
}

void onWebSocketEvent(AsyncWebSocket* server,
                      AsyncWebSocketClient* client,
                      AwsEventType type,
                      void* arg,
                      uint8_t* data,
                      size_t len) {
  switch (type) {
    case WS_EVT_CONNECT:
      Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
      break;
    case WS_EVT_DISCONNECT:
      Serial.printf("WebSocket client #%u disconnected\n", client->id());
      processWindowAction("0", 0, 0);
      break;
    case WS_EVT_DATA:
      AwsFrameInfo* info;
      info = (AwsFrameInfo*)arg;
      if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
        std::string myData = "";
        myData.assign((char*)data, len);

        String action = String(myData.c_str()).substring(0, 1);
        String startTime = String(myData.c_str()).substring(2);
        int startHour = startTime.substring(0, 2).toInt();
        int startMinute = startTime.substring(3).toInt();
        processWindowAction(action, startHour, startMinute);
      }
      break;
  }
}

void setup() {
  Serial.begin(115200);

  pinMode(MOTOR_PIN_DIR, OUTPUT);
  pinMode(MOTOR_PIN_PWM, OUTPUT);
  pinMode(LIMIT_SWITCH_PIN1, INPUT_PULLUP);
  pinMode(LIMIT_SWITCH_PIN2, INPUT_PULLUP);

  rotateMotor(0); // Ferma il motore

  WiFi.softAP(ssid, password);

  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);

  server.on("/", HTTP_GET, handleRoot);
  server.onNotFound(handleNotFound);

  ws.onEvent(onWebSocketEvent);
  server.addHandler(&ws);

  server.begin();
}

void loop() {
  ws.cleanupClients();

  int currentHour = hour();
  int currentMinute = minute();
  Serial.print("currentHour=");
  Serial.print(currentHour);
  Serial.print("  currentMinute=");
  Serial.println(currentMinute);
  
  if (currentHour == motor1StartHour && currentMinute == motor1StartMinute && windowMoving && windowDirection == 1) {
    rotateMotor(0); // Ferma il motore
    windowMoving = false;
    windowDirection = 0;
  } else if (currentHour == motor2StartHour && currentMinute == motor2StartMinute && windowMoving && windowDirection == 2) {
    rotateMotor(0); // Ferma il motore
    windowMoving = false;
    windowDirection = 0;
  }

  bool newLimitSwitch1State = digitalRead(LIMIT_SWITCH_PIN1);
  bool newLimitSwitch2State = digitalRead(LIMIT_SWITCH_PIN2);

  if (newLimitSwitch1State != limitSwitch1State && newLimitSwitch1State == HIGH) {
    if (windowMoving && windowDirection == 1) {
      rotateMotor(2); // Inverti la direzione del motore
      windowDirection = 2;
    }
  }

  if (newLimitSwitch2State != limitSwitch2State && newLimitSwitch2State == HIGH) {
    if (windowMoving && windowDirection == 2) {
      rotateMotor(1); // Inverti la direzione del motore
      windowDirection = 1;
    }
  }

  limitSwitch1State = newLimitSwitch1State;
  limitSwitch2State = newLimitSwitch2State;

  delay(100);
}

and this version prints the values only once every second

// MACRO-START * MACRO-START * MACRO-START * MACRO-START * MACRO-START * MACRO-START *
// a detailed explanation how these macros work is given in this tutorial
// https://forum.arduino.cc/t/comfortable-serial-debug-output-short-to-write-fixed-text-name-and-content-of-any-variable-code-example/888298
#define dbg(myFixedText, variableName) \
  Serial.print( F(#myFixedText " "  #variableName"=") ); \
  Serial.println(variableName);

#define dbgi(myFixedText, variableName,timeInterval) \
  { \
    static unsigned long intervalStartTime; \
    if ( millis() - intervalStartTime >= timeInterval ){ \
      intervalStartTime = millis(); \
      Serial.print( F(#myFixedText " "  #variableName"=") ); \
      Serial.println(variableName); \
    } \
  }

#define dbgc(myFixedText, variableName) \
  { \
    static long lastState; \
    if ( lastState != variableName ){ \
      Serial.print( F(#myFixedText " "  #variableName" changed from ") ); \
      Serial.print(lastState); \
      Serial.print( F(" to ") ); \
      Serial.println(variableName); \
      lastState = variableName; \
    } \
  }

#define dbgcf(myFixedText, variableName) \
  { \
    static float lastState; \
    if ( lastState != variableName ){ \
      Serial.print( F(#myFixedText " "  #variableName" changed from ") ); \
      Serial.print(lastState); \
      Serial.print( F(" to ") ); \
      Serial.println(variableName); \
      lastState = variableName; \
    } \
  }
// MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END *


```cpp
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebSrv.h>
#include <TimeLib.h>
#include <WiFiUdp.h>
#include <NTPClient.h>

#define MOTOR_PIN_DIR 16
#define MOTOR_PIN_PWM 17
#define LIMIT_SWITCH_PIN1 18
#define LIMIT_SWITCH_PIN2 19

const char* ssid = "MARTIN ROUTER KING";
const char* password = "Francescomonicamarino1999";


AsyncWebServer server(80);
AsyncWebSocket ws("/ws");

const char* htmlHomePage PROGMEM = R"HTMLHOMEPAGE(
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body {
      background-color: white;
      padding: 10px;
    }
    h1, h2 {
      color: teal;
      text-align: center;
    }
    .clock-container {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 20px;
    }
    .clock {
      background-color: teal;
      color: white;
      font-size: 20px;
      padding: 10px 20px;
      border-radius: 5px;
      box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
    }
    .btn-container {
      display: flex;
      justify-content: space-around;
      margin-top: 20px;
    }
    .btn {
      background-color: black;
      color: white;
      font-size: 18px;
      padding: 10px 20px;
      border-radius: 5px;
      box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
    }
    .noselect {
      -webkit-touch-callout: none; /* iOS Safari */
      -webkit-user-select: none; /* Safari */
      -khtml-user-select: none; /* Konqueror HTML */
      -moz-user-select: none; /* Firefox */
      -ms-user-select: none; /* Internet Explorer/Edge */
      user-select: none; /* Non-prefixed version, currently supported by Chrome and Opera */
    }
  </style>
</head>
<body class="noselect">

<h1>Finestra casetta</h1>
<h2>Usare con maniera</h2>

<div class="clock-container">
  <div class="clock">
    <label for="startTime1">Orario di apertura:</label>
    <br>
    <input type="time" id="startTime1">
  </div>
</div>
<div class="clock-container">
  <div class="clock">
    <label for="startTime2">Orario di chiusura:</label>
    <br>
    <input type="time" id="startTime2">
  </div>
</div>

<div class="btn-container">
  <button class="btn" ontouchstart="openWindow()" ontouchend="stopAction()">Apri</button>
  <button class="btn" ontouchstart="closeWindow()" ontouchend="stopAction()">Chiudi</button>
</div>

<script>
  var webSocketUrl = "ws:\/\/" + window.location.hostname + "/ws";
  var websocket;

  function initWebSocket() {
    websocket = new WebSocket(webSocketUrl);
    websocket.onopen = function (event) {};
    websocket.onclose = function (event) {
      setTimeout(initWebSocket, 2000);
    };
    websocket.onmessage = function (event) {
      if (event.data === "stop") {
        stopAction();
      }
    };
  }

  // Aggiunta delle seguenti funzioni

function openWindow() {
  var startTime1 = document.getElementById("startTime1").value;
  webStartTime1 = startTime1;
  websocket.send("1#" + startTime1);
}


function closeWindow() {
  var startTime2 = document.getElementById("startTime2").value;
  webStartTime2 = startTime2;
  websocket.send("2#" + startTime2);
}

  function stopAction() {
    websocket.send("0");
  }

  window.onload = initWebSocket;
</script>
)HTMLHOMEPAGE";

String webStartTime1 = "";
String webStartTime2 = "";


int motor1StartHour = 8;
int motor1StartMinute = 0;
int motor2StartHour = 17;
int motor2StartMinute = 30;
int velocita_motore = 100;

bool limitSwitch1State = false;
bool limitSwitch2State = false;
bool windowMoving = false;
int windowDirection = 0; // 0: Stop, 1: Opening, 2: Closing

void rotateMotor(int motorDirection) {
  if (motorDirection == 1) {
    digitalWrite(MOTOR_PIN_DIR, HIGH);
    analogWrite(MOTOR_PIN_PWM, velocita_motore);
  } else if (motorDirection == 2) {
    digitalWrite(MOTOR_PIN_DIR, LOW);
    analogWrite(MOTOR_PIN_PWM, velocita_motore);
  } else {
    digitalWrite(MOTOR_PIN_DIR, LOW);
    analogWrite(MOTOR_PIN_PWM, 0);
  }
}

void processWindowAction(String action, int startHour, int startMinute) {
  if (action == "1") {
    motor1StartHour = webStartTime1.substring(0, 2).toInt();
    motor1StartMinute = webStartTime1.substring(3).toInt();
    rotateMotor(1); // Apri la finestra
    windowMoving = true;
    windowDirection = 1;
  } else if (action == "2") {
    motor2StartHour = webStartTime2.substring(0, 2).toInt();
    motor2StartMinute = webStartTime2.substring(3).toInt();
    rotateMotor(2); // Chiudi la finestra
    windowMoving = true;
    windowDirection = 2;
  } else {
    rotateMotor(0); // Ferma il motore
    windowMoving = false;
    windowDirection = 0;
  }
}


void handleRoot(AsyncWebServerRequest* request) {
  request->send_P(200, "text/html", htmlHomePage);
}

void handleNotFound(AsyncWebServerRequest* request) {
  request->send(404, "text/plain", "File Not Found");
}

void onWebSocketEvent(AsyncWebSocket* server,
                      AsyncWebSocketClient* client,
                      AwsEventType type,
                      void* arg,
                      uint8_t* data,
                      size_t len) {
  switch (type) {
    case WS_EVT_CONNECT:
      Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
      break;
    case WS_EVT_DISCONNECT:
      Serial.printf("WebSocket client #%u disconnected\n", client->id());
      processWindowAction("0", 0, 0);
      break;
    case WS_EVT_DATA:
      AwsFrameInfo* info;
      info = (AwsFrameInfo*)arg;
      if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
        std::string myData = "";
        myData.assign((char*)data, len);

        String action = String(myData.c_str()).substring(0, 1);
        String startTime = String(myData.c_str()).substring(2);
        int startHour = startTime.substring(0, 2).toInt();
        int startMinute = startTime.substring(3).toInt();
        processWindowAction(action, startHour, startMinute);
      }
      break;
  }
}

void setup() {
  Serial.begin(115200);

  pinMode(MOTOR_PIN_DIR, OUTPUT);
  pinMode(MOTOR_PIN_PWM, OUTPUT);
  pinMode(LIMIT_SWITCH_PIN1, INPUT_PULLUP);
  pinMode(LIMIT_SWITCH_PIN2, INPUT_PULLUP);

  rotateMotor(0); // Ferma il motore

  WiFi.softAP(ssid, password);

  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);

  server.on("/", HTTP_GET, handleRoot);
  server.onNotFound(handleNotFound);

  ws.onEvent(onWebSocketEvent);
  server.addHandler(&ws);

  server.begin();
}

void loop() {
  ws.cleanupClients();

  int currentHour = hour();
  int currentMinute = minute();

  dbgi("Top of loop",currentHour,1000);
  dbgi("Top of loop",currentMinute,1000);
  
  if (currentHour == motor1StartHour && currentMinute == motor1StartMinute && windowMoving && windowDirection == 1) {
    rotateMotor(0); // Ferma il motore
    windowMoving = false;
    windowDirection = 0;
  } else if (currentHour == motor2StartHour && currentMinute == motor2StartMinute && windowMoving && windowDirection == 2) {
    rotateMotor(0); // Ferma il motore
    windowMoving = false;
    windowDirection = 0;
  }

  bool newLimitSwitch1State = digitalRead(LIMIT_SWITCH_PIN1);
  bool newLimitSwitch2State = digitalRead(LIMIT_SWITCH_PIN2);

  if (newLimitSwitch1State != limitSwitch1State && newLimitSwitch1State == HIGH) {
    if (windowMoving && windowDirection == 1) {
      rotateMotor(2); // Inverti la direzione del motore
      windowDirection = 2;
    }
  }

  if (newLimitSwitch2State != limitSwitch2State && newLimitSwitch2State == HIGH) {
    if (windowMoving && windowDirection == 2) {
      rotateMotor(1); // Inverti la direzione del motore
      windowDirection = 1;
    }
  }

  limitSwitch1State = newLimitSwitch1State;
  limitSwitch2State = newLimitSwitch2State;

  delay(100);
}

best regards Stefan

Add Serial.print() statements to check the values of key variables, and to confirm that your program flow is what you expect.

The part you pulled out is like flying blind. You must confirm that the steps are what you meant to happen. The final arbiter of what is happening is the running code.

a7

Your web page might "look" okay as it is, but you do not close the HTML markup, which will cause problems if you open another HTML markup.

You are missing (at least) this:

</html>

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.