ESP32 Webserver with analogue and digital sensors

Hello guys!

I am trying to program an ESP32 board to read an analog and digital values and display both on a webpage. The board is running in SoftAP mode meaning it acts both as a webserver and access point with its own network.

I managed to make it work with only the digital value (temperature) but I have issues getting it to run with both analog (pressure) and digital values.

I use ds18b20 sensor for temperature and a generic analog pressure sensor.

My code is this:

// Import required libraries
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is connected to GPIO 4
#define ONE_WIRE_BUS 4

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);

// Variables to store temperature values
String temperatureC = "";
String pressureValue ="";

// Float Vars to store pressure values - NEW
const int pressureInput1 = 5; //select the analog input pin for the pressure OIL
//const int pressureInput2 = A2; //select the analog input pin for the pressure of FUEL
const int pressureZero = 285.3; //analog reading of pressure transducer at 0psi
const int pressureMax = 4095; //analog reading of pressure transducer at 100psi
const int pressuretransducermaxPSI = 100; //psi value of transducer being used
//const int baudRate = 115200; //constant integer to set the baud rate for serial monitor
//const int sensorreadDelay = 250; //constant integer to set the sensor read delay in milliseconds

//Float pressureValue = 0; //variable to store the value coming from the pressure transducer

// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 300;

// Replace with your network credentials - CHANGED
const char *ssid = "MyESP32AP";
const char *password = "123456789";

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

// OIL PRESSURE
String ReadPressureValue() {
  int pressureValueRead = analogRead(pressureInput1); //reads value from input pin and assigns to variable
  float pressureValueActual = (((pressureValueRead - pressureZero) * pressuretransducermaxPSI) / (pressureMax - pressureZero)) / 14.504; //conversion equation to convert analog reading to psi
  Serial.print(pressureValueActual, 2); //prints value from previous line to serial
  Serial.println("psi"); //prints label to serial
 }

String readDSTemperatureC() {
  // Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
  sensors.requestTemperatures();
  float tempC = sensors.getTempCByIndex(0);

  if (tempC == -127.00) {
    Serial.println("Failed to read from DS18B20 sensor");
    return "--";
  } else {
    Serial.print("Temperature Celsius: ");
    Serial.println(tempC);
  }
  return String(tempC);
}

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    html {
     font-family: Arial;
     display: inline-block;
     margin: 0px auto;
     text-align: center;
    }
    h2 { font-size: 3.0rem; }
    p { font-size: 3.0rem; }
    .units { font-size: 1.2rem; }
    .ds-labels{
      font-size: 1.5rem;
      vertical-align:middle;
      padding-bottom: 15px;
    }
  </style>
</head>
<body>
  <h2>ESP32 SoftAP</h2>
  <p>
    <span class="ds-labels">Temperature Celsius</span><br> 
    <span id="temperaturec">%TEMPERATUREC%</span>
    <sup class="units">&deg;C</sup>
  </p>
    <p>
    <span class="ds-labels">Pressure PSI</span><br> 
    <span id="pressure1">%pressureValue%</span>
    <sup class="units">PSI</sup>
  </p>
</body>
<script>
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("temperaturec").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/temperaturec", true);
  xhttp.send();
    var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("pressureValue").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/pressureValue", true);
  xhttp.send();
}, 50) ;
</script>
</html>)rawliteral";

// Replaces placeholder with DS18B20 values - NEW - pressure values too
String processor(const String& var) {
  //Serial.println(var);
  if (var == "TEMPERATUREC") {
    return temperatureC;
  }
  else if (var == "pressureValue") {
    return pressureValue;
  }
  return String();
}

void setup() {
  // Serial port for debugging purposes
  Serial.begin(115200);
  Serial.println();

  // Start up the DS18B20 library
  sensors.begin();

  //Serial.println(xPortGetCoreID());

  temperatureC = readDSTemperatureC();
  pressureValue = ReadPressureValue();

  // Wi-Fi Soft AP start
  WiFi.softAP(ssid, password);

  // Print ESP Local IP Address
  Serial.println(WiFi.localIP());

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

  // Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send_P(200, "text/html", index_html, processor);
  });
  server.on("/temperaturec", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send_P(200, "text/plain", temperatureC.c_str());
  });
  // Start server
  server.begin();
}

void loop() {
  if ((millis() - lastTime) > timerDelay) {
    temperatureC = readDSTemperatureC();
     pressureValue = ReadPressureValue();
    lastTime = millis();
  }

}

