// Define the pin numbers for buzzer and potentiometers
const int buzzerPin = 9;
const int tonePotPin = A0; // Connect tone potentiometer to analog pin A0
const int durPotPin = A1; // Connect pitch potentiometer to analog pin A1
const int buttonPins[] = {2, 3, 4, 5, 6, 7, 8, 10}; // Connect your buttons to these digital pins
const int switchPin = 11; // Slider switch pin

// Variables to store potentiometer readings
int tonePotValue = 0;
int durPotValue = 0;

// Define arrays to store state and timing information for keys
const int NUM_BUTTONS = 8;
int keyActive[NUM_BUTTONS] = {0}; // State of each button
unsigned long changeTime[NUM_BUTTONS] = {0}; // Timing for each button

void setup() {
  // Set buzzer pin as output
  pinMode(buzzerPin, OUTPUT);
  
  // Set button pins as input with pull-up resistors
  for (int i = 0; i < NUM_BUTTONS; i++) {
    pinMode(buttonPins[i], INPUT_PULLUP);
  }

  // Set slider switch pin as input with pull-up resistor
  pinMode(switchPin, INPUT);
}

void loop() {
  // Read potentiometer values
  tonePotValue = analogRead(tonePotPin);
  durPotValue = analogRead(durPotPin);

  // Map potentiometer values to desired range
  int Tone = map(tonePotValue, 0, 1023, 200, 2000); // Adjust 200 and 2000 as per your preference
  int dur = map(durPotValue, 0, 1023, 50, 150); // Adjust 50 and 500 as per your preference

  // Check the state of the slider switch
  bool continuousMode = digitalRead(switchPin) == LOW;

  // Check each button
  for (int i = 0; i < NUM_BUTTONS; i++) {
    // If button is pressed
    if (digitalRead(buttonPins[i]) == LOW) {
      // If button is not already active
      if (keyActive[i] == 0) {
        keyActive[i] = 1;
        changeTime[i] = millis();
        if (continuousMode) {
          // If in continuous mode, play the tone continuously
          while (digitalRead(buttonPins[i]) == LOW) {
            tone(buzzerPin, Tone);
          }
          noTone(buzzerPin);
        } else {
          playTone(buzzerPin, Tone, dur);
        }
      }
    } else {
      keyActive[i] = 0;
    }
  }

  // A small delay to avoid reading the potentiometers too quickly
  delay(10);
}

// Function to play a tone of a given frequency and duration
void playTone(int pin, int startTone, int duration) {
  int currentTone = startTone;
  int fadeStep = 5; // Adjust the step size for gradual fading

  // Start playing the tone
  tone(pin, startTone);

  // Gradually decrease the frequency
  for (int i = 0; i < duration; i += fadeStep) {
    delay(fadeStep);
    currentTone -= fadeStep;
    if (currentTone < 0) {
      currentTone = 0;
    }
    tone(pin, currentTone);
  }

  // Stop playing the tone
  noTone(pin);
}