Introduction
In this tutorial we will learn how to obtain temperature measurements from a BMP388 sensor, using the ESP32 and the Arduino core.
We will be using this module from DFRobot, which we can directly connect to an ESP32 microcontroller. We will be using this library to interact with the sensor using the I2C protocol.
For an introductory tutorial on how to interact with the sensor, including an electric schematic, please check here.
The tests from this tutorial were done using a DFRobot’s ESP32 module integrated in a ESP32 development board.
The code
We will start the code with the DFRobot_BMP388_I2C.h library include. After that, we will define an object of type DFRobot_BMP388_I2C, which will expose to us the method we need to get temperature measurements from the sensor.
#include "DFRobot_BMP388_I2C.h"
DFRobot_BMP388_I2C bmp388;
Moving on to the Arduino setup, we will start by opening a serial connection. That way we will be able to print our temperature measurements.
Serial.begin(115200);
Then we will initialize the sensor with a call to the begin method on the DFRobot_BMP388_I2C object. Note that this method takes no arguments and returns zero in case of success.
while(bmp388.begin() != 0){
Serial.println("Initialization error! Trying again..");
delay(1000);
}
The full setup can be seen below.
void setup(){
Serial.begin(115200);
while(bmp388.begin() != 0){
Serial.println("Initialization error! Trying again..");
delay(1000);
}
}
We will use the Arduino loop to periodically fetch the temperature measurements. To get a measurement, we simply need to call the readTemperature method on our DFRobot_BMP388_I2C object.
This method takes no arguments and returns the temperature as a float, in degrees Celsius.
float temperature = bmp388.readTemperature();
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" C");
The complete main loop can be seen below.
void loop(){
float temperature = bmp388.readTemperature();
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" C");
delay(1000);
}
The full code can be seen below.
#include "DFRobot_BMP388_I2C.h"
DFRobot_BMP388_I2C bmp388;
void setup(){
Serial.begin(115200);
while(bmp388.begin() != 0){
Serial.println("Initialization error! Trying again..");
delay(1000);
}
}
void loop(){
float temperature = bmp388.readTemperature();
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" C");
delay(1000);
}
Testing the code
After connecting the ESP32 to the sensor module, compile the code and upload it using the Arduino IDE.
Once the procedure finishes, open the IDE serial monitor. You should get an output similar to figure 1.
