ESP32-Wert aus URL übernehmen

Hallo mal wieder,
bin überm Bau einer Lüfterreglung. Eigentlich wollte ich einen Wemos D1 dazu nutzen. Leider fangen die Lüfter mit PWM an zu pfeifen. Beim EP32 DEV ist das nicht der Fall. Nun versuche ich verzweifelt das Programm umzustellen auf ESP32. Über ein Input Feld möchte ich die tempMax ändern können und da klemmt es. Der neue Wert wird nicht übernommen bzw. es wird eine 0 reingeschrieben. Ich denke an es liegt hier dran:
Zeile 186: String text1 = ("TEXT1");
tempMax = text1.toInt();
Das Programm ist teilweise aus Beispielen übernommen.
Wär nett wenn jemand einen Tipp hätte. Hier mal der Sketch.
Bitte nicht zu sehr über meine Fehler schimpfen :pensive:

[code]
#include <OneWire.h>
#include <DallasTemperature.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>

WiFiServer server(80);            

// Variable to store the HTTP request
String header;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

////////////////////////////////////////////////////////
// WiFi connect
////////////////////////////////////////////////////////

//Enter your SSID and PASSWORD
const char* ssid = "xxxx";
const char* password = "xxxx";

// Output Status
String luefterState = "auto";
// definition of PWM pins:
const int luefter = 16;  // 16 corresponds to GPIO16, sets fan1(luefter) to GPIO16
////////////////////////////////////////////////////////
// Temperatur Sensor 
////////////////////////////////////////////////////////
// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor 
DallasTemperature sensors(&oneWire);

////////////////////////////////////////////////////////
// PWM Werte setzen
////////////////////////////////////////////////////////

// setting PWM properties
const int freq1 = 200;                //frequency fan1(luefter)
const int resolution = 8;             //bit-resolution
const int pwmChannel1 = 0;            //inner PWM-Channels
//FanSpeed Variablen
int fanSpeed = 0;                     //basic fanspeed(set to 0)
int tempMin = 22;                     //definition of minimum temperature
int tempMax = 28;                     //definition of maximum temperature

