1

I am trying to have a magnetic door sensor be detected after every time it connects and disconnects. I have looked at this as a guide, but I am stuck at on part when compiling.

Traceback (most recent call last): File "sensor_test.py", line 9, in pin.DOOR_SENSOR_PIN = 18 NameError: name 'pin' is not defined

My code looks like this

import RPi.GPIO as GPIO
import time
import sys
import signal


GPIO.setmode(GPIO.BCM)
pin.DOOR_SENSOR_PIN = 18

isOpen = None
oldIsOpen = None

GPIO.setup(DOOR_SENSOR_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)

while True:
   oldIsOpen = isOpen
   isOpen = GPIO.input(DOOR_SENSOR_PIN)

isOpen = None
oldIsOpen = None

GPIO.setup(DOOR_SENSOR_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)

while True:
oldIsOpen = isOpen
isOpen = GPIO.input(DOOR_SENSOR_PIN)

if(isOpen and (isOpen != oldIsOpen)):
elif(isOpen != oldIsOpen):
    print "Sensor is connected"
    #sock.send("open")
time.sleep(0.1)

Most errors I've read says that the "import RPi.GPIO as GPIO" is missing or the setmode is missing, but I have both of those. Any help would be appreciated!

  • 2
    what happens if you remove pin. from the code – Jaromanda X Nov 8 '18 at 3:14
  • >'DOOR_SENSOR_PIN' is not defined – Logan Vanderbeck Nov 8 '18 at 3:50
  • 2
    The page you referenced is just poorly formatted html. the "pin.' is part of the comment on the previous line. There are plenty of well written tutorials. NOTE that if you are copying code you should also include the comments - they are there for a reason! You can't just delete lines of code e.g. after if(isOpen and (isOpen != oldIsOpen)): – Milliways Nov 8 '18 at 4:22
  • 3
    You would be better to start with gpiozero – Milliways Nov 8 '18 at 4:31
  • @LoganVanderbeck - I didn't mean that whole line ... I said remove pin. - so remove exactly what I said to remove – Jaromanda X Nov 8 '18 at 22:11
3

Skip the pin. so that

pin.DOOR_SENSOR_PIN = 18

turns into

DOOR_SENSOR_PIN = 18

because that is just what is needed and what is used further down the script, e.g.:

# here
GPIO.setup(DOOR_SENSOR_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)
# here
isOpen = GPIO.input(DOOR_SENSOR_PIN)
# and here
GPIO.setup(DOOR_SENSOR_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)

DOOR_SENSOR_PIN is just supposed to be a constant that prevents you from putting a magic number (18) in every statement where it is used - which is error prone once you start changing it. This way you change it once and be done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.