#include <DHT.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define buzzer A3
int pinR = 6;
int pinK = 5;
int pinB = 4;

#define DHTPIN 7
#define DHTTYPE DHT22

Adafruit_SSD1306 display = Adafruit_SSD1306(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

DHT dht = DHT(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println(F("DHT22 On"));
  dht.begin();

  display.begin(SSD1306_SWITCHCAPVCC, 0x3c);
  display.clearDisplay();

  pinMode(buzzer, OUTPUT);

  pinMode(pinR, OUTPUT);
  pinMode(pinK, OUTPUT);
  pinMode(pinB, OUTPUT);

}


void loop() {

  delay(2000);
  display.clearDisplay();
  display.setTextSize(1.5);
  display.setTextColor(WHITE);
  display.setCursor(0, 10);

  float t = dht.readTemperature();
  
  if (isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  float hic = dht.computeHeatIndex(t, false);

  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" \xC2\xB0");
  Serial.print("C | ");


  display.println("Temperature:");
  display.println(t);

    if (t < 29) {
      display.print("Suhu Rendah");
      display.display();
      digitalWrite(pinR, LOW);
      digitalWrite(pinK, LOW);
      digitalWrite(pinB, HIGH);
      noTone(buzzer);
    }

    else if (t >= 29 && t <= 35 ) {
      display.print("Suhu Cukup");
      display.display();
      digitalWrite(pinR, LOW);
      digitalWrite(pinK, HIGH);
      digitalWrite(pinB, LOW);    
      noTone(buzzer);  
    }
    else if (t > 35){
      display.print("Suhu Panas!!!");
      display.display();
      digitalWrite(pinR, HIGH);
      digitalWrite(pinK, LOW);
      digitalWrite(pinB, LOW);      
      tone(buzzer, 100);
      delay(100);
      tone(buzzer, 500);
      delay(100);
    }

    else {
      display.println("Suhu tidak normal!");
      display.display();
    }

}