Untitled

mail@pastecode.io avatarunknown
plain_text
a month ago
1.5 kB
2
Indexable
Never
const int outputPin = 5; // Output pin for square wave
const int button1Pin = 2; // Button 1 pin
const int button2Pin = 3; // Button 2 pin
const int ledPin = 13; // LED pin

volatile float frequency = 10000.0; // Initial frequency
volatile bool outOfRange = false; // Flag for out of range frequency

void setup() {
  pinMode(outputPin, OUTPUT);
  pinMode(button1Pin, INPUT_PULLUP);
  pinMode(button2Pin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);

  attachInterrupt(digitalPinToInterrupt(button1Pin), decreaseFrequency, FALLING);
  attachInterrupt(digitalPinToInterrupt(button2Pin), increaseFrequency, FALLING);

  Serial.begin(9600);
}

void loop() {
  if (outOfRange) {
    digitalWrite(ledPin, HIGH);
    Serial.println("Error: Frequency out of range!");
    outOfRange = false;
  } else {
    digitalWrite(ledPin, LOW);
    float halfPeriod = (500000.0 / frequency); // Calculate half period in microseconds
    digitalWrite(outputPin, HIGH);
    delayMicroseconds(halfPeriod);
    digitalWrite(outputPin, LOW);
    delayMicroseconds(halfPeriod);
  }
}

void decreaseFrequency() {
  frequency *= 0.9;
  if (frequency < 1000.0 || frequency > 20000.0) {
    outOfRange = true;
    
  } else {
    Serial.print("Frequency decreased to ");
    Serial.print(frequency);
    Serial.println(" Hz");
  }
}

void increaseFrequency() {
  frequency *= 1.1;
  if (frequency < 1000.0 || frequency > 20000.0) {
    outOfRange = true;
  } else {
    Serial.print("Frequency increased to ");
    Serial.print(frequency);
    Serial.println(" Hz");
  }
}