1

I've been trying to run the following esp32 LED PWM code to change the LED's brightness, and show the current PWM duty on the webpage, but the PWM values on the webpage won't change until I hit the submit button twice.

#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>
WebServer ser(80);
int s=0;
String k;



String iso()
{
  k="<p style=\"text-align: center;\"><strong><font size=\"9\">LED PWM</font></strong><font size=\"3\"></font><FORM action=\"/\" method=\"post\"><input type=\"text\" name=\"duty\"><br> <input type=\"submit\" value=\"Submit\">Cureent Duty=";
  k=k+s;
  k=k+"</p>";

  return k;
}

void root()
{
  iso();
  ser.send(200, "text/html", iso());

  if (ser.hasArg("duty")) 
  {
      iso();
      s=ser.arg("duty").toInt();  
      ledcWrite(4, s);
      iso();
      ser.send(200, "text/html", iso());
  }
}





void setup() {
  Serial.begin(9600);
  ledcAttachPin(33, 4);
  ledcSetup(4, 5000, 8);
  WiFi.begin("ssid", "pass");
  Serial.print("\nConnecting To WiFi");
  while (WiFi.status()!=WL_CONNECTED)
  {

    Serial.printf("\n.");
  }
  Serial.print("\nConnected");

  ser.on("/", root);
  ser.begin(80);
}



void loop() {
  ser.handleClient();
}

Here's a GIF addressing the issue

Issue

  • upvote for visually demonstrating the issue – jsotola Jun 11 at 16:11
3

When the client sends you a request, you should answer only once. Your root() function attempts to answer twice whenever the request contains the argument “duty”. The client will not handle a duplicate response to a single request.

Here is your root() function:

void root()
{
  iso();
  ser.send(200, "text/html", iso());  // ← first response

  if (ser.hasArg("duty"))
  {
      iso();
      s=ser.arg("duty").toInt();
      ledcWrite(4, s);
      iso();
      ser.send(200, "text/html", iso());  // ← second response
  }
}

You may notice that the first response was sent before updating the duty cycle.

The proper way to handle the request is to first handle the request parameters, if any, then send the response:

void root()
{
  if (ser.hasArg("duty")) {
    s = ser.arg("duty").toInt();
    ledcWrite(4, s);
  }
  ser.send(200, "text/html", iso());  // ← only sent once
}

As a side note, there is absolutely no need to build the response five times (you have five calls to iso() within root()) when you only need it once!

  • I'm such an idiot ! ;P thanks a lot. – FOX Jun 11 at 8:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.