Leggy
Leggy

Reputation: 155

Magnetic door sensor connected to Raspberry Pi running Python script is reporting false alarms

This is such a strange issue. I'm not sure even how to troubleshoot it...

I wrote a very simple piece of code for a Raspberry Pi at the entrance of my house. It just poles the GPIO every 2 seconds to see if the circuit has been completed. It's connected via GPIO to a magnetic door sensor, like one of these: https://s3.amazonaws.com/assets.controlanything.com/photos/CKN6004-900.jpg

Here is the python code:

import os
import time
import socket
import RPi.GPIO as io
io.setmode(io.BCM)

ADDRESS = "192.168.1.118"
PORT = 1234

def doorOpened():
    "report door has been opened"
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((ADDRESS, PORT))
        s.send(b'DOOR_OPEN')
    except Exception as e:
        print("Exception: " + e)
    s.close()
    return

DOOR_PIN = 23

io.setup(DOOR_PIN, io.IN)
print("Watching over the door")
while True:
    time.sleep(2)
    if io.input(DOOR_PIN):
        doorOpened()
        time.sleep(60)

Anyways, for some reason, like maybe once a week, the alarm will get triggered falsely. Sometimes when I'm sleeping, at work, whatever. I'm not sure how the code could possibly be reading a value from the GPIO as long as the magnets are close to one another, it shouldn't complete the circuit. I've played with opening the door and they have to be about 1.5-2 inches away from one another before the the sensor gets triggered, so I have no idea how it could possibly trigger while they're basically touching (less than 1 mm apart).

So... does anyone have any ideas or explanations?

Thanks!

Upvotes: 1

Views: 1379

Answers (1)

paxdiablo
paxdiablo

Reputation: 882146

Problems that occur only 'once a week' are possibly the most annoying ones I've ever encountered in embedded systems, they make debugging particularly hard.

Here's a few things you can try:

First, investigate using other means. By that, I mean monitor the door with a recording device (e.g., video recorder) of some sort, preferably one you can moderately cross-reference to the times the alarm goes off.

Second, if it's an electrically intermittent problem (like the keybounce from old cheap keyboards we used to see), you can modify the code slightly to reduce false positives.

In other words, don't raise an alarm on the first detected issue. Instead, go in to a tighter loop and (for example) sample the input five times with a tenth of a second delay.

Then decide, based on a preponderance of the evidence, whether it was an actual alarm or not.

And, just as an aside, I wonder at the wisdom of closing a socket that may never have been opened. It's not likely to be your issue here but it would be worth cleaning up the logic in doorOpened at some point.

Upvotes: 4

Related Questions