5

mail@pastecode.io avatarunknown
c_cpp
a month ago
2.6 kB
2
Indexable
Never
// Define the digital pin number for the square wave output
const int outputPin = 9;

// Define initial, minimum, and maximum frequencies in Hz
volatile unsigned long frequency = 10000; // Initial frequency
const unsigned long minFrequency = 1000;  // Minimum frequency
const unsigned long maxFrequency = 20000; // Maximum frequency

// Define digital pins for the left and right buttons
const int leftButtonPin = 2;  // Left button
const int rightButtonPin = 3; // Right button

// Setup function runs once on startup
void setup() {
  // Set the output pin as OUTPUT
  pinMode(outputPin, OUTPUT);
  
  // Set the left and right button pins as INPUT_PULLUP
  pinMode(leftButtonPin, INPUT_PULLUP);
  pinMode(rightButtonPin, INPUT_PULLUP);

  // Attach interrupts for button presses
  attachInterrupt(digitalPinToInterrupt(leftButtonPin), increaseFrequency, FALLING);
  attachInterrupt(digitalPinToInterrupt(rightButtonPin), decreaseFrequency, FALLING);
  
  // Start serial communication at 9600 bps
  Serial.begin(9600);

  // Initialize the output frequency
  updateFrequency();
}

// Loop function runs repeatedly after setup
void loop() {
  // No code needed here
}

// Function to update the square wave frequency
void updateFrequency() {
  // Calculate the duration based on the desired frequency to maintain consistent pulse density
  unsigned long duration = 1000000 / frequency; // Convert frequency to microseconds
  tone(outputPin, frequency, duration); // Generate the square wave
}

// Function to decrease the frequency
void decreaseFrequency() {
  // Calculate the new frequency after decreasing by 10%
  unsigned long newFrequency = frequency - (frequency * 0.1);
  
  // Check if the new frequency is above the minimum
  if (newFrequency >= minFrequency) {
    frequency = newFrequency; // Update the frequency
    updateFrequency(); // Update the output
    Serial.print("Frequency decreased to: ");
    Serial.println(frequency);
  } else {
    Serial.println("Frequency is already at the minimum value.");
  }
}

// Function to increase the frequency
void increaseFrequency() {
  // Calculate the new frequency after increasing by 10%
  unsigned long newFrequency = frequency + (frequency * 0.1);
  
  // Check if the new frequency is below the maximum
  if (newFrequency <= maxFrequency) {
    frequency = newFrequency; // Update the frequency
    updateFrequency(); // Update the output
    Serial.print("Frequency increased to: ");
    Serial.println(frequency);
  } else {
    Serial.println("Frequency is already at the maximum value.");
  }
}