1

I am trying to have a magnetic door sensor be detected after every time it connects and disconnects. I have looked atthis 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 GPIOimport timeimport sysimport signalGPIO.setmode(GPIO.BCM)pin.DOOR_SENSOR_PIN = 18isOpen = NoneoldIsOpen = NoneGPIO.setup(DOOR_SENSOR_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)while True:   oldIsOpen = isOpen   isOpen = GPIO.input(DOOR_SENSOR_PIN)isOpen = NoneoldIsOpen = NoneGPIO.setup(DOOR_SENSOR_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)while True:oldIsOpen = isOpenisOpen = 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!

askedNov 8, 2018 at 2:37
Logan Vanderbeck's user avatar
5
  • 2
    what happens if you removepin. from the codeCommentedNov 8, 2018 at 3:14
  • >'DOOR_SENSOR_PIN' is not definedCommentedNov 8, 2018 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. afterif(isOpen and (isOpen != oldIsOpen)):CommentedNov 8, 2018 at 4:22
  • 3
    You would be better to start withgpiozeroCommentedNov 8, 2018 at 4:31
  • @LoganVanderbeck - I didn't meanthat whole line ... I saidremovepin. - so remove exactly what I said to removeCommentedNov 8, 2018 at 22:11

1 Answer1

3

Skip thepin. 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.:

# hereGPIO.setup(DOOR_SENSOR_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)# hereisOpen = GPIO.input(DOOR_SENSOR_PIN)# and hereGPIO.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.

answeredNov 8, 2018 at 7:16
Ghanima's user avatar

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.