Untitled
c_cpp
a month ago
1.8 kB
1
Indexable
Never
const int outputPin = 9; // Digital pin for the square wave output volatile unsigned long frequency = 10000; // Initial frequency in Hz const unsigned long minFrequency = 1000; // Minimum allowed frequency in Hz const unsigned long maxFrequency = 20000; // Maximum allowed frequency in Hz const int leftButtonPin = 2; // Digital pin for the left button const int rightButtonPin = 3; // Digital pin for the right button void setup() { pinMode(outputPin, OUTPUT); pinMode(leftButtonPin, INPUT_PULLUP); pinMode(rightButtonPin, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(leftButtonPin), increaseFrequency, FALLING); attachInterrupt(digitalPinToInterrupt(rightButtonPin), decreaseFrequency, FALLING); Serial.begin(9600); updateFrequency(); } void loop() { // No code needed here } 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 } void decreaseFrequency() { unsigned long newFrequency = frequency - (frequency * 0.1); if (newFrequency >= minFrequency) { frequency = newFrequency; updateFrequency(); Serial.print("Frequency decreased to: "); Serial.println(frequency); } else { Serial.println("Frequency is already at the minimum value."); } } void increaseFrequency() { unsigned long newFrequency = frequency + (frequency * 0.1); if (newFrequency <= maxFrequency) { frequency = newFrequency; updateFrequency(); Serial.print("Frequency increased to: "); Serial.println(frequency); } else { Serial.println("Frequency is already at the maximum value."); } }