void setup() {
    Serial.begin(115200);                               //baud rate
    Serial.println("Ready");
    // configure PWM functionalitites
    ledcSetup(pwmChannel1, freq1, resolution);            
    // channelvariable for GPIO-control
    ledcAttachPin(luefter, pwmChannel1);
    // temperaturesensor start
    sensors.begin();
    
    // initializing Output variables
    pinMode(luefter, OUTPUT);
    // Set outputs to LOW
    pinMode(luefter, LOW);
    // connection to Network, for example WLAN 
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    // Output of the connection options
    Serial.println("");
    Serial.println("WiFi connected.");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());

    // start web server
    server.begin();
}
void loop(void) {

    // read temperature sensor
    sensors.requestTemperatures();                         //Request to temperature sensor
    float temperatureC = sensors.getTempCByIndex(0);       //sets temperatureC to input value
    String StemperatureC;                                  //StemperatureC for Webserver, (actually Value)
    StemperatureC = String(temperatureC);                  //cast temperature variable too String Casten for output an the Webserver
    //Umwandeln tempMax in string
    int tempm = tempMax;      
    String Stempm;
    Stempm = String(tempm);
    
    Serial.print(temperatureC);
    Serial.println("ºC");
    delay(1000);

    //------------------------------------------------------------------------
   WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    currentTime = millis();
    previousTime = currentTime;
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected() && currentTime - previousTime <= timeoutTime) {  // loop while the client's connected
      currentTime = millis();
      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
        header += c;
        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) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

                        // turns Luefter status   auto -> on ->  off -> auto...
                        if (header.indexOf("GET /1/on") >= 0) {                   //fan1, Url-extension
                            Serial.println("L\x81fter 1 on");                     //print "fan1 on" to output
                            luefterState = "on";                                 //sets fan1state "on"
                        } 
                          else if (header.indexOf("GET /1/off") >= 0) {           //fan1
                            Serial.println("L\x81fter 1 off");
                            luefterState = "off";
                        } else if (header.indexOf("GET /1/auto") >= 0) {          //fan1
                            Serial.println("L\x81fter 1 auto");
                            luefterState = "auto";
                        }                       
                        // Display the HTML web page
                        //String SendHTML(int tempMax);
                        client.println("<!DOCTYPE html><html>");
                        client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" http-equiv=\"refresh\" content=\"2\">");
                        client.println("<link rel=\"icon\" href=\"data:,\">");
                        client.println("<style>html { font-family: Helvetica; background-color:#c9f128; display: inline-block; margin: 0px auto; text-align: center;}");
                        client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
                        client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
                        client.println(".button2 {background-color: #555555; border: none; color: white; padding: 16px 40px;");
                        client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
                        client.println(".button3 {background-color: #D8D800;border: none; color: white; padding: 16px 40px;");
                        client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}</style></head>");
                                                                 
                        // Web Page Heading
                        client.println("<body><h1>Test ESP32</h1>");
                        // current temperature
                        client.println("<h1>Temperatur: " + StemperatureC + "&degC</h1>");
                        // Display current state, and ON/OFF/AUTO buttons for fan1(luefter)  
                        client.println("<p>L&uumlfter1 - Status " + luefterState + "</p>");

                        // If the luefterState is off, it displays the auto button       
                        if (luefterState == "off") {
                            client.println("<p><a href=\"/1/auto\"><button class=\"button button3\">AUTO</button></a></p>");
                            luefterState = "off";
                        }
                        // If the luefterState is auto, it displays the on button
                        else if (luefterState == "auto") {
                            client.println("<p><a href=\"/1/on\"><button class=\"button \">ON</button></a></p>");
                            luefterState = "auto";
                        }
                        // If the luefterState is on, it displays the off button
                        else {
                            client.println("<p><a href=\"/1/off\"><button class=\"button button2\">OFF</button></a></p>");
                            luefterState = "on";
                        }
                        client.print("<h1>TemperaturMax: " + Stempm + "&degC</h1>");
                        //client.print("<form action='/buton' method='POST'>");                      
                        client.print("<form action=\"/get\">"); //added a form to take a text input and send a get request.
                        client.print("<p>TempMax &aumlndern</p>");
                        client.print( "<input type='text1' name='TEXT1' value='");
                        client.print(tempMax);
                        client.print("'size='6'>");
                        client.print("<input type='submit' name='SUBMIT' value='senden'>");
                        
                        String text1 = ("TEXT1");
                        tempMax = text1.toInt();
                        
                        Serial.println(tempMax);
                        client.print("</form><br>");                        
                        client.println("</body></html>");   

                        // The HTTP response ends with another blank line
                        client.println();
                        // Break out of the while loop
                        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
        }
      }
    }
        // Clear the header variable
        header = "";
        // Close the connection
        client.stop();
        Serial.println("Client disconnected.");
        Serial.println("");
    }
    //-------------------------------------------------  
      // fan1(Luefter 1) state requesting
    if (luefterState == "auto")                         // auto = automatical PWM regulation
    {
        if (temperatureC < tempMin)
        {
            //Temperature below tempMin fan1 off
            fanSpeed = 0;
            Serial.println("L1 = auto, Temp < " + String(tempMin) + ", fanSpeed= " + String(fanSpeed));                                     //print in serial interface the temperature,the current terms and the fan speed
            ledcWrite(pwmChannel1, fanSpeed);
        }
        else if (temperatureC >= tempMin && temperatureC < tempMax)
        {
            //Temperature from tempMin fan1 20% -80%
            //0...255 = 256 values because of 8-bit
            // 32 means 20% of 256 values and 80% means 216
            //fanSpeed = map(tempC, tempMin, tempMax, 32, 255);
            fanSpeed = map(temperatureC, tempMin, tempMax, 32,216);
            Serial.println("L1 = auto, Temp > " + String(tempMin) + " + Temp < " + String(tempMax) + ", fanSpeed= " + String(fanSpeed));    //print in serial interface the temperature,the current terms and the fan speed
            ledcWrite(pwmChannel1, fanSpeed);
        }
        else if (temperatureC >= tempMax)
        {
            //Temperature from temMax fan1 100%
            fanSpeed = 255;                                                                                                                 //fanSpeed 100% means 255
            Serial.println("L1 = auto, Temp > " + String(tempMax) + ", fanSpeed= " + String(fanSpeed));                                     //print in serial interface the temperature,the current terms and the fan speed
            ledcWrite(pwmChannel1, fanSpeed);
        }
    }
    else if (luefterState == "off")  // no terms -> fan 1 off
    {
        fanSpeed = 0;
        Serial.println("L1 = off , fanSpeed= " + String(fanSpeed));
        ledcWrite(pwmChannel1, fanSpeed);

    }
    else if (luefterState == "on")  // no terms -> fan 1 on
    {
        fanSpeed = 255;
        Serial.println("L1 = on , fanSpeed= " + String(fanSpeed));
        ledcWrite(pwmChannel1, fanSpeed);
    } 
}
[/code]

Du verwendest die falsche Ausgangsbasis. Am ESP32 baut man den HTTP Header nicht mehr selber zusammen.

Auch hat der Webserver Funktionalitäten um Parameter direkt auszulesen die man über ein form übermittelt hat.

ich mach das so:

https://werner.rothschopf.net/microcontroller/202108_esp_generic_webserver_en.htm

