#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHTesp.h>
#include <ThingSpeak.h>
#include <WiFi.h>
const char* ssid = "Wokwi-GUEST"; // SSID wifi pada wokwi
const char* password = ""; // password
WiFiClient client;
unsigned long myChannelNumber = 2;
const char * myWriteAPIKey = "NC5GBQ6TP4D5T3LD";
unsigned long lastTime = 0;
unsigned long timerDelay = 10000;
const int DHT_PIN = 15;
DHTesp dhtSensor;
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET 4
#define SCREEN_ADDRESS 0x3C
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire,
OLED_RESET);
void setup() {
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Inisialisasi ThingSpeak
Serial.begin(115200);
// Connect atau reconnect ke WiFi
if(WiFi.status() != WL_CONNECTED){
Serial.print("Menghubungkan ke jaringan");
while(WiFi.status() != WL_CONNECTED){
WiFi.begin(ssid, password);
delay(5000);
}
Serial.println("\nTerhubung ke jaringan.");
}
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
// Cek OLED display
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.display();
delay(2000);
display.clearDisplay();
display.setTextColor(WHITE);
display.setTextSize(2);
}
void loop() {
TempAndHumidity data = dhtSensor.getTempAndHumidity();
float temp = data.temperature;
float hum = data.humidity;
Serial.println("Temp: " + String(data.temperature, 2) + "°C");
Serial.println("Humidity: " + String(data.humidity, 1) + "%");
Serial.println("---");
delay(3000); // Menunggu pembacaan sensor
// Kosongkan Display
display.clearDisplay();
// Mengatur ukuran teks
display.setTextSize(1.7);
// Mengatur warna teks
display.setTextColor(SSD1306_WHITE);
// Mengatur posisi pixel76
display.setCursor(0, 0);
// Menampilkan teks
display.println("Suhu: " +String(data.temperature, 2) + " C");
display.setCursor(0, 15);
display.println("Kelembaban: " +String(data.humidity, 1) + "%");
ThingSpeak.setField(1, temp);
ThingSpeak.setField(2, hum);
display.display();
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if(x == 200){
Serial.println("Channel update sukses.");
}
else{
Serial.println("Updating channel gagal. HTTP error code " +
String(x));
}
}