The above code compiles fine but the ESP goes into boot loop with the below error:

Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x16 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1044
load:0x40078000,len:10124
load:0x40080400,len:5856
entry 0x400806a8

Temperature Celsius: 23.25
-0.48psi
Guru Meditation Error: Core  1 panic'ed (LoadProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0x4000c3f0  PS      : 0x00060330  A0      : 0x800d9c6b  A1      : 0x3ffb1f00  
A2      : 0x3ffc16f0  A3      : 0x00000000  A4      : 0x00000001  A5      : 0x3fe866cb  
A6      : 0x00000000  A7      : 0x00000008  A8      : 0x00000000  A9      : 0x00000000  
A10     : 0x00000002  A11     : 0x3f400974  A12     : 0x00000003  A13     : 0x0000ff00  
A14     : 0x00ff0000  A15     : 0xff000000  SAR     : 0x0000001c  EXCCAUSE: 0x0000001c  
EXCVADDR: 0x00000000  LBEG    : 0x400014fd  LEND    : 0x4000150d  LCOUNT  : 0xffffffff  

ELF file SHA256: 0000000000000000

Backtrace: 0x4000c3f0:0x3ffb1f00 0x400d9c68:0x3ffb1f20 0x400d9d62:0x3ffb1f40 0x400d0bf8:0x3ffb1f60 0x400da562:0x3ffb1fb0 0x4008982e:0x3ffb1fd0

Any help would be appreciated.

Thanks in advance

Could you post the decoded error after putting the debug info into the ESP Exception Decoder, an add on to the Arduino IDE?

is that going to be an int or a float?

'const float pressureZero = 285.3f;' is how to declare a float.

Stack Trace:

Decoding stack results
0x400d9c68: String::move(String&) at C:\Users\Nicolas\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.6\cores\esp32\WString.cpp line 231
0x400d9d62: String::operator=(String&&) at C:\Users\user\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.6\cores\esp32\WString.cpp line 273
0x400d0bf8: setup() at C:\Users\user\Documents\Arduino\Pressure_and_Temp_SoftAP/Pressure_and_Temp_SoftAP.ino line 150
0x400da562: loopTask(void*) at C:\Users\user\Documents\ArduinoData\packages\esp32\hardware\esp32\1.0.6\cores\esp32\main.cpp line 18
0x4008982e: vPortTaskWrapper at /home/runner/work/esp32-arduino-lib-builder/esp32-arduino-lib-builder/esp-idf/components/freertos/port.c line 143

That is going to be an int. Used it on its own and it works.

Thank you!!

Hi
The error is being caused because the function:
"String ReadPressureValue() " needs to return a String value,
but it doesn't have the return statement.

Add this line to the end of this function:
"return String(pressureValueActual);"
and see if it works.

// OIL PRESSURE
String ReadPressureValue() 
{
  int pressureValueRead = analogRead(pressureInput1); //reads value from input pin and assigns to variable
  float pressureValueActual = (((pressureValueRead - pressureZero) * pressuretransducermaxPSI) / (pressureMax - pressureZero)) / 14.504; //conversion equation to convert analog reading to psi
  Serial.print(pressureValueActual, 2); //prints value from previous line to serial
  Serial.println("psi"); //prints label to serial
  return String(pressureValueActual);
 }

Thanks for the reply, error is gone and it works but the pressure sensor does not refresh like the temp does and it also looks wrong seating at -0.48 and wont change

Hi
What ESP32 board are you using?

This one :smiley:

Hi

in your code indicates that you are using GPIO5 as an analog input. "const int pressureInput1 = 5; "
But GPIO5 is not an analog input on ESP32.
The analog inputs are:
ADC1 : GPIO32, GPIO33, GPIO34, GPIO35, GPIO36 and GPIO39 and
ADC2 : GPIO2, GPIO4, GPIO12, GPIO13, GPIO14, GPIO15, GPIO25, GPIO26 and GPIO27.

But ADC2 pins cannot be used when Wi-Fi is used.

so change your "const int pressureInput1 = x; " to any GPIO of ADC1.

You could not be more right! Wifi point is really useful!

Thank you very much. Its working!

For future development and anyone that may require something similar this is my final working code:

/*********
  Nicolas Constantinou
  ESP32 SoftAP with analog and digital inputs displayed on a webpage with an Async Webserver
*********/