Danke für Antwort. Hab mir den Link mal angeschaut und die Demo. Das ist aber ne Nummer zu groß für mich. Da steig ich nicht dahinter wie ich das mit meinen Vorhaben zusammen bringen soll.

schau dir wenigstens das IDE Example Webserver / HelloServer an.

Das zeigt wie der Webserver einen Text ausgibt, und wie Parameter gelesen werden.

Die wesentlichen Infos stehen in der Webserver.h

// Dein Parameter sei http://url?wert=15
// Deim Webserver im Sketch heißt server
int x;
if (server.hasArg("wert")) {  // gibt es einen Parameter mit dem Namen wert?
  x = server.arg("wert").toInt(); 
 // mache was mit der Zahl
}

Du kannst Dir auch mal die Seiten von Fips anschauen.

Gruß Tommy

Vielen Dank für eure Tipps. Leider hab ich Blödmann einen großen Fehler gemacht.
Statt "WebServer server(80);" hatte ich "WiFiServer server(80); benutzt. Ich werde jetzt nochmal von vorn beginnen und melde mich wieder.

Bei Deinem Programm aus #1 habe ich DallasTemperature kommentiert und durch eine Zufallszahl ersetzt. Sonst habe ich ein paar Änderungen vorgenommen, um die maximale Temperatur übernehmen zu können:

//#include <OneWire.h>
//#include <DallasTemperature.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>

WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

////////////////////////////////////////////////////////
// WiFi connect
////////////////////////////////////////////////////////

#include "zugangsdaten.h"
const char * ssid     = STA_SSID;      // << kann bis zu 32 Zeichen haben
const char * password = STA_PASSWORD;  // << mindestens 8 Zeichen jedoch nicht länger als 64 Zeichen

// Output Status
String luefterState = "auto";
// definition of PWM pins:
const int luefter = 16;  // 16 corresponds to GPIO16, sets fan1(luefter) to GPIO16
////////////////////////////////////////////////////////
// Temperatur Sensor
////////////////////////////////////////////////////////
// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;

// Setup a oneWire instance to communicate with any OneWire devices
//OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
//DallasTemperature sensors(&oneWire);

////////////////////////////////////////////////////////
// PWM Werte setzen
////////////////////////////////////////////////////////

// setting PWM properties
const int freq1 = 200;                //frequency fan1(luefter)
const int resolution = 8;             //bit-resolution
const int pwmChannel1 = 0;            //inner PWM-Channels
//FanSpeed Variablen
int fanSpeed = 0;                     //basic fanspeed(set to 0)
int tempMin = 22;                     //definition of minimum temperature
int tempMax = 28;                     //definition of maximum temperature

