Monday, May 15, 2023

Monitoring Temperatur dan Kelembaban DHT11 via Thingspeak

//program ini berhasil connect ke thingspeak
//untuk 4 inputan/data random

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

#define WIFI_SSID "RANACITTA"
#define WIFI_PASSWORD "Pandakgede999"
#define API_KEY "N3JG5CU3O8TA9B86"
int bilanganacak;
int bilanganacak2;

#define DHTPIN D5
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(115200);
  // Connect to WiFi network
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }

  Serial.println("Connected to WiFi");

  // Start the DHT sensor
  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements
  delay(5000);

  // Read temperature and humidity from the DHT sensor
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  bilanganacak = random(0,1000);
  bilanganacak2 = random(1000,5000);

  if (isnan(temperature) || isnan(humidity)) {
    Serial.println("Failed to read from DHT sensor");
    return;
  }

  // Connect to ThingSpeak server
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect("api.thingspeak.com", httpPort)) {
    Serial.println("Connection to ThingSpeak failed");
    return;
  }

  // Send data to ThingSpeak
  String url = "/update?key=" + String(API_KEY) +
               "&field1=" + String(temperature) +
               "&field2=" + String(humidity) +
               "&field3=" + String(bilanganacak) +
               "&field4=" + String(bilanganacak2);
               "&field5=" + String(0.0);
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: api.thingspeak.com\r\n" +
               "Connection: close\r\n\r\n");

    Serial.print(" Temperature: ");
    Serial.print(temperature);
    Serial.print(" Celcius Humidity: ");
    Serial.print(humidity);
    Serial.print(" Bilangan Acak: ");
    Serial.print(bilanganacak);
    Serial.print(" Bilangan Acak 2: ");
    Serial.print(bilanganacak2);

  delay(20000);

  Serial.println(" Data sent to ThingSpeak");
}

No comments: