#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 
#define SCREEN_HEIGHT 64 
#define OLED_RESET    -1 
#define SCREEN_ADDRESS 0x3C // Oft 0x3C oder 0x3D

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

const int inputPin = 12;
const int calButtonPin = 2;
float offset = 0.8;
const float k = 45500.0;
float smoothedCap = 0.0;

void setup() {
  Serial.begin(9600);
  pinMode(inputPin, INPUT);
  pinMode(calButtonPin, INPUT_PULLUP);

  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    for(;;); // Stoppt, falls Display nicht gefunden wird
  }
  
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0,0);
  display.println("LCR-Meter bereit");
  display.display();
  delay(1000);
}

void loop() {
  unsigned long durationHigh = pulseIn(inputPin, HIGH, 1000000);
  unsigned long durationLow = pulseIn(inputPin, LOW, 1000000);
  unsigned long period = durationHigh + durationLow;

  if (period > 0) {
    float frequency = 1000000.0 / period;
    float rawCapacity = (k / frequency);
    float currentCap = rawCapacity - offset;
    smoothedCap = (smoothedCap * 0.9) + (currentCap * 0.1);

    // OLED Anzeige aktualisieren
    display.clearDisplay();
    display.setCursor(0,0);
    display.setTextSize(1);
    display.print("Frequenz: "); display.print(frequency, 0); display.println(" Hz");
    
    display.setCursor(0, 25);
    display.setTextSize(2);
    display.print(smoothedCap, 1);
    display.println(" pF");
    
    display.setTextSize(1);
    display.setCursor(0, 50);
    display.print("Offset: "); display.print(offset, 2);
    display.display();

    if (Serial.read() == 'k' || digitalRead(calButtonPin) == LOW) {
      offset = rawCapacity;
      display.clearDisplay();
      display.setCursor(0,20);
      display.println("KALIBRIERT!");
      display.display();
      delay(1000);
    }
  }
  delay(100);
}