void setup() {
  delay(500);
  Serial.begin(115200);                               //baud rate
  Serial.println("Ready");
  // configure PWM functionalitites
  ledcSetup(pwmChannel1, freq1, resolution);
  // channelvariable for GPIO-control
  ledcAttachPin(luefter, pwmChannel1);
  // temperaturesensor start
  //sensors.begin();

  // initializing Output variables
  pinMode(luefter, OUTPUT);
  // Set outputs to LOW
  pinMode(luefter, LOW);
  // connection to Network, for example WLAN
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Output of the connection options
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  // start web server
  server.begin();
}
void loop(void) {

  // read temperature sensor
  //sensors.requestTemperatures();                         //Request to temperature sensor
  //float temperatureC = sensors.getTempCByIndex(0);       //sets temperatureC to input value
  float temperatureC = random(150, 250) / 10;
  String StemperatureC;                                  //StemperatureC for Webserver, (actually Value)
  StemperatureC = String(temperatureC);                  //cast temperature variable too String Casten for output an the Webserver
  
  Serial.print(temperatureC);
  Serial.println("ºC");
  delay(1000);

  //------------------------------------------------------------------------
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    currentTime = millis();
    previousTime = currentTime;
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected() && currentTime - previousTime <= timeoutTime) {  // loop while the client's connected
      currentTime = millis();
      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
        header += c;
        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) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            // turns Luefter status   auto -> on ->  off -> auto...
            if (header.indexOf("GET /1/on") >= 0) {                   //fan1, Url-extension
              Serial.println("Lüfter 1 on");                     //print "fan1 on" to output
              luefterState = "on";                                 //sets fan1state "on"
            }
            else if (header.indexOf("GET /1/off") >= 0) {           //fan1
              Serial.println("Lüfter 1 off");
              luefterState = "off";
            } else if (header.indexOf("GET /1/auto") >= 0) {          //fan1
              Serial.println("Lüfter 1 auto");
              luefterState = "auto";
            } else if (header.indexOf("TEXT1=") >= 0) {
              Serial.println("#####");
              byte s = header.indexOf("TEXT1=") + 6;
              byte e = header.indexOf("&");
              Serial.println();
              Serial.print( s );
              Serial.print( '\t' );
              Serial.println( e );
              Serial.println( header.substring(s, e) );
              tempMax = header.substring(s, e).toInt();
              Serial.println( tempMax );
            }

            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" http-equiv=\"refresh\" content=\"2\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            client.println("<style>html { font-family: Helvetica; background-color:#c9f128; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #555555; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button3 {background-color: #D8D800;border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}</style></head>");

            // Web Page Heading
            client.println("<body><h1>Test ESP32</h1>");
            // current temperature
            client.println("<h1>Temperatur: " + StemperatureC + "&degC</h1>");
            // Display current state, and ON/OFF/AUTO buttons for fan1(luefter)
            client.println("<p>L&uumlfter1 - Status " + luefterState + "</p>");

            // If the luefterState is off, it displays the auto button
            if (luefterState == "off") {
              client.println("<p><a href=\"/1/auto\"><button class=\"button button3\">AUTO</button></a></p>");
              luefterState = "off";
            }
            // If the luefterState is auto, it displays the on button
            else if (luefterState == "auto") {
              client.println("<p><a href=\"/1/on\"><button class=\"button \">ON</button></a></p>");
              luefterState = "auto";
            }
            // If the luefterState is on, it displays the off button
            else {
              client.println("<p><a href=\"/1/off\"><button class=\"button button2\">OFF</button></a></p>");
              luefterState = "on";
            }
            client.print("<h1>TemperaturMax: " + String(tempMax) + "&degC</h1>");
            //client.print("<form action='/buton' method='POST'>");
            client.print("<form action=\"/get\">"); //added a form to take a text input and send a get request.
            client.print("<p>TempMax &aumlndern</p>");
            client.print( "<input type='text1' name='TEXT1' value='");
            client.print(tempMax);
            client.print("'size='6'>");
            client.print("<input type='submit' name='SUBMIT' value='senden'>");
            client.print("</form><br>");
            client.println("</body></html>");

            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            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
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
  //-------------------------------------------------
  // fan1(Luefter 1) state requesting
  if (luefterState == "auto")                         // auto = automatical PWM regulation
  {
    if (temperatureC < tempMin)
    {
      //Temperature below tempMin fan1 off
      fanSpeed = 0;
      Serial.println("L1 = auto, Temp < " + String(tempMin) + ", fanSpeed= " + String(fanSpeed));                                     //print in serial interface the temperature,the current terms and the fan speed
      ledcWrite(pwmChannel1, fanSpeed);
    }
    else if (temperatureC >= tempMin && temperatureC < tempMax)
    {
      //Temperature from tempMin fan1 20% -80%
      //0...255 = 256 values because of 8-bit
      // 32 means 20% of 256 values and 80% means 216
      //fanSpeed = map(tempC, tempMin, tempMax, 32, 255);
      fanSpeed = map(temperatureC, tempMin, tempMax, 32, 216);
      Serial.println("L1 = auto, Temp > " + String(tempMin) + " + Temp < " + String(tempMax) + ", fanSpeed= " + String(fanSpeed));    //print in serial interface the temperature,the current terms and the fan speed
      ledcWrite(pwmChannel1, fanSpeed);
    }
    else if (temperatureC >= tempMax)
    {
      //Temperature from temMax fan1 100%
      fanSpeed = 255;                                                                                                                 //fanSpeed 100% means 255
      Serial.println("L1 = auto, Temp > " + String(tempMax) + ", fanSpeed= " + String(fanSpeed));                                     //print in serial interface the temperature,the current terms and the fan speed
      ledcWrite(pwmChannel1, fanSpeed);
    }
  }
  else if (luefterState == "off")  // no terms -> fan 1 off
  {
    fanSpeed = 0;
    Serial.println("L1 = off , fanSpeed= " + String(fanSpeed));
    ledcWrite(pwmChannel1, fanSpeed);

  }
  else if (luefterState == "on")  // no terms -> fan 1 on
  {
    fanSpeed = 255;
    Serial.println("L1 = on , fanSpeed= " + String(fanSpeed));
    ledcWrite(pwmChannel1, fanSpeed);
  }
}

grafik

Ich weiß nicht, ob es Dir noch hilft, aber nun ja :slightly_smiling_face:

1 Like

Ob dem TO weis ich nicht aber mir schon.
Da kommen mir sofort " Deine Freunde und Die Prinzen" mi Alles nur geklaut vor die Augen und Ohr :wink:
Also nicht um sonst gemacht :clap: :clap: :clap:

Danke

Das freut mich :slightly_smiling_face:

Optimal ist die Sache allerding nicht, da die gemessene Temperatur nicht automatisch aktualisiert wird.

