Hi,
I'm doing my assignment for school and I've came across this problem in my code. When the laser is interrupted the alarm goes off like it should. The problem with my code is when I try to reset it with a button. The purpose of the button is to turn the laser back to high which therefore, turns the alarm off. Practically if the alarm is on the laser is off and when the alarm is off the laser is on. The button works as intended but only when its being held down. When I let go of it, the alarm restarts. I want the alarm to turn off and the laser to go back to high when the button is pressed. Thanks.
This project uses a laser, photoresistor/ldr, a button and a buzzer.
int laserPin = 4;
int photoresistorPin = A1;
int buttonPin = 5;
int buzzerPin = 3;
int threshold = 12;
void setup() {
pinMode(laserPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
}
bool alarm = false;
void loop() {
if (alarm == false) {
delay(1000);
digitalWrite(laserPin, HIGH);
delay(10);
unsigned long current = millis();
while (millis() - current < 1000) {
int Value = analogRead(laserPin);
if (Value > threshold) {
alarm = true;
break;
}
delay(10);
}
digitalWrite(laserPin, LOW);
} else {
tone(buzzerPin, 440);
if (!digitalRead(buttonPin)) {
alarm = false;
noTone(buzzerPin);
}
delay(10);
}
}
It's a simple state machine using your boolean to represent the state
if the alarm is off, you need to check if the laser beam is interrupted and in that case trigger the alarm state
if the alarm is on, you need to check if the button is being pressed and in that case restore the watch state
const byte laserPin = 4;
const byte photoresistorPin = A1;
const byte buttonPin = 5;
const byte buzzerPin = 3;
const int threshold = 12;
bool alarmIsOn = false;
void setup() {
pinMode(buzzerPin, OUTPUT);
pinMode(laserPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
digitalWrite(laserPin, HIGH);
}
void alarmIsOn() {
if (alarm) {
// alarm is sounding/on, check if the stop button is pressed
if (digitalRead(buttonPin) == LOW) {
alarm = false;
digitalWrite(laserPin, HIGH);
noTone(buzzerPin);
}
} else {
// alarm is off, check if the laser beam is interrupted
if (analogRead(photoresistorPin) > threshold) {
alarm = true;
digitalWrite(laserPin, LOW);
tone(buzzerPin, 440);
}
}
}