Search code examples
javascripthtmlc++arduinoesp32

Stop while loop with HTML button arduino


Hello I am working on a project with an esp32 (IDE arduino) and I am trying to start / stop a while loop with 2 html button.

I have a webpage with html and js. When I click the button start, it send a command string and same for the stop : here is the part code of the js function.

    <p>
  <button type='button' id='BTN_START'>
    Start
  </button>
</p>

<p>
    <button type='button' id='BTN_STOP'>
      Stop
    </button>
  </p>

</span>

</body>

<script>
  var Socket;
  var isTransmitting = false;

  document.getElementById('BTN_START').addEventListener('click', StartTrans);
  document.getElementById('BTN_STOP').addEventListener('click', StopTrans);
  
  function init() {
    Socket = new WebSocket('ws://' + window.location.hostname + ':81/');
    Socket.onmessage = function(event) {
      processCommand(event);
    };
  }
  

  function StartTrans() {

    var msg = {command:'start_transmission'};
    Socket.send(JSON.stringify(msg));
  }

  function StopTrans() {

    var msg = {command:'stop_transmission'};
    Socket.send(JSON.stringify(msg));
  }

In the arduino when i receive the text "start_transmission" it runs the code inside the loop, but when I send the "stop_transmission" it does nothing.

here is the code : of the function to receive websocket event.

void webSocketEvent(byte num, WStype_t type, uint8_t * payload, size_t length) {
  switch (type) {
    case WStype_DISCONNECTED:
      Serial.println("Client " + String(num) + " disconnected");
      break;
    case WStype_CONNECTED:
      Serial.println("Client " + String(num) + " connected");
      break;
    case WStype_TEXT:
      String command = "";
      StaticJsonDocument<200> doc;
      DeserializationError error = deserializeJson(doc, payload, length);
      if (!error) {
        command = doc["command"].as<String>();
        Serial.println("Received command: " + command);
      }
      
         do
        {   
            int data = ShortRead();
            Serial.print("Force is: ");
            Serial.println(data);
            delay(1000);  
            if(command == "stop_transmission"){break;}    
         } while (command == "start_transmission")
         
        
        Serial.println("");
      break;
  }
}

I tried to use a volatile bool value that changed when I send the stop command, but it didn't work either.

Am I missing something ?

Thank you.


Solution

  • Problem is that you loop in do/while indefinitely without updating command.

    I use a boolean global var to enable reading after receiving start command and disable it after stop command.

    EDIT3 : move read data in loop and remove delay() to avoid blocking loop and missing socket packet.

    boolean startRead = false;
    unsigned long tw;
    
    void loop() {
      if (millis() - tw > 1000) {  //non blocking wait 1 sec
        if (startRead) {
          int data = ShortRead();
          Serial.print("Force is: ");
          Serial.println(data);
          tw = millis();           //raz time wait
        }
      }
    }
    
    void webSocketEvent(byte num, WStype_t type, uint8_t * payload, size_t length) {
      switch (type) {
        case WStype_DISCONNECTED:
          Serial.println("Client " + String(num) + " disconnected");
          break;
        case WStype_CONNECTED:
          Serial.println("Client " + String(num) + " connected");
          break;
        case WStype_TEXT:
          String command = "";
          StaticJsonDocument<200> doc;
          DeserializationError error = deserializeJson(doc, payload, length);
          if (!error) {
            command = doc["command"].as<String>();
            Serial.println("Received command: [" + command + "]");
          }
          
          if (command == "start_transmission") {
            startRead = true;
          }
          else if (command == "stop_transmission") {
            startRead = false;
          }
          break;
    
        default:
          Serial.println("Data type not managed");
      }
    }