When Door Closed, there are following two serial print happen at the same time
Door Open
Door Close
This means I want to when I open the door then the serial print door open & door close then the serial print door close only 1 time (loop should be closed when one event (Door Open or Door Close) Done.
Arduino Code
const int SensorInput = 2;
byte lastSensorState = LOW;
void setup() {
Serial.begin(115200);
pinMode(SensorInput, INPUT);
}
void loop() {
byte SensorState = digitalRead(SensorInput);
if (SensorState != lastSensorState)
{
lastSensorState = SensorState;
Serial.println(“Door Open”);
if (SensorState == LOW)
{
Serial.println(“Door Close”);
}
}
}
It’s not a false reading. Your code is doing exactly what you told it to do. You need to work though your code to see what happens.
If we start at the beginning you set lastSensorState to LOW. Now, through the loop. Let’s start with SensorState HIGH. the first if statement is true so it prints “Door Open” and sets lastSensorState to HIGH. SensorState is HIGH so the second if statement is false and we return to the beginning of the loop. Nothing happens until SensorState goes LOW. Then the first If statement is now true. (lastSensorState == HIGH and SensorState == LOW). So, it again prints “Door Open” and sets lastSensorState to LOW. The second if statement is now true (SensorState == LOW) so it prints “Door Close”. This will repeat over and over as you see.
You’ll need to fix your logic. What you want to do is to add another if statement inside the beginning if statement. So, if SensorState == LOW it prints “Door Close” OR if SensorState == HIGH it prints “Door Open”.
Hi.
You need to add a debounce code to prevent false readings.
Do you know how to do that?
There’s a basic example on the Arduino IDE. Go to File > Examples > Digital > Debounce.
Additionally, you can use debounce + interrupts. We have the following example with the ESP32:
It sends notifications when the door sensor changes state, but you can ignore the sections that use Telegram.
Here’s the code:
Let me know if you need further help.
Regards,
Sara
Your guidance is so helpful.
Your support is gratifying. Thank you for your support