Welcome to Hackster!
Hackster is a community dedicated to learning hardware, from beginner to pro. Join us, it's free!
carlosvolt
Published © LGPL

Uploading BME280 Sensor Data to ThingSpeak Using ESP32

In this tutorial, we will show you how to connect a BME280 sensor to an ESP32 to read temperature, humidity, and atmospheric pressure data,

IntermediateFull instructions provided105
Uploading BME280 Sensor Data to ThingSpeak Using ESP32

Things used in this project

Hardware components

ESP32S
Espressif ESP32S
×1

Story

Read more

Code

Source code

C/C++
Source Code
#include <WiFi.h>
#include <HTTPClient.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
// Definiciones para el sensor BME280
#define PRESION_NIVEL_MAR_HPA (1013.25)
// Reemplaza con tus credenciales Wi-Fi
const char* red_wifi = "Tu_Red_Wifi";
const char* contrasena_wifi = "Tu_Contraseña";
// API Key de ThingSpeak
const char* clave_api = "Tu_Clave_Api";
// Dirección URL de ThingSpeak
const char* servidor_thingspeak = "http://api.thingspeak.com/update";
// Objeto del sensor BME280
Adafruit_BME280 sensor_bme;
void setup() {
  Serial.begin(115200);  
  // Inicializar WiFi
  WiFi.begin(red_wifi, contrasena_wifi);
  Serial.print("Conectando a WiFi");  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }  
  Serial.println("\nConectado a WiFi");  
  // Inicializar el sensor BME280
  if (!sensor_bme.begin(0x76)) {
    Serial.println("No se encuentra el sensor BME280. Revisa la conexión.");
    while (1);
  }
}
void loop() {
  // Leer datos del sensor BME280
  float temperatura = sensor_bme.readTemperature();
  float humedad = sensor_bme.readHumidity();
  float presion = sensor_bme.readPressure() / 100.0F; // Conversión a hPa  
  // Mostrar datos en el monitor serial
  Serial.print("Temperatura = ");
  Serial.print(temperatura);
  Serial.println(" *C");  
  Serial.print("Humedad = ");
  Serial.print(humedad);
  Serial.println(" %");
  Serial.print("Presión = ");
  Serial.print(presion);
  Serial.println(" hPa");
  // Enviar datos a ThingSpeak
  if(WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    String url = String(servidor_thingspeak) + "?api_key=" + clave_api + "&field1=" + String(temperatura) + "&field2=" + String(humedad) + "&field3=" + String(presion);
    http.begin(url);    
    int codigo_http = http.GET();    
    if(codigo_http > 0) {
      Serial.printf("Código de respuesta: %d\n", codigo_http);
      if(codigo_http == HTTP_CODE_OK) {
        String respuesta = http.getString();
        Serial.println("Datos enviados a ThingSpeak");
      }
    } else {
      Serial.printf("Error en la conexión: %s\n", http.errorToString(codigo_http).c_str());
    }    
    http.end();
  } else {
    Serial.println("Error de conexión WiFi");
  }
  // Intervalo de actualización (15 segundos)
  delay(15000);
}

Credits

carlosvolt
34 projects • 3 followers
Contact

Comments

Please log in or sign up to comment.