0

I'm trying to shorten my Arduino code but I've run into a problem. Here is the code snippet:

server.on("/temperature1", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", readDSTemperature1().c_str());
  });

Can I use a for loop for change the 1 to 2, 3,... until 7? Otherwise I need to write that block 6 more times. The "/temperature1" is just a string so adding + i would work. The problem is in the readDSTemperature1 method, where I can't apply that.

I'm just a beginner at Arduino so maybe I'm missing something.

Can anyone help me further?


Fixed by using the ESP8266WebServer library instead of the ESPAsyncWebServer library.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83

1 Answers1

0

As you use async webserver it would be easier to work with params:

 server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
      if (request->args() == 0) // no arguments attached -> STATUS_BAD_REQUEST
          return request->send(400, "text/plain", F("ERROR: Bad or no arguments"));
     uint8_t dhtSensor = request->arg("sensor").toInt(); 
     request->send(200, "text/plain", readDSTemperature(dhtSensor).c_str());
 });

Not knowing your function readDSTemperature() you'll have to modify to (xxxx is the return type of the function)

 xxxx readDSTemperature(uint8_t sensorNumber){
  switch(sensorNumber){
      case 1:
          // read sensor number 1
         // return sensorValue;
          break;
      ....        
      }
   }

and your browser should send request like this

http://192.168.0.1/temperature?sensor=1

As mentioned in the comments functions with numbers or similar methods are a bad design and programming style. Not only hard to maintain and change but also wasting memory. The code above is far from optimized but not knowing more than you have given its hard to guess.
Btw replace send_P with send, because only serving from PROGMEM is done with send_P (e.g. and index.html is stored in PROGMEM - which I would not recommend)

Codebreaker007
  • 2,911
  • 1
  • 10
  • 22