Welcome to Hackster!
Hackster is a community dedicated to learning hardware, from beginner to pro. Join us, it's free!
ElectroPeak
Published © GPL3+

PIR Motion Sensor: How to Use PIRs w/ Arduino & Raspberry Pi

Learn how to use a PIR motion sensor to detect movement. You will also learn how PIR motion sensors work and how to use them.

BeginnerProtip1 hour209,687
PIR Motion Sensor: How to Use PIRs w/ Arduino & Raspberry Pi

Things used in this project

Hardware components

ElectroPeak HC-SR501 PIR Sensor
×1
Arduino UNO R3
×1
Raspberry Pi 3 Model B+
×1

Story

Read more

Code

Arduino Code

Arduino
/*

PIR HCSR501 

modified on 5 Feb 2019
by Saeed Hosseini @ ElectroPeak
https://electropeak.com/learn/guides/

*/
 
int ledPin = 13;                // LED 
int pirPin = 2;                 // PIR Out pin 
int pirStat = 0;                   // PIR status
 
void setup() {
  pinMode(ledPin, OUTPUT);     
  pinMode(pirPin, INPUT);     
 
  Serial.begin(9600);
}
 
void loop(){
  
  pirStat = digitalRead(pirPin); 
   
  if (pirStat == HIGH) {            // if motion detected
    digitalWrite(ledPin, HIGH);  // turn LED ON
    Serial.println("Hey I got you!!!");

  } 
  else {
    digitalWrite(ledPin, LOW); // turn LED OFF if we have no motion
   
  }
}

Raspberry Pi Code

Python
import sys
sys.path.append('/home/pi/Adafruit-Raspberry-Pi-Python-Code/Adafruit_CharLCD')
from Adafruit_CharLCD import Adafruit_CharLCD

lcd=Adafruit_CharLCD()     # instantiate LCD Display
lcd.clear()

from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)     # set up BCM GPIO numbering

# Set up input pin
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

# Set up LED output
GPIO.setup(20, GPIO.OUT)

# Callback function to run when motion detected
def motionSensor(channel):
    lcd.clear()
    GPIO.output(20, GPIO.LOW)
    if GPIO.input(21):     # True = Rising
        global counter
        counter += 1
        lcd.message('Motion Detected\n{0}'.format(counter))
        GPIO.output(20, GPIO.HIGH)

# add event listener on pin 21
GPIO.add_event_detect(21, GPIO.BOTH, callback=motionSensor, bouncetime=300) 
counter = 0

try:
    while True:
        sleep(1)         # wait 1 second

finally:                   # run on exit
    GPIO.cleanup()         # clean up
    print "All cleaned up."

Credits

ElectroPeak
57 projects • 742 followers
At ElectroPeak we want to teach you to enjoy electronics more. We offer Top-notch guides and worry-free shopping experience.
Contact

Comments

Please log in or sign up to comment.