// Import required libraries
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is connected to GPIO 4
#define ONE_WIRE_BUS 4

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);

// Variables to store temperature values
String temperatureC = "";
String pressureValuePSI = "";

// Float Vars to store pressure values - NEW
const int pressureInput = 32; //select the analog input pin for the pressure OIL
const int pressureZero = 285.3; //analog reading of pressure transducer at 0psi
const int pressureMax = 4095; //analog reading of pressure transducer at 100psi
const int pressuretransducermaxPSI = 100; //psi value of transducer being used
String pressureValue = ""; //variable to store the value coming from the pressure transducer

//Call Sensors and store actual value after equation to string
String readPressureValues () {     
    float pressureValueRead = analogRead(pressureInput); //reads value from input pin and assigns to variable
          pressureValuePSI = (((pressureValueRead-pressureZero)*pressuretransducermaxPSI)/(pressureMax-pressureZero))/14.504; //conversion equation to convert analog reading to psi    
            Serial.print("OIL  Press:"); //prints label 
            Serial.print(pressureValuePSI); //prints value from previous line to serial
            Serial.println("bar"); //prints label to serial
            Serial.println(pressureValueRead);
                      
     return String(pressureValuePSI); 
}

// Timer variables
unsigned long lastTime = 0;
unsigned long timerDelay = 300;

// Replace with your network credentials - CHANGED
const char *ssid = "MyESP32AP";
const char *password = "123456789";

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

String readDSTemperatureC() {
  // Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
  sensors.requestTemperatures();
  float tempC = sensors.getTempCByIndex(0);

  if (tempC == -127.00) {
    Serial.println("Failed to read from DS18B20 sensor");
    return "--";
  } else {
    Serial.print("Temperature Celsius: ");
    Serial.println(tempC);
  }
  return String(tempC);
}

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    html {
     font-family: Arial;
     display: inline-block;
     margin: 0px auto;
     text-align: center;
    }
    h2 { font-size: 3.0rem; }
    p { font-size: 3.0rem; }
    .units { font-size: 1.2rem; }
    .ds-labels{
      font-size: 1.5rem;
      vertical-align:middle;
      padding-bottom: 15px;
    }
  </style>
</head>
<body>
  <h2>ESP32 Su
  barakka</h2>
  <p>
    <span class="ds-labels">Temperature</span><br> 
    <span id="temperaturec">%TEMPERATUREC%</span>
    <sup class="units">&deg;C</sup>
  </p>
    <p>
    <span class="ds-labels">Oil Pressure</span><br> 
    <span id="pressureValue">%pressureValue%</span>
    <sup class="units">BAR</sup>
  </p>
</body>
<script>
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("temperaturec").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/temperaturec", true);
  xhttp.send();
    var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("pressureValue").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "/pressureValue", true);
  xhttp.send();
}, 50) ;
</script>
</html>)rawliteral";

// Replaces placeholder with DS18B20 values - NEW - pressure values too
String processor(const String& var) {
  //Serial.println(var);
  if (var == "TEMPERATUREC") {
    return temperatureC;
  }
  else if (var == "pressureValue") {
    return pressureValuePSI;
  }
 
  return String();
}

void setup() {
  // Serial port for debugging purposes
  Serial.begin(115200);
  Serial.println();

  // Start up the DS18B20 library
  sensors.begin();

  //Serial.println(xPortGetCoreID());
  
  //Declare strings to be used by webserver
  temperatureC = readDSTemperatureC();
  pressureValue = readPressureValues() ;


  // Wi-Fi Soft AP start
  WiFi.softAP(ssid, password);

  // Print ESP Local IP Address
  Serial.println(WiFi.localIP());
  Serial.println();
  Serial.print("IP address: ");
  Serial.println(WiFi.softAPIP());

  // Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send_P(200, "text/html", index_html, processor);
  });
  server.on("/temperaturec", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send_P(200, "text/plain", temperatureC.c_str());
  });
  server.on("/pressureValue", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send_P(200, "text/plain", pressureValue.c_str());
  });
  // Start server
  server.begin();
}

void loop() {
  if ((millis() - lastTime) > timerDelay) {
    temperatureC = readDSTemperatureC();
    pressureValue = readPressureValues () ;
    lastTime = millis();
  }

 }

Now lets get it to multitask :smiley:

1 Like

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