Dragos Florin BrinzeiCezar Pleșu
Published © GPL3+

Sensor-Timer with Raspberry Pi 4

A timer which registry the activity and inactivity of a PIR sensor, evaluating its potentials.

IntermediateProtip3 hours1,186
Sensor-Timer with Raspberry Pi 4

Things used in this project

Hardware components

Raspberry Pi 4 Model B
Raspberry Pi 4 Model B
×1
PIR Sensor, 7 m
PIR Sensor, 7 m
×1
Resistor 1k ohm
Resistor 1k ohm
×7
Solderless Breadboard Full Size
Solderless Breadboard Full Size
×1
LED (generic)
LED (generic)
As long as the logic of the program is followed, the colours of the LEDs won't matter.
×7
Female/Female Jumper Wires
Female/Female Jumper Wires
For the PIR.
×3
Male/Female Jumper Wires
Male/Female Jumper Wires
For LEDs and connections between BreadBoard and RPi 4.
×9

Software apps and online services

Raspbian
Raspberry Pi Raspbian
Plus you will need a python editor and text editor for the Python and HTML/PHP codes. Luckily the full installation of the Raspberry Pi OS will provide them for free.

Story

Read more

Schematics

Sensor-Timer's schematic

This picture will provide you a cleaner view regard the project and positions of the wires so it will match with the python files.

Code

TimerReady.py

