// Sietse Jonker
// 09/02/2024

#include <Wire.h>
#include "SSD1306Wire.h"
#include "Adafruit_SGP30.h"
#include "DHT.h"

#define MICPIN 6
#define DHTPIN 7
#define SCL 9
#define SDA 8

#define DHTTYPE DHT11

SSD1306Wire display(0x3c, SDA, SCL);

DHT dht(DHTPIN, DHTTYPE);

Adafruit_SGP30 sgp;

uint16_t TVOC_base, eCO2_base;
int counter = 0;
float temperature = 0;
float humidity = 0;
int eCO2 = 0;
int TVOC = 0;
bool noise = false;

void resetValues() {
TVOC_base, eCO2_base;
counter = 0;
temperature = 0;
humidity = 0;
eCO2 = 0;
TVOC = 0;
noise = false;
}

void displayData(){
  display.setFont(ArialMT_Plain_16);
  display.setTextAlignment(TEXT_ALIGN_LEFT);
  display.drawString(0, 0, String(sgp.eCO2) + " ppm" + "   " + String(sgp.TVOC) + " ppb");
  display.drawString(0, 18, String(temperature) + " C");
  display.drawString(0, 39, String(humidity) + "%");

  display.display();
}

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

  display.init();
  display.flipScreenVertically();

  dht.begin();

  sgp.begin();
  pinMode(MICPIN, INPUT);
  pinMode(DHTPIN, INPUT);

  resetValues();

  display.setFont(ArialMT_Plain_16);
  display.setTextAlignment(TEXT_ALIGN_LEFT);
}

void loop() {
  display.clear();

  if (!sgp.IAQmeasure()) {
    Serial.println("SGP30: BAD");
    return;
  }
  else {
    Serial.println("SGP30: OK");
  }

  temperature = float(dht.readTemperature());
  humidity = float(dht.readHumidity());

  displayData();

  sgp.getIAQBaseline(&eCO2_base, &TVOC_base);

  Serial.print("eCO2 ");
  Serial.print(sgp.eCO2);
  Serial.println(" ppm");

  delay(100);
  counter++;
}