#include <U8g2lib.h>
#include <Wire.h>
#include <math.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)

U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, 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
  u8g2.begin();
  u8g2.setPowerSave(0);

  delay(2000); // Pause for 2 seconds
  u8g2.clearBuffer();
  u8g2.sendBuffer();
}

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
  u8g2.clearBuffer();
 // u8g2.setFont(u8g2_font_profont15_tf);
 // u8g2.setCursor(0, 20);
 // u8g2.print("Freq 1: ");
 // u8g2.print(freq1);
 // u8g2.println(" Hz");
 // u8g2.setCursor(0, 0);
 // u8g2.print("Freq 2: ");
 // u8g2.print(freq2);
  //u8g2.println(" Hz");

  // Generate and display sinusoidal wave simulations
  u8g2.setFont(u8g2_font_profont15_tf);
  u8g2.setCursor(0, 60);
 // u8g2.print("Waveform:");
  drawSinWave(u8g2, 0, 35, freq1, SCREEN_WIDTH);
	 drawSinWave(u8g2, 0, 35, freq2, SCREEN_WIDTH);

  u8g2.sendBuffer();

  // 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
  }

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

void drawSinWave(U8G2 &u8g2, int x, int y, float frequency, int width) {
  float period = 1000.0 / frequency; // Period of the sine wave in milliseconds

  for (int i = 0; i < width; i++) {
    float angle = (i * 2 * PI) / period; // Calculate the angle based on time and frequency
    int yOffset = static_cast<int>(25 * sin(angle)); // Scale and offset the sine wave

    // Draw the point on the screen
    u8g2.drawPixel(x + i, y - yOffset);
  }
}