MicroPython
The file will prepare the main program to be launched.
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
#the code below helps you set the pins as outputs and prepares the program 

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(37,GPIO.OUT)
GPIO.setup(35,GPIO.OUT)
GPIO.setup(33,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
GPIO.setup(40,GPIO.OUT)
GPIO.setup(38,GPIO.OUT)
GPIO.setup(36,GPIO.OUT)

print("Timer Ready!")

GPIO.output(40,1)
GPIO.output(37,0)
GPIO.output(35,0)
GPIO.output(33,0)
GPIO.output(13,0)
GPIO.output(38,0)
GPIO.output(36,0)

time.sleep(0.3)

TimerStart.py

MicroPython
This is the main file of the program which will start to receive the PIR's signals and will output the total time, active time and delay time, or will attention you to start the program, or will show you the output of a controlled close of the file, or will show you the output of the IDLE stage of the program.
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time

#the code below represents the whole program which will receive signals from the sensor and registry for how long the program receives signals, plus the delays which may come
#first we set the pins as outputs for LEDs and input for sensor

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(37,GPIO.OUT)
GPIO.setup(35,GPIO.OUT)
GPIO.setup(33,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
GPIO.setup(40,GPIO.OUT)
GPIO.setup(38,GPIO.OUT)
GPIO.setup(36,GPIO.OUT)
GPIO.setup(11,GPIO.IN)

#we prepare variables which will help us detect the activity moments and record the active, inactive and delay times

VerifActiv=0
Timer=0
Inactive=0
Delay=0
print("Timer Start!")

#pattern for IDLE/inactive stage

def Inactivity():
    for Inac in range(0,5):
        GPIO.output(38,1)
        time.sleep(0.5)
        GPIO.output(38,0)
        time.sleep(0.5)

#the next 4 timers functions are patterns for each stage of time recording
#here you can set them as you want, but you need to keep the logic so you can distinguish the sections of a record
#the prints are commented as the program works, but if you not sure if it works, uncomment them and test
#each function lasts exactly 2 seconds per call (we will name a call of function "cycle")        

def Time1():
    #print("First Quarter")
    GPIO.output(37,1)
    time.sleep(1)
    GPIO.output(37,0)
    time.sleep(1)
    
def Time2():
    #print("Second Quarter")
    GPIO.output(37,1)
    time.sleep(0.7)
    GPIO.output(35,1)
    GPIO.output(37,0)
    time.sleep(0.7)
    GPIO.output(35,0)
    time.sleep(0.6)

def Time3():
    #print("Third Quarter")
    GPIO.output(37,0)
    GPIO.output(35,1)
    GPIO.output(33,1)
    time.sleep(0.5)
    GPIO.output(37,1)
    GPIO.output(35,0)
    GPIO.output(33,1)
    time.sleep(0.5)
    GPIO.output(37,1)
    GPIO.output(35,1)
    GPIO.output(33,0)
    time.sleep(0.5)
    GPIO.output(37,0)
    GPIO.output(35,0)
    GPIO.output(33,0)
    time.sleep(0.5)

def Time4():
    #print("Fourth Quarter")
    GPIO.output(37,0)
    GPIO.output(35,1)
    GPIO.output(33,1)
    GPIO.output(13,0)
    time.sleep(0.4)
    GPIO.output(37,1)
    GPIO.output(35,0)
    GPIO.output(33,0)
    GPIO.output(13,1)
    time.sleep(0.4)
    GPIO.output(37,1)
    GPIO.output(35,0)
    GPIO.output(33,1)
    GPIO.output(13,0)
    time.sleep(0.4)
    GPIO.output(37,0)
    GPIO.output(35,1)
    GPIO.output(33,0)
    GPIO.output(13,1)
    time.sleep(0.4)
    GPIO.output(37,0)
    GPIO.output(35,0)
    GPIO.output(33,0)
    GPIO.output(13,0)
    time.sleep(0.4)

#we set 2 pins as start signal and stop signal

Active=GPIO.input(40)
Stop=GPIO.input(38)

#Active=while program active
#Timer=time recorded during sensor's activity(we set a max of 40 cycles, meaning 80 seconds max)
#Inactive=max time recorded before IDLE stage where the program will automatically shutdown
#Stop=the signal which will close the program, starts as 0 so the program works. If it's 1, the program will close, so it's important to be 0 in the beginning
#NOTE: if you want your program to work infinitely, remove Timer and Inactive from the main while clause below

while Active and Timer!=40 and Inactive!=15 and not Stop:
    #we define Active and Stop again so we can be able to close the program from other terminals
    Active=GPIO.input(40)
    Stop=GPIO.input(38)
    #Detection is the infinitely signal coming from the sensor
    Detection=GPIO.input(11)
    
    if Detection==1:
        if VerifActiv==0:
            #if the program is active, makes VerifActiv 1 and resets the Inactive timer, so the program won't close
            print("Active!")
            Inactive=0
            VerifActiv=1
        #counts the cycles and activates a pattern Time function from above according to the number of cycles
        Timer+=1
        if Timer<=10:
            Time1()
        if Timer<=20 and Timer>10:
            Time2()
        if Timer<=30 and Timer>20:
            Time3()
        if Timer<=40 and Timer>30:
            Time4()
        
    elif Detection==0:
        #if program is inactive, makes VerifActiv 0
        if VerifActiv==1:
            print("Inactive!")
            VerifActiv=0
        #we count the  number of seconds we have IDLE/Delay time, 1 second each time enters here
        #Delay will calculate the whole time when sensor detects nothing, while Inactive will trigger IDLE stage if reaches max value setted
        Inactive+=1
        Delay+=1
        #print("No activity detected!")
        time.sleep(1)

#When program completes all cycles, a signal will trigger and it will output the total time of 80 seconds, plus the delay time

if Timer==40:
    print("Complet!")
    print("Total Time:",end=' ')
    print(Timer*2)
    print("Delay:",end=' ')
    print(Delay)
    GPIO.output(36,1)
    GPIO.output(40,0)
    time.sleep(0.1)

#If we start the program, without activating the Ready Stage program, the output will tell you to run that stage first

if Active==0:
    if Timer==0:
        print("You forgot to open the program.Press Ready!")
    time.sleep(0.1)

#If we stop the program from the Stop Stage while Start Stage is ongoing, we close the program
#The output will show the total time active, the delay time and during which cycle the program stopped
#NOTE: As here and in the main while, each section of the timer has 10 cycles to execute, meaning 20 seconds per section

if Stop and Active:
    print("Closed from program!")
    GPIO.output(40,0)
    print("Time on:",end=' ')
    print(Timer*2)
    print("Time delay:",end=' ')
    print(Delay)
    if Timer<=10:
        print("Delayed First Quarter.")
    if Timer<=20 and Timer>10:
        print("Delayed Second Quarter.")
    if Timer<=30 and Timer>20:
        print("Delayed Third Quarter.")
    if Timer<=40 and Timer>30:
        print("Delayed Fourth Quarter.")
    time.sleep(0.1)

        
#If the Inactive time reaches the max, the program will shutdown automatically
#The program will have same output as above, but here will show you when the program closed from its own

if Inactive==15:
    print("Program closed due IDLE!")
    print("Time on:",end=' ')
    print(Timer*2)
    if Timer<=10:
        print("IDLE First Quarter.")
    if Timer<=20 and Timer>10:
        print("IDLE Second Quarter.")
    if Timer<=30 and Timer>20:
        print("IDLE Third Quarter.")
    if Timer<=40 and Timer>30:
        print("IDLE Fourth Quarter.")
    print("Time delay:",end=' ')
    print(Delay)
    Inactivity()
    GPIO.output(38,1)
    time.sleep(0.1)
    


            
    

TimerStop.py

MicroPython
The Python file will send a signal to the main program from another terminal/tab in order to stop the program in a controlled way.
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
#the code below helps you activate a signal which will stop the main program

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(38,GPIO.OUT)

print("Timer Stop!")

GPIO.output(38,1)

time.sleep(0.5)

TimerClose.py

MicroPython
This file will close the program and deallocate the PINs of the RPi4.
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
#the code below sets the pins as outputs and closes the program properly, deallocating the pins

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(37,GPIO.OUT)
GPIO.setup(35,GPIO.OUT)
GPIO.setup(33,GPIO.OUT)
GPIO.setup(13,GPIO.OUT)
GPIO.setup(40,GPIO.OUT)
GPIO.setup(38,GPIO.OUT)
GPIO.setup(36,GPIO.OUT)

print("Timer Close!")

GPIO.output(40,0)
GPIO.output(37,0)
GPIO.output(35,0)
GPIO.output(33,0)
GPIO.output(13,0)
GPIO.output(38,0)
GPIO.output(36,0)

time.sleep(0.3)
GPIO.cleanup()

TWSproiect.php

PHP
The PHP/HTML file which represent the web page which will control the program.
 <html>
 <head>
  <?php
  //these if functions selects which selection signal will be sent to the server
  if (isset($_POST['ron'])) // START
  {
   
   $x=shell_exec('sudo python3 /var/www/html/TimerStart.py');
  }
  if (isset($_POST['roff']))  //  STOP
  {
    $x=shell_exec('sudo python /var/www/html/TimerStop.py');
  }
  if (isset($_POST['gon']))  // READY
  {
    $x=shell_exec('sudo python /var/www/html/TimerReady.py');
  }
  if (isset($_POST['goff']))  // CLOSE
  {
    $x=shell_exec('sudo python /var/www/html/TimerClose.py');
  }
  
  ?>
 <title>Proiect</title>
</head>

<body background="FX3.png">
<center>
<table witdh="400" border="1" bgcolor="silver">
<td>

<Font color='blue'><b>
<center>
Universitatea Tehnica 'Gh.Asachi' Iasi - Fac. Automatica si Calculatoare<br> 
<br>

</Font><b>


<center> <h1> <Font color='navy'>
SM PROIECT <br> Cronometru pentru detectie miscare <br>

</h1></font>
<center>
<img src="pause.png" width="385" height="282"> </center><br><br>
<form method="post" action="TWSproiect.php">
  <table
 style="width: 50%; text-align: left; margin-left: auto; margin-right: auto;"
 border="1" cellpadding="2" cellspacing="2">
      <!--Here we click a button and we select a signal which will be sent to the PHP script from above -->
      <tr>
        <td style="text-align: center;"><input type="submit"  value="START TIMER" style="color:green"  name="ron"></td>
        <td style="text-align: center;"><input type="submit"  value="STOP TIMER" style="color:red"  name="roff"></td>
      </tr></font>
      <tr><font color="green">
        <td style="text-align: center;"><input type="submit" value="TIMER READY" style="color:green"  name="gon"></td>
        <td style="text-align: center;"><input type="submit" value="TIMER RESET" style="color:red"  name="goff"></td>
      </tr></font>
      
    </tbody>
  </table>

</form>

<font color="navy">
<br>
<center> <h1> <Font color='navy'>
Afisaj cronometru <br>
<form method="post">
  <table
 style="width: 50%; text-align: left; margin-left: auto; margin-right: auto;"
 border="1" cellpadding="2" cellspacing="2">
      <tr>
	  <td><?php echo $x ?></td>
	  </tr>
	  
	</tbody>
  </table>

</form>
<br>
&copy 2021 Fac. Automatica si Calculatoare
 
</td>
</table>

</body>
</html>

Credits

Dragos Florin Brinzei
1 project • 0 followers
Creativity and engineering work superb together. Hobbyist Computer Science Engineering Student.
Cezar Pleșu
1 project • 0 followers

Comments