pips
Posts: 5
Joined: Mon Apr 03, 2017 5:39 pm

Motion Sensor Python 3.0

Tue May 02, 2017 10:42 pm

Was wondering if anyone had a code for a PIR motion sensor which every time something is detected, it counts the score. This is for a basketball scoring system. I'm using Python 3.0

User avatar
jadro
Posts: 456
Joined: Sun Oct 02, 2016 1:20 pm
Location: Croatia

Re: Motion Sensor Python 3.0

Wed May 03, 2017 1:23 pm

This is code for motion detected but in python 2...

Code: Select all

#!/usr/bin/python

import RPi.GPIO as GPIO
import time
import datetime

# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

# PIR MOTION module ********************************
pir_pin = 23 
GPIO.setup(pir_pin, GPIO.IN)
LIGHT_PIN = 21 #GPIO21 / PIN 40 - last
TIME_TO_OFF_LIGHT = 0.3 #sec
GPIO.setup(LIGHT_PIN, GPIO.OUT)
GPIO.output(LIGHT_PIN, 0)

def pir_motion_init():
    print "please wait, initializing PIR MOTION sensor..."
    now = datetime.datetime.now()
    print "PIR MOTION sensor is ready - " + now.strftime("%d.%m.%Y") + " / " + now.strftime("%H:%M:%S")
    GPIO.add_event_detect(pir_pin, GPIO.RISING, callback=MOTION)
    #print("*******************************************")

def MOTION(pir_pin):
    now = datetime.datetime.now()  
    my_date = now.strftime("%d.%m.%Y")
    my_time = now.strftime("%H:%M:%S")
    my_message = "Motion-Detected-at-" + str(my_date) + "-" + str(my_time)
		print(my_message)
    motion_light_on()
    time.sleep(TIME_TO_OFF_LIGHT)
    motion_light_off()

def motion_light_off():
    GPIO.output(LIGHT_PIN, 0)
    
def motion_light_on():
    GPIO.output(LIGHT_PIN, 1)
#***************************************************

# main function
def main():
    try:
        # PIR MOTION init
        pir_motion_init()
  
        while True:   
            time.sleep(0.5)
        
    except KeyboardInterrupt:
        print " Quit"
        GPIO.cleanup()
    except Exception as e:
        print " Quit"
        GPIO.cleanup()

if __name__=="__main__":
    main()
Please compile it with Python 3 and for every error you get, please google it for function that is apropriate for Python 3...
Jadro
Oracle backend database developer
SmartHome IoT & Microprocessor enthusiast and hobbyist

Return to “General discussion”