Untitled
unknown
plain_text
a year ago
3.0 kB
9
Indexable
Never
// Define the digital pin number for the square wave output const int outputPin = 9; const int LEDPin = 12; // 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 volatile unsigned long duration = 10000; // Initial duration // 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); pinMode(LEDPin, 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(); Serial.print("Frequency is: "); Serial.println(frequency); } // Loop function runs repeatedly after setup void loop() { tone(outputPin, frequency, duration); // Generate the square wave } // Function to update the square wave frequency void updateFrequency() { // Calculate the duration based on the desired frequency to maintain consistent pulse density duration = 1000000 / frequency; // Convert frequency to microseconds } // Function to decrease the frequency void decreaseFrequency() { // Calculate the new frequency after decreasing by 10% unsigned long newFrequency = frequency*0.9; // Check if the new frequency is above the minimum if (newFrequency >= minFrequency) { frequency = newFrequency; // Update the frequency digitalWrite(LEDPin, LOW); //turn off LED updateFrequency(); // Update the output Serial.print("Frequency decreased to: "); Serial.println(frequency); } else { Serial.println("Frequency is already at the minimum value."); digitalWrite(LEDPin, HIGH); //turn on LED; } } // Function to increase the frequency void increaseFrequency() { // Calculate the new frequency after increasing by 10% unsigned long newFrequency = frequency*1.1; // Check if the new frequency is below the maximum if (newFrequency <= maxFrequency) { frequency = newFrequency; // Update the frequency digitalWrite(LEDPin, LOW); //turn off LED updateFrequency(); // Update the output Serial.print("Frequency increased to: "); Serial.println(frequency); } else { Serial.println("Frequency is already at the maximum value."); digitalWrite(LEDPin, HIGH); //turn on LED ; } }