#include <Servo.h>

// Define the pins for the potentiometer, buzzer, and LED
int potPin = A0;
int buzzerPin = 13;
int ledPin = 9;

// Define the minimum and maximum frequencies for the Shepard Tone
float minFreq = 34.0; // Hz - Lowest audible frequency
float maxFreq = 115; // Hz

// Define the range of values from the potentiometer and the corresponding angle range for the servo
int potMin = 0;
int potMax = 1023;
int servoMinAngle = 0;
int servoMaxAngle = 180;

// Define the voltage threshold for LED blinking
int blinkThreshold = 100;

// Define variables for LED state and brightness
bool ledState = false;
int ledBrightness = 0;

// Create a Servo object to control the servo
Servo myServo;

void setup() {
  // Set the buzzer and LED pins as outputs
  pinMode(buzzerPin, OUTPUT);
  pinMode(ledPin, OUTPUT);

  // Attach the servo to its pin
  myServo.attach(7);
}

void loop() {
  // Read the value from the potentiometer
  int potValue = analogRead(potPin);

  // Map the potentiometer value to the frequency range of the Shepard Tone
  float freq = map(potValue, potMin, potMax, minFreq, maxFreq);

  // Generate the Shepard Tone using the tone() function
  // Use a duration of 100ms for the tone
  tone(buzzerPin, freq, 90);

  // Map the potentiometer value to the angle range of the servo
  int servoAngle = map(potValue, potMin, potMax, servoMinAngle, servoMaxAngle);

  // Set the servo angle
  myServo.write(servoAngle);

  // Map the potentiometer value to the LED brightness range
  ledBrightness = map(potValue, potMin, potMax, 0, 255);

  // If the potentiometer value is below the blink threshold, blink the LED
  if (potValue < blinkThreshold) {
    ledState = !ledState; // Toggle the LED state
    digitalWrite(ledPin, ledState ? HIGH : LOW); // Turn the LED on or off
    delay(100); // Delay for a short period to control the blink rate
  } 
  else {
    analogWrite(ledPin, ledBrightness); // Set the LED brightness to the mapped value
    delay(10); // Delay for a short period to smooth the transition
  }
}