Go Down

Topic: switch button to turn buzzer off? (Read 436 times) previous topic - next topic


I'm fairly new to Arduino, though I've been playing around with a couple of projects.

I have figured out how to create a circuit to turn on a buzzer, but my goal is to figure out how to have the buzzer turn on and have a switch button turn it off.

I'm working on a time limit so if anyone has any tips or helpful information that would be great!


Nov 05, 2018, 10:08 pm Last Edit: Nov 05, 2018, 10:13 pm by DVDdoug
You'll need at least one if-statement.

You may also need some 'and' or 'or' logic.

Take a look at the Button Example to get an idea how to read a button, and then "do something" based on the button state.

turn on and have a switch button turn it off.
Remember that your program ("sketch") runs in a loop.    So, you'll need to make sure the program doesn't loop-around and immediately turn the buzzer back on after you push the button to stop it.     And, you should think about what happens next, after you push the button and the buzzer stops...

You can add more loops inside the main loop (and you can make more nested loops).  There are for-loops (the most common type of loop), do-while loops, and while() loops.

So, I'm thinking a while() loop...  After the buzzer is turned-on, you enter a while() loop and you just stay in that loop (doing nothing) "while" the button is not pushed.   When the button is pushed, the loop ends, and you go-on from there...   But, I haven't really thought-through your program.  That's just what pops-into my mind.

The two most important concepts in programming are conditional execution (if statements, etc.)  and loops  (doing something over-and-over, usually until some condition is reached).   Once you understand those two concepts you can start to write useful programs.


One useful tip is that we can usually help a lot better if you post the code you currently have. It's really difficult working out what changes might be needed to something you've never seen.



Nov 05, 2018, 11:45 pm Last Edit: Nov 05, 2018, 11:46 pm by Cwaynert
The code I started with.. which not too surprisingly doesn't work (I'm still figuring out how to do coding)


const int buttonPin = 2;
 const int buzzerPin = 13;
 int buttonState = 0;
void setup() {
 // put your setup code here, to run once:
pinMode(buzzerPin, OUTPUT);
pinMode(buttonPin, INPUT);

void loop() {
 // put your main code here, to run repeatedly:
buttonState = digitalRead(buttonPin);

if (buttonState = HIGH) {
 digitalWrite(buzzerPin, LOW);
} else {
 digitalWrite(buzzerPin, HIGH);

and the circuit photo is attached (the alarm is wrapped in a sock cause it's incredibly loud)


buttonState = HIGH assigns the value HIGH to buttonState. In the if() you want == which will compare buttonState to HIGH.

Whether that will do what you want depends on how the button is wired.


Go Up