Ich bin ab und zu fauler Sack :wink:
und statt komplette Seite mit HTML Editor bauen, für Kleinlichkeiten nehme ich client.println :wink:
Jetzt habe dazugelernt wie man abfrage macht mit dem System.

Das kann man mit der Fetch-API leicht nachziehen.
Ich habe für solche Testfälle einen Webserver nach Fips) mit OTA und SPIFFS/LittleFS-Verwaltung rumliegen. Da kann man die statischen Teile problemlos auf dem PC im Browser aufbauen und sie dann komfortabel hoch laden.

Gruß Tommy

Hallo agmue,
war keineswegs umsonst deine Mühe. Ich kann nur draus lernen.
Danke

wenn, dann solltest du aber so wenige Client Print wie möglich nehmen, da jedes client print zu einem separaten TCP Packet führt und somit die Übertragungszeit länger wird. Besser einen Buffer befüllen und den Buffer übertragen.

Aber mit WebServer server(80);, den Handlern und server.argName(i) sowie server.arg(i) finde ich es einfacher:

// ESP32
//#include <OneWire.h>
//#include <DallasTemperature.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>

WebServer server(80);

// Variable to store the HTTP request
String header;

////////////////////////////////////////////////////////
// WiFi connect
////////////////////////////////////////////////////////

#include "zugangsdaten.h"
const char * ssid     = STA_SSID;      // << kann bis zu 32 Zeichen haben
const char * password = STA_PASSWORD;  // << mindestens 8 Zeichen jedoch nicht länger als 64 Zeichen
const int led = 13;

// Output Status
String luefterState = "auto";
// definition of PWM pins:
const int luefter = 16;  // 16 corresponds to GPIO16, sets fan1(luefter) to GPIO16
////////////////////////////////////////////////////////
// Temperatur Sensor
////////////////////////////////////////////////////////
// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;
float temperatureC = 0;
// Setup a oneWire instance to communicate with any OneWire devices
//OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
//DallasTemperature sensors(&oneWire);

////////////////////////////////////////////////////////
// PWM Werte setzen
////////////////////////////////////////////////////////

// setting PWM properties
const int freq1 = 200;                //frequency fan1(luefter)
const int resolution = 8;             //bit-resolution
const int pwmChannel1 = 0;            //inner PWM-Channels
//FanSpeed Variablen
int fanSpeed = 0;                     //basic fanspeed(set to 0)
int tempMin = 22;                     //definition of minimum temperature
int tempMax = 28;                     //definition of maximum temperature

void setup() {
  delay(500);
  Serial.begin(115200);                               //baud rate
  Serial.println("Ready");
  // configure PWM functionalitites
  ledcSetup(pwmChannel1, freq1, resolution);
  // channelvariable for GPIO-control
  ledcAttachPin(luefter, pwmChannel1);
  // temperaturesensor start
  //sensors.begin();

  // initializing Output variables
  pinMode(luefter, OUTPUT);
  // Set outputs to LOW
  pinMode(luefter, LOW);
  // connection to Network, for example WLAN
  pinMode(led, OUTPUT);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    digitalWrite(led, !digitalRead(led));
  }
  digitalWrite(led, 0);
  // Output of the connection options
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // start web server
  server.on("/1/auto", handle_1_auto);
  server.on("/1/on", handle_1_on);
  server.on("/1/off", handle_1_off);
  server.on("/get", handleTemperatur);
  server.on("/", handleRoot);
  server.onNotFound(handleNotFound);
  server.begin();
}

void loop(void) {
  server.handleClient();
  luefterreglung();
}

void handle_1_auto()
{
  luefterState = "auto";
  handleRoot();
}

void handle_1_on()
{
  luefterState = "on";
  handleRoot();
}

void handle_1_off()
{
  luefterState = "off";
  handleRoot();
}

void handleTemperatur() {
  if (server.args())
  {
    for (uint8_t i = 0; i < server.args(); i++) {
      if (server.argName(i) == "TEXT1")
      {
        if (server.arg(i).toInt() > 0)
        {
          tempMax = server.arg(i).toInt();
          Serial.print("tempMax: ");
          Serial.println( tempMax );
        }
      }
    }
  }
  handleRoot();
}

