I'm having a problem with this Arduino code.
So whenever I press the "button" in port 11, which is supposed to either reset the burglar alarm or stop it, the whole program stops (the void loop() function stops). The wiring is most likely not the problem, because I've tested it on multiple occasions with different codes. The button, too, works perfectly well as a button with different codes.
In the Serial port, it keeps printing "78005", which it should before the button is pressed, until when I press the button, at which it randomly breaks off printing (resulting in 78, 780, 7, 7800, or 78005 as the last line printed).
Can anyone explain why the arduino will behave in this way?
Thank you so much.
int button = 11;
int receiver = 12;
int buzzer = 13;
int frequency = 1000; // frequency of buzzer
bool keepAlerting = false; // toggles Alarm regardless of detected charge
int receiverVal = LOW; // value from port 12
int buttonVal = LOW; // value from button
int oldButtonVal = LOW;
int setupTime = 5000; // time the user has to close the box after toggling alarm
bool alarmOn;
int buttonMode = 0;
const int resetButton = 1;
const int stopButton = 2;
int buttonModeDecider = 0;
void setup() {
// put your setup code here, to run once:
pinMode(buzzer, OUTPUT);
pinMode(receiver, INPUT);
pinMode(button, INPUT);
Serial.begin(9600);
noTone(buzzer);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.print("7");
receiverVal = digitalRead(receiver);
buttonVal = digitalRead(button);
Serial.print("8");
if(alarmOn == true){
Serial.print("6");
setAlarm();
}
Serial.print(buttonVal);
Serial.print(oldButtonVal);
if(buttonVal == HIGH && oldButtonVal == LOW){
buttonModeDecider = 1 - buttonModeDecider;
Serial.print("Toggled");
if(buttonModeDecider == 1){
buttonMode = resetButton;
Serial.print("1");
} else {
buttonMode = stopButton;
Serial.print("2");
}
switch(buttonMode) {
case resetButton:
{
delay(setupTime);
alarmOn = true;
break;
Serial.print("3");
}
case stopButton:
{
alarmOn = false;
Serial.print("4");
}
}
}
Serial.println("5");
oldButtonVal = buttonVal;
}
void setAlarm() {
if(receiverVal == LOW || keepAlerting == true) {
tone(buzzer, frequency);
keepAlerting = true;
}
}
INPUT
mode notINPUT_PULLUP
, this means you added yourself a pullup or pulldown resistor "between" your button and the input pin, can you confirm this wiring? And then the opposite button side is connected to GND (if you use a pullup resistor) or +5V (if you use a pulldown resistor). A bad wiring here could make your program fail unexpectedly.