Declare the GPIO pin that is connected to the DS18B20 sensor. In our case we are connecting to GPIO 4 (D1):
#define ONE_WIRE_BUS 4
Instantiate the instances needed to initialize the sensor:
// 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);
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);
}
In case the sensor is not able to get a valid reading, it returns -127. So, we have an if statement that returns two dashes (–-) in case the sensor fails to get the readings.
if(tempC == -127.00){
Serial.println("Failed to read from DS18B20 sensor");
return "--";
The reaDSTemperatureF() function works in a similar way but returns the readings in Fahrenheit degrees.
The readings are returned as string type. To convert a float to a string, use the String() function.
return String(tempC);
The next step is building the web page. The HTML and CSS needed to build the web page are saved on the index_html variable.
In the HTML text we have TEMPERATUREC and TEMPERATUREF between % signs. This is a placeholder for the temperature values.
This means that this %TEMPERATUREC% text is like a variable that will be replaced by the actual temperature value from the sensor. The placeholders on the HTML text should go between % signs.
Processor
The next will be to create a processor function that will replace the placeholders in our HTML text with the actual temperature values.
When the web page is requested, we check if the HTML has any placeholders. If it finds the %TEMPERATUREC% placeholder, we return the temperature in Celsius by calling the readDSTemperatureC() function created previously.
When we make a request on the root URL, we send the HTML text that is stored in the index_html variable. We also need to pass the processor function, that will replace all the placeholders with the right values.
We need to add two additional handlers to update the temperature readings. When we receive a request on the /temperaturec URL, we simply need to send the updated temperature value. It is plain text, and it should be sent as a char, so, we use the c_str() method.