void handleRoot() {
  digitalWrite(led, 1);
  // Display the HTML web page
  String message = "<!DOCTYPE html><html>\n";
  message += "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" http-equiv=\"refresh\" content=\"2\">\n";
  message += "<link rel=\"icon\" href=\"data:,\">\n";
  message += "<style>html { font-family: Helvetica; background-color:#c9f128; display: inline-block; margin: 0px auto; text-align: center;}\n";
  message += ".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;\n";
  message += "text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}\n";
  message += ".button2 {background-color: #555555; border: none; color: white; padding: 16px 40px;\n";
  message += "text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}\n";
  message += ".button3 {background-color: #D8D800;border: none; color: white; padding: 16px 40px;\n";
  message += "text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}</style></head>\n";

  // Web Page Heading
  message += "<body><h1>Test ESP32</h1>\n";
  // current temperature
  message += "<h1>Temperatur: " + String(temperatureC) + "&degC</h1>\n";
  // Display current state, and ON/OFF/AUTO buttons for fan1(luefter)
  message += "<p>L&uumlfter1 - Status " + luefterState + "</p>\n";

  // If the luefterState is off, it displays the auto button
  if (luefterState == "off") {
    message += "<p><a href=\"/1/auto\"><button class=\"button button3\">AUTO</button></a></p>\n";
    luefterState = "off";
  }
  // If the luefterState is auto, it displays the on button
  else if (luefterState == "auto") {
    message += "<p><a href=\"/1/on\"><button class=\"button \">ON</button></a></p>\n";
    luefterState = "auto";
  }
  // If the luefterState is on, it displays the off button
  else {
    message += "<p><a href=\"/1/off\"><button class=\"button button2\">OFF</button></a></p>\n";
    luefterState = "on";
  }
  message += "<h1>TemperaturMax: " + String(tempMax) + "&degC</h1>";
  message += "<form action=\"/get\">"; //added a form to take a text input and send a get request.
  message += "<p>TempMax &aumlndern</p>";
  message += "<input type='text1' name='TEXT1' value='";
  message += String(tempMax);
  message += "'size='6'>";
  message += "<input type='submit' name='SUBMIT' value='senden'>";
  message += "</form><br>";
  message += "</body></html>\n";

  server.send(200, "text/html", message);
  digitalWrite(led, 0);
}

void handleNotFound() {
  digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  digitalWrite(led, 0);
}

void luefterreglung()
{
  const unsigned long intervall = 1000;  // Meßintervall
  unsigned long currentTime = millis();
  static unsigned long previousTime = -intervall;

  if (currentTime - previousTime >= intervall)
  {
    previousTime = currentTime;
    // read temperature sensor
    //sensors.requestTemperatures();                         //Request to temperature sensor
    //float temperatureC = sensors.getTempCByIndex(0);       //sets temperatureC to input value
    temperatureC = random(150, 250) / 10;
    Serial.print(temperatureC, 1);
    Serial.print("ºC\t");

    if (luefterState == "auto")                         // auto = automatical PWM regulation
    {
      if (temperatureC < tempMin)
      {
        //Temperature below tempMin fan1 off
        fanSpeed = 0;
        Serial.println("L1 = auto, Temp < " + String(tempMin) + ", fanSpeed= " + String(fanSpeed));                                     //print in serial interface the temperature,the current terms and the fan speed
        ledcWrite(pwmChannel1, fanSpeed);
      }
      else if (temperatureC >= tempMin && temperatureC < tempMax)
      {
        //Temperature from tempMin fan1 20% -80%
        //0...255 = 256 values because of 8-bit
        // 32 means 20% of 256 values and 80% means 216
        //fanSpeed = map(tempC, tempMin, tempMax, 32, 255);
        fanSpeed = map(temperatureC, tempMin, tempMax, 32, 216);
        Serial.println("L1 = auto, Temp > " + String(tempMin) + " + Temp < " + String(tempMax) + ", fanSpeed= " + String(fanSpeed));    //print in serial interface the temperature,the current terms and the fan speed
        ledcWrite(pwmChannel1, fanSpeed);
      }
      else if (temperatureC >= tempMax)
      {
        //Temperature from temMax fan1 100%
        fanSpeed = 255;                                                                                                                 //fanSpeed 100% means 255
        Serial.println("L1 = auto, Temp > " + String(tempMax) + ", fanSpeed= " + String(fanSpeed));                                     //print in serial interface the temperature,the current terms and the fan speed
        ledcWrite(pwmChannel1, fanSpeed);
      }
    }
    else if (luefterState == "off")  // no terms -> fan 1 off
    {
      fanSpeed = 0;
      Serial.println("L1 = off , fanSpeed= " + String(fanSpeed));
      ledcWrite(pwmChannel1, fanSpeed);

    }
    else if (luefterState == "on")  // no terms -> fan 1 on
    {
      fanSpeed = 255;
      Serial.println("L1 = on , fanSpeed= " + String(fanSpeed));
      ledcWrite(pwmChannel1, fanSpeed);
    }
  }
}

handleNotFound() teilt http://192.168.178.27/temperatur?TEXT1=40&SUBMIT=senden schön auf

File Not Found

URI: /temperatur
Method: GET
Arguments: 2
 TEXT1: 40
 SUBMIT: senden

Das kann man dann direkt für server.on() nutzen.

PS: Die Regelung habe ich nicht getestet!

