

### PIR sensor

import RPi.GPIO as GPIO                           #Import GPIO library
import time                                       #Import time library
import os
import threading
import datetime

gain = str(-1200)    #sets the gain of the audio output

GPIO.setmode(GPIO.BOARD)                          #Set GPIO pin numbering
pir = 26                                       #Associate pin 26 to pir 
GPIO.setup(pir, GPIO.IN)                          #Set pin as GPIO in 

#######################  threading Plays the background music file eerie_sounds_7Hr.mp3

def play_clip():
    playing_clip = 1
    zzz = 'omxplayer ' + ' -o both --vol -1800 --loop ' +'/home/pi/distance/distance_audio_clips/eerie.mp3'
    print zzz
    os.system(zzz)

threading.Thread(target=play_clip).start() #Plays background music
#########################

j=1     #### Sound file index number Gets incemented after each playback
i=1     ### dummy variable for loop   

while 1==1:             ## 
    
    
    print "Waiting for sensor to settle ",j
    time.sleep(2)                                     #Waiting 2 seconds for the sensor to initiate
    print "Detecting motion"
     
    while True:
       
       filename = str(j)+'.mp3'             # sets the file name to be played
       if GPIO.input(pir):                            #Check whether pir is HIGH
          ttime = datetime.datetime.now()          # saves the detection time
          print "Motion Detected!   ", filename,'  ',str(ttime)[0:19]  #
          xxx='omxplayer -o both --vol '+gain+ ' /home/pi/distance/distance_audio_clips/'+filename 
          os.system(xxx)                            ## Play audio clip
          if j == 25:               # 
              j=0
          j=j+1
          print "Detecting motion"
          file = open ('/home/pi/distance/logfile.txt','a')
          file.write(filename + '   '+str(ttime)[0:19]+'\n')
          file.close()
        

          
          time.sleep(2)                               #D1- Delay to avoid multiple detection
       time.sleep(0.1)                                #While loop delay should be less than detection(hardware) delay
      

