I'm trying to build a circuit that buzzes until a button is pressed, or it buzzes 5 times:
void alarm()
{
int AlarmState = 0; //Just to get while loop going
int count = 1;
while(AlarmState==0)
{
int count = 1;
AlarmState = digitalRead(alarmStop);
digitalWrite(buzz,HIGH);
AlarmState = digitalRead(alarmStop);
delay(500);
AlarmState = digitalRead(alarmStop);
digitalWrite(buzz,LOW);
AlarmState = digitalRead(alarmStop);
delay(500);
count++;
if(count>=5){
break;
}
}
I put a bunch of digitalRead's so it has a better chance of catching the button press while the loop is going, there's a better way to do that I'm sure but it's not my main concern right now.
This is part of a larger project, but I hope I've posted only the necessary code. The function runs, but does not break after count
equals 5. Why?
int count = 1;
from within the while-loop.for
loop to count to 5, and thenif (AlarmState != 0) break;
.for(unsigned char i = 0;i<5 && AlarmState != 0;i++){
? Not sure if it fits the problem, but it's a little more readable (since you can see when the loop will end, within the statement/check).&& AlarmState == 0
to match the original post, but yes, that is another way. Actually the posted code in the question reads alarmStop multiple times which is a bit alarming (no pun intended). I suppose it depends how quickly you want to react to a change in alarmStop.AlarmState = digitalRead(alarmStop);
you just read the last value. Replace all those lines withAlarmState |= digitalRead(alarmStop);
; this way as soon as one reading is 1 it will exit