basierend auf @agmues Vorschlag hab ich mir gedacht, die 3 extra handler braucht es nicht, man schicke einfach einen Parameter.

Dann noch etwas das HTML und das CSS aufgeräumt, html entities richtig gemacht ...
schön ist es immer noch nicht, die Farben sind eher für'n Augenkrebs.

Der reload ist auskommentiert - sowas gefällt mir nicht. Würde jetzt aber gehen wenn man ihn aktiviert.

Der W3 Validator meint: Document checking completed. No errors or warnings to show.
Ich nehme dazu immer diesen: Ready to check - Nu Html Checker

Die favicon-Anforderung wird jetzt abgefangen und retourniert ein 204.

// ESP32
// https://forum.arduino.cc/t/esp32-wert-aus-url-ubernehmen/1029259/
//#include <OneWire.h>
//#include <DallasTemperature.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>

#include <ESPmDNS.h> // Bonjour/multicast DNS, finds the device on network by name

WebServer server(80);

// Variable to store the HTTP request
String header;

////////////////////////////////////////////////////////
// WiFi connect
////////////////////////////////////////////////////////

#include "zugangsdaten.h"
const char * ssid     = STA_SSID;      // << kann bis zu 32 Zeichen haben
const char * password = STA_PASSWORD;  // << mindestens 8 Zeichen jedoch nicht länger als 64 Zeichen

const int led = 13; // was 13

// Output Status
String luefterState = "auto";
// definition of PWM pins:
const int luefter = 16;  // 16 corresponds to GPIO16, sets fan1(luefter) to GPIO16
////////////////////////////////////////////////////////
// Temperatur Sensor
////////////////////////////////////////////////////////
// GPIO where the DS18B20 is connected to
const int oneWireBus = 4;   // was 4 
float temperatureC = 0;
// Setup a oneWire instance to communicate with any OneWire devices
//OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
//DallasTemperature sensors(&oneWire);

////////////////////////////////////////////////////////
// PWM Werte setzen
////////////////////////////////////////////////////////

// setting PWM properties
const int freq1 = 200;                //frequency fan1(luefter)
const int resolution = 8;             //bit-resolution
const int pwmChannel1 = 0;            //inner PWM-Channels
//FanSpeed Variablen
int fanSpeed = 0;                     //basic fanspeed(set to 0)
int tempMin = 22;                     //definition of minimum temperature
int tempMax = 28;                     //definition of maximum temperature

void setup() {
  delay(500);
  Serial.begin(115200);                               //baud rate
  Serial.println(F("Ready"));
  // configure PWM functionalitites
  ledcSetup(pwmChannel1, freq1, resolution);
  // channelvariable for GPIO-control
  ledcAttachPin(luefter, pwmChannel1);
  // temperaturesensor start
  //sensors.begin();

  // initializing Output variables
  pinMode(luefter, OUTPUT);
  // Set outputs to LOW
  digitalWrite(luefter, LOW);                   // CHANGED

  // connection to Network, for example WLAN
  pinMode(led, OUTPUT);
  Serial.print(F("Connecting to "));
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    digitalWrite(led, !digitalRead(led));
  }
  digitalWrite(led, LOW);  // changed
  // Output of the connection options
  Serial.println(F("\nWiFi connected."));
  Serial.print(F("IP address: "));
  Serial.println(WiFi.localIP());

  // start web server
  server.on("/get", handleTemperatur);
  server.on("/", handleRoot);
  server.on("/favicon.ico", handle204);          // not available, send 204
  server.onNotFound(handleNotFound);
  server.begin();
}

void loop(void) {
  server.handleClient();
  luefterreglung();
}

void handleTemperatur() {
  if (server.args())
  {
    for (uint8_t i = 0; i < server.args(); i++) {
      if (server.argName(i) == "TEXT1")
      {
        if (server.arg(i).toInt() > 0)
        {
          tempMax = server.arg(i).toInt();
          Serial.print("tempMax: ");
          Serial.println( tempMax );
        }
      }
    }
  }
  handleRoot();
}

