oliver
Posts: 26
Joined: Sun Mar 30, 2014 4:53 pm

motion sensor code

Sun Mar 30, 2014 5:07 pm

hi
i have been trying to make a motion sensor turn on a buzzer when motion was sensed but for some reason i get this error

Motion Detected!
Traceback (most recent call last):
File "motion.py", line 21, in MOTION
if (pirState == False):
UnboundLocalError: local variable 'pirState' referenced before assignmen

this is my code:

import RPi.GPIO as GPIO
import time

pirVal = False
pirState = False

GPIO.setmode(GPIO.BOARD)
PIR_PIN = 26
GPIO.setup(PIR_PIN, GPIO.IN)
GPIO.setup(11, GPIO.OUT)
GPIO.output(11, False)

def MOTION(PIR_PIN):
print "Motion Detected!"
while True:
pirVal = GPIO.input(PIR_PIN)
if (pirVal == True):
GPIO.output(11, True)
time.sleep(1)
pirVal = False
if (pirState == False):
pirState = True
if (pirState == True):
time.sleep(2)
pirState = False;

print "PIR Motion Test (CTRL+C to exit)"
time.sleep(2)
print "Ready"

try:
GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION)
while 1:
time.sleep(100)

except KeyboardInterrupt:
print " Cancel"
GPIO.cleanup()


could someone please help as it is the holidays now and i am 11 i have looked throuh the web but i dont understand the answers
the indents are in there but they went when i copied it

thanks in advance
olly

User avatar
paddyg
Posts: 2554
Joined: Sat Jan 28, 2012 11:57 am
Location: UK

Re: motion sensor code

Sun Mar 30, 2014 6:06 pm

Olly, I suspect you are suffering from globals. Generally these should be avoided at all costs... However you have to use them with the GPIO callback system (I've commented on this before so won't rant about it) Python's behaviour wrt variable scope is rather confusing (and you should google and read about it) but your code might work if you put in a line making the variables explicitly global:

Code: Select all

def MOTION(PIR_PIN):
  global pirVal, pirState
  print "Motion Detected!"
  while True:
    pirVal = GPIO.input(PIR_PIN)
    if pirVal:
      GPIO.output(11, True)
      time.sleep(1)
      pirVal = False
    if not pirState:
      pirState = True
    if pirState:
      time.sleep(2)
      pirState = False;
When you paste code in posts, highlight it and click the code button at the top.

Also you don't need brackets on if lines in python and you don't need to test if a boolean variable is equal to True
also https://groups.google.com/forum/?hl=en-GB&fromgroups=#!forum/pi3d

oliver
Posts: 26
Joined: Sun Mar 30, 2014 4:53 pm

Re: motion sensor code

Sun Mar 30, 2014 7:32 pm

thanks

Return to “Python”