#!/usr/bin/python

# Import der Python libraries
import RPi.GPIO as GPIO
import time
import datetime

# We use the Board Mode, enter the PIN number instead of the GPIO BCM number
GPIO.setmode(GPIO.BOARD)

# define GPIO, 7 because my sensor is connected to Pin7
GPIO_PIR = 7

print "Motionsensor Test (CTRL-C for exit)"
print "========================================="

#  define GPIO as an "Input"
GPIO.setup(GPIO_PIR,GPIO.IN)

Current_State  = 0
Previous_State = 0

try:

 print "%s: initialize Sensor ..." % datetime.datetime.now()

 # waiting for signal of the Sensor
 while GPIO.input(GPIO_PIR)==1:
   Current_State  = 0

 print "%s: Ready! Waiting for motion..."  % datetime.datetime.now()

 # Loop until CTRL+C
 while True :

   #Getting status of the Sensor
   Current_State = GPIO.input(GPIO_PIR)

   if Current_State==1 and Previous_State==0:

     print " %s: Motion detected!" % datetime.datetime.now()
     Previous_State=1

   elif Current_State==0 and Previous_State==1:

     print " %s: Ready! Waiting for motion..."  % datetime.datetime.now()
     Previous_State=0

   time.sleep(0.01)

except KeyboardInterrupt:
 print " Exit"
 GPIO.cleanup()
