#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Wire.h>

#define SCREEN_WIDTH 128 // Change according to your OLED screen specs
#define SCREEN_HEIGHT 64 // Change according to your OLED screen specs
#define OLED_RESET -1    // Reset pin (or -1 if not used)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

const int potPin1 = A0; // Potentiometer 1 connected to analog pin A0
const int potPin2 = A1; // Potentiometer 2 connected to analog pin A1
const int relayPin = 7; // Relay control pin

void setup() {
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, LOW);

  // Initialize the OLED display
  if (!display.begin(SSD1306_I2C_ADDRESS, OLED_RESET)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;);
  }
  display.display();
  delay(2000);  // Pause for 2 seconds

  // Clear the display
  display.clearDisplay();
  display.display();
}

void loop() {
  // Read potentiometer values
  int potValue1 = analogRead(potPin1);
  int potValue2 = analogRead(potPin2);

  // Calculate frequencies based on potentiometer values
  float freq1 = map(potValue1, 0, 1023, 1, 100); // Adjust the range and values as needed
  float freq2 = map(potValue2, 0, 1023, 1, 100); // Adjust the range and values as needed

  // Display frequency values on OLED
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.print("Freq 1: ");
  display.print(freq1);
  display.println(" Hz");
  display.print("Freq 2: ");
  display.print(freq2);
  display.println(" Hz");

  // Generate waveforms on analog pins A0 and A1
  float waveValue1 = 0.5 + 0.5 * sin(millis() * 2 * PI * freq1 / 1000.0); // Sine wave on A0
  float waveValue2 = 0.5 + 0.5 * sin(millis() * 2 * PI * freq2 / 1000.0); // Sine wave on A1

  // Write the waveform values to the analog pins
  analogWrite(A0, waveValue1 * 255); // Convert the 0-1 range to 0-255
  analogWrite(A1, waveValue2 * 255); // Convert the 0-1 range to 0-255

  // Check if the frequencies are the same and trigger the relay
  if (abs(freq1 - freq2) < 0.1) {
    digitalWrite(relayPin, HIGH); // Activate the relay
  } else {
    digitalWrite(relayPin, LOW); // Deactivate the relay
  }

  display.display();

  // Adjust the delay to control the refresh rate of the display and waveforms
  delay(100);
}