It's me again with another probably quite stupid mistake. I have a simple goal: Play a tone as long as a button is pressed. Here's the code:
void setup() {
pinMode(8, OUTPUT);
pinMode(2, INPUT);
}
void loop() {
int a = digitalRead(2);
if (a = HIGH) {
tone(8, 500);
}
if (a = LOW) {
noTone(8);
}
}
When I upload this sketch, the piezo speaker starts to play the specified tone and never stops. Regardless of if I'm pressing the button or not. If I read the button state via the serial output like this:
void setup() {
pinMode(8, OUTPUT);
pinMode(2, INPUT);
Serial.begin(9600);
}
void loop() {
int a = digitalRead(2);
Serial.println(a);
if (a = HIGH) {
tone(8, 500);
}
if (a = LOW) {
noTone(8);
}
}
The serial output shows 1 when I press the button and 0 when I don't, so I know I wired the button up correctly. I also tried using 1 and 0 instead of HIGH and LOW in the if statement. Didn't work either.
Again, I feel like I'm making a basic mistake. I'd appreciate your help, thanks!