Hi,
I am really new to this, but have cobbled together a project that simply sounds an alarm and flashes lights if the fridge door is left open.
My switch is a magnet switch, and so far this all works very well, except the alarm goes off immediately the door is opened.
I have played with delay(), but it just seems to cause more problems than it solves.
Can anyone give me pointers on how I can tweak this code so that when the switch is opened, a 120 seconds countdown begins, only then sounding the alarm. However, if the door is closed and the switch closed, the alarm cancels and returns to monitoring?
Any help would be hugely appreciated,
Mike
// constants won't change. Used here to set a pin number :
const int greenledPin = 3; // the number of the LED pin
const int redledPin = 4; // the number of the LED pin
const int magSwitch = 5; // the number of the Magnetic Switch
const int alarmBuzzer = 6; // the number of the Buzzer
// Variables will change :
int ledState = LOW; // ledState used to set the LED
int magswitchState = 0; // variable for reading the mag switch status
// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0; // will store last time LED was updated
// constants won't change :
const long interval = 750; // green interval at which to blink (milliseconds)
void setup() {
// set INPUTS OUTPUTS
pinMode(greenledPin, OUTPUT);
pinMode(redledPin, OUTPUT);
pinMode(magSwitch, INPUT);
pinMode(alarmBuzzer, OUTPUT);
}
void loop() {
// here is where you'd put code that needs to be running all the time.
// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
unsigned long currentMillis = millis();
// read the state of the mag switch value:
magswitchState = digitalRead(magSwitch);
if (magswitchState == LOW) {
digitalWrite(redledPin, LOW);
digitalWrite(alarmBuzzer, LOW);
// GREEN LED
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
// set the LED with the ledState of the variable:
digitalWrite(greenledPin, ledState);
}
} else {
digitalWrite(greenledPin, LOW);
digitalWrite(redledPin, HIGH);
digitalWrite(alarmBuzzer, HIGH);
delay(100);
digitalWrite(alarmBuzzer, LOW);
delay(100);
}
}