void handleRoot() {
  digitalWrite(led, HIGH);

  if (server.args())
  {
    if (server.argName(0) == "cmd")
    {
      luefterState = server.arg(0);
    }
  }

  // Display the HTML web page
  String message = "<!DOCTYPE html>\n"
                   "<html lang='de'>\n";
  message += "<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n"
             // "<meta http-equiv=\"refresh\" content=\"2\">\n"
             "<title>ein title muss sein</title>\n";
             
  //message += "<link rel=\"icon\" href=\"data:,\">\n";  // unvollständig
  message += "<style>html { font-family: Helvetica; background-color:#c9f128; display: inline-block; margin: 0px auto; text-align: center;}\n"; //tippfehler
  message += ".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;"
             "text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}\n";
  message += ".button2 {background-color: #555555;}\n";  // es reicht das abweichende da du sowieso beide Klassen zuordnest
  message += ".button3 {background-color: #D8D800;}\n"
             "</style>\n";
  message += "</head>\n";

  // Web Page Heading
  message += "<body>\n"
             "<h1>Test ESP32</h1>\n";
  // current temperature
  message += "<h1>Temperatur: " + String(temperatureC) + "&deg;C</h1>\n";  // entity;
  // Display current state, and ON/OFF/AUTO buttons for fan1(luefter)
  message += "<p>L&uuml;fter1 - Status " + luefterState + "</p>\n";        // entity;

  // If the luefterState is off, it displays the auto button
  if (luefterState == "off") {
    message += "<p><a href=\"/?cmd=auto\" class=\"button button3\">AUTO</a></p>\n";
    luefterState = "off";
  }
  // If the luefterState is auto, it displays the on button
  else if (luefterState == "auto") {
    message += "<p><a href=\"/?cmd=on\" class=\"button\">ON</a></p>\n";
    luefterState = "auto";
  }
  // If the luefterState is on, it displays the off button
  else {
    message += "<p><a href=\"/?cmd=off\" class=\"button button2\">OFF</a></p>\n";
    luefterState = "on";
  }
  message += "<h1>TemperaturMax: " + String(tempMax) + "&deg;C</h1>\n";         // entity;
  message += "<form action=\"/get\" method='post' target='i'>"; //added a form to take a text input and send a get request.
  message += "<p>TempMax &auml;ndern</p>\n";                                    // entity;
  message += "<input type='text' name='TEXT1' value='";
  message += String(tempMax);
  message += "' size='6'>\n";
  message += "<input type='submit' name='SUBMIT' value='senden'>\n";
  message += "</form><br>\n";
  message += "<iframe name='i' style='display:none'></iframe>\n"; // hack to keep the button press in the window
  message += "</body>\n</html>\n";

  server.send(200, "text/html", message);
  digitalWrite(led, LOW);
}

void handleNotFound() {
  digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  digitalWrite(led, 0);
}

void handle204()
{
  server.send(204);                // this page doesn't send back content
}

void luefterreglung()
{
  const unsigned long intervall = 1000;  // Meßintervall
  unsigned long currentTime = millis();
  static unsigned long previousTime = -intervall;

  if (currentTime - previousTime >= intervall)
  {
    previousTime = currentTime;
    // read temperature sensor
    //sensors.requestTemperatures();                         //Request to temperature sensor
    //float temperatureC = sensors.getTempCByIndex(0);       //sets temperatureC to input value
    temperatureC = random(150, 250) / 10;
    Serial.print(temperatureC, 1);
    Serial.print("ºC\t");

    if (luefterState == "auto")                         // auto = automatical PWM regulation
    {
      if (temperatureC < tempMin)
      {
        //Temperature below tempMin fan1 off
        fanSpeed = 0;
        Serial.println("L1 = auto, Temp < " + String(tempMin) + ", fanSpeed= " + String(fanSpeed));                                     //print in serial interface the temperature,the current terms and the fan speed
        ledcWrite(pwmChannel1, fanSpeed);
      }
      else if (temperatureC >= tempMin && temperatureC < tempMax)
      {
        //Temperature from tempMin fan1 20% -80%
        //0...255 = 256 values because of 8-bit
        // 32 means 20% of 256 values and 80% means 216
        //fanSpeed = map(tempC, tempMin, tempMax, 32, 255);
        fanSpeed = map(temperatureC, tempMin, tempMax, 32, 216);
        Serial.println("L1 = auto, Temp > " + String(tempMin) + " + Temp < " + String(tempMax) + ", fanSpeed= " + String(fanSpeed));    //print in serial interface the temperature,the current terms and the fan speed
        ledcWrite(pwmChannel1, fanSpeed);
      }
      else if (temperatureC >= tempMax)
      {
        //Temperature from temMax fan1 100%
        fanSpeed = 255;                                                                                                                 //fanSpeed 100% means 255
        Serial.println("L1 = auto, Temp > " + String(tempMax) + ", fanSpeed= " + String(fanSpeed));                                     //print in serial interface the temperature,the current terms and the fan speed
        ledcWrite(pwmChannel1, fanSpeed);
      }
    }
    else if (luefterState == "off")  // no terms -> fan 1 off
    {
      fanSpeed = 0;
      Serial.println("L1 = off , fanSpeed= " + String(fanSpeed));
      ledcWrite(pwmChannel1, fanSpeed);

    }
    else if (luefterState == "on")  // no terms -> fan 1 on
    {
      fanSpeed = 255;
      Serial.println("L1 = on , fanSpeed= " + String(fanSpeed));
      ledcWrite(pwmChannel1, fanSpeed);
    }
  }
}

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