Uploading data to a server and getting value from a DHT11 sensor and ESP8266

Hi, I'm needing help. I'm doing a code to get data from a DHT11 sensor and upload it as a Json format from a ESP8266. The problem here is that I can't manage to do the connection, plus, the code is not swiping the data from the sensors. If anyone knows what my problem might be, i would rlly appriciate it. I'll leave some of the codes I tryed this with.


#include <ESP8266WiFi.h>
#include <DHT.h>
#include <WiFiClient.h>


const char* ssid = "IoTB";
const char* password = "inventaronelVAR";


const char* serverAddress = "https://subite-back.vercel.app/hard";
const int serverPort = 80;


#define DHTPIN 0  
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);


WiFiClient client;

void setup() {
  Serial.begin(115200);
  delay(10);

 
  Serial.println();
  Serial.println();
  Serial.print("Conectando a ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("Conexión WiFi exitosa");
  Serial.println("Dirección IP: ");
  Serial.println(WiFi.localIP());

  dht.begin();
}

void loop() {

  float temperatura = dht.readTemperature();
  float humedad = dht.readHumidity();


  if (isnan(temperatura) || isnan(humedad)) {
    Serial.println("Error al leer el sensor DHT11");
    return;
  }

 
  String jsonPayload = "{\"temp\":" + String(temperatura) + ",\"hum\":" + String(humedad) + "}";


  String postData = "POST /ruta-api HTTP/1.1\r\n";
  postData += "Host: " + String(serverAddress) + "\r\n";
  postData += "Content-Type: application/json\r\n";
  postData += "Content-Length: " + String(jsonPayload.length()) + "\r\n\r\n";
  postData += jsonPayload;


  if (client.connect(serverAddress, serverPort)) {
    Serial.println("Conectado al servidor");
    client.print(postData);


    while (client.connected()) {
      if (client.available()) {
        String response = client.readStringUntil('\r');
        Serial.println("Respuesta del servidor: ");
        Serial.println(response);
      }
    }
    client.stop();
  } else {
    Serial.println("Error al conectarse al servidor");
  }


  delay(60000);  
}

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