int x;
int state = 0;
void setup() {
pinMode(2, INPUT); // Set pin 2 as input (pull-up)
pinMode(4, OUTPUT); // Set pin 4 as output
}
void loop() {
x = digitalRead(2); // Read the button state
// Toggle the state only when button is pressed
if (x == LOW) {
state = !state; // Toggle the state
if (state == HIGH) {
tone(4, 7000); // Start tone at 7kHz
} else {
noTone(4); // Stop the tone
}
// Wait until the button is released to avoid rapid toggling
while (digitalRead(2) == LOW) {
delay(10); // Small delay to avoid CPU overuse
}
}
}