Programming On Raspberry Pi With Python: Activate LED and Buzzer on Motion Detection

In previous post we started exploring hardware side of Raspberry Pi. We learned how to make connections with GPIO pins and control the LED. Lets go one step further and write program to detect motion and send the notifiction on telegram channel.


In this article we will cover below things:

- Printing message on terminal when motion is detected
- Connecting PIR motion detection sensor, buzzer and LED to GPIO pins
- Activating the buzzer and LED on motion detection


We are using Raspberry Pi 3 B+ model.


Requirements:

We will require below components (apart from Raspberry Pi obviously :D ) to make this work.

- Breadboard
- Jumper Wires
- Buzzer (Optional)
- LED 
- Resistors
- PIR motion detection sensor



Printing message on terminal when motion is detected:

Here we will print a simple message 'motion detected' on the screen when motion is detected by PIR motion detection sensor. To know more about working of PIR motion detection sensor please refer this wikipedia article.


Connections:

PIR motion detection sensor have three pins. If you remove the plastic cover from the PIR sensor, you will be able to see which pin needs to be connected to where. Refer the picture below.


pir motion sensor


Left pin needs to be connected to 5v pin, middle pin will be send the output when motion is detected and right pin will be connected to ground pin.

So we connect the left pin to 2nd pin of GPIO set on Raspberry Pi. Middle one to any pin which can be set to receive the output, 11 in our case and right pin to 6th pin. See the image with connections below.


pir motion sensor connections

Connection diagram:

pir motion sensor connections


Python Program:

Now lets understand the code which print message on screen when motion is detected.

import RPi.GPIO as GPIO
import time

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
# Read output from PIR motion sensor
GPIO.setup(11, GPIO.IN)  

while True:
    inp = GPIO.input(11)
    # When output from motion sensor is HIGH
    if 1 == inp:               
        print("motion detected")

    time.sleep(0.1)

As discussed in previous article as well, we set the mode to GPIO.BOARD which means pin number is its position on board. We set pin number 11 to read the output from PIR sensor.

We check if output from pin number 11 is high, if yes print message on screen. Then sleep for 0.1 seconds and repeat it.


Activate the python3 virtual environment. Install RPi.GPIO package is not installed already. pip install RPi.GPIO.

Save the above program and run it. Move your hand in front of sensor and you will see the output on screen. 

python pir_basic.py


AAAAAElFTkSuQmCC

If motion is not detected, please make sure connections are correct. Try tuning the two knobs on PIR sensor.



Connecting Buzzer and LED:

This time when motion is detected we will activate a buzzer and turn on the LED. 

This is the first time we will be connecting more than one component on breadboard. Please follow below instructions to make connections.

- Connect pin 2 (5v) to live column of breadboard.
- Connect pin 6 (ground) to ground column of breadboard.
- Connect left pin (5v) of PIR sensor to live column of breadboard.
- Connect middle pin (output) to pin 11 of GPIO pin set of Raspberry Pi.
- Connect right pin (ground) to ground column of breadboard.
- Connection of PIR sensor is done using breadboard. Now lets connect the LED and buzzer.
- Connect the positive end of LED (longer leg) to pin 36 but with 220 ohm resistor in between. Refer previous article
- Connect the neutral end of LED (smaller leg) to ground column on breadboard.
- Connect the Positive terminal of buzzer to pin 36. Connect negative terminal to ground column of breadboard.


Refer below diagram and picture for connections.


pir motion sensor connections


motion detection


Python Code:

Python code for these connections will be almost same with only difference of sending output to pin 36 whenever motion is detected.

Use below code. Comment has been added with each line to make it easy to understand.


#
# Motion detection with buzzer and LED
# Author - https://www.pythoncircle.com
#

import RPi.GPIO as GPIO
import time

LED_PIN = 36
GPIO.setwarnings(False)
# refer pins by their sequence number on board
GPIO.setmode(GPIO.BOARD)
# Read output from PIR motion sensor
GPIO.setup(11, GPIO.IN)
# LED output pin
GPIO.setup(LED_PIN, GPIO.OUT)

while True:
    i = GPIO.input(11)
    # When output from motion sensor is LOW
    if i == 0:
        print("No motion")
        # Turn OFF LED and buzzer
        GPIO.output(LED_PIN, 0)
    # When output from motion sensor is HIGH
    elif i == 1:
        print("motion detected")
        # Turn ON LED and buzzer
        GPIO.output(LED_PIN, 1)

    time.sleep(0.1)


When you run the above code and motion is detected, LED is turned on and buzzer is activated. 

If something is not working for you, feel free to comment.




Programming on Raspberry Pi with Python: Controlling LED

In the first and second articles of the series 'Programming on Raspberry Pi with Python' we learned how to setup Raspberry Pi, configure WIFI and enable SSH.

In third article, we created a python script to send the IP address of Raspberry Pi on reboot to a telegram channel and scheduled it in crontab.

Now is the time to start exploring hardware side of Raspberry Pi. In this article we will control the LED (light emitting diode) via GPIO pins of Raspberry Pi by Python program.

Programming on Raspberry Pi with Python: Raspberry Pi Setup

Programming on Raspberry Pi with Python: WIFI and SSH configuration

Programming on Raspberry Pi with Python: Sending IP address on Telegram channel on Raspberry Pi reboot


We are using Raspberry Pi 3 B+ model.



Requirements:

 - Raspberry Pi 3B+ 
 - Jumper wires
 - Breadboard
 - LED 
 - Resistors



Understanding GPIO pins:

I strongly recommend you to visit https://www.raspberrypi.org/documentation/usage/gpio/ for better understandig the GPIO pins of your Raspberry Pi.

Alternatively you can go to command prompt of your Raspberry Pi and run the command pinout which will present you a handy reference of GPIO pins.


gpio pins pinout command


You can refer the instruction card received along with canakit.


gpio pins pinout command



Connections:

Lets connect the components together.

- Connect pin 36 ( we will refer pins by literal sequence number, here pin 36 is GPIO pin 16 in above pic) with the live/voltage row on breadboard.
- Connect pin 6 (ground) with ground row on breadboard.
- Now connect a 220 ohm resistor with live row and positive terminal of LED.
- Connect the negative/ground terminal with ground row of breadboard.
- Use jumper wires for above connections. Refer my hand drawn diagram below for connections.


breadboard connections raspberry pi


L and G stands for live and ground respectively. 



Python Program:

Use below python code to control the LED.

import RPi.GPIO as GPIO
import time

PIN = 36

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(PIN, GPIO.OUT)         #LED output pin

while True:
    GPIO.output(PIN, 0)  #Turn OFF LED
    time.sleep(1)
    GPIO.output(PIN, 1)  #Turn ON LED
    time.sleep(1)

First we imported the RPi.GPIO module.
Since we will be dealing with pin number 36, lets define it in a variable PIN.

Set the mode to GPIO.BOARD, which means we are referring pin number by their position on board.
Set the pin 36 to receive output.

Until loop is terminal, set the output to false/0/low on pin 36 and then sleep for 1 second. In next lines, set the output to true/1/high and then sleep for 1 second. 

I clicked the below pictures to show LED in two states i.e. on and off. Look closely and try to figure out the connections.

LED Turned Off:

led controll raspberry pi

LED Turned On:

breadboard connections raspberry pi


Try it out and if you are stuck anywhere feel free to comment.


Purchase Raspberry Pi Starter Kit Here.


References:




Programming on Raspberry Pi with Python: Sending IP address on Telegram channel on Raspberry Pi reboot

In first article we completed the Raspberry Pi Setup, installed OS on SD card and updated the packages. We were connected to Raspberry Pi using LAN cable and external monitor via HDMI cable.

In second article we configured WIFI and enabled SSH. We were not using LAN cable to connect the system. We were able to ssh into Raspberry Pi from our laptop. 

Programming on Raspberry Pi with Python: Raspberry Pi Setup

Programming on Raspberry Pi with Python: WIFI and SSH configuration


But there was one problem. How do we know the local IP address of Raspberry Pi when it reboots. We will address the same issue in this article.

We will create a python script which will run on every reboot and will send the IP address to a telegram channel.

We are using Raspberry Pi 3 B+ model.


Telegram Channel and Bot:

 - First we need to create a telegram bot and add it as administrator to the desired telegram channel where you wish to receive the messages.

 - Follow this step by step article on how to create a telegram channel and add a telegram bot to it as administrator



Python Script:

 - Login to your Raspberry pi.

 - First create a virtual environment using python3. We will install all the required packages and dependencies in this virtual environment using pip.

 - Please refer this article to create virtual environment, to activate it and intalling the packages.

 - Create a file, requirements.txt and paste below content in it. It is a list of packages you will require for your future python programms.

aiohttp==3.3.2
async-timeout==3.0.0
attrs==18.1.0
certifi==2018.4.16
chardet==3.0.4
future==0.16.0
idna==2.7
idna-ssl==1.0.1
multidict==4.3.1
pkg-resources==0.0.0
python-telegram-bot==10.1.0
requests==2.7.0
telebot==0.0.3
telepot==12.7
urllib3==1.23
yarl==1.2.6

 - Activate the virtual environment and install the telegram package in it using the command pip install -r requirements.txt.

 - Now create a python script with below content.

import telegram
import subprocess
import time

time.sleep(60)
bot = telegram.Bot(token="YOUR BOT TOKEN GOES HERE")
msg = subprocess.check_output("hostname -I", shell=True).decode('ascii')
status = bot.send_message(chat_id="@YOUR CHANNEL ID", text=msg, parse_mode=telegram.ParseMode.HTML)
print(status)

We are using telegram package.

Since this script will be executed after Raspberry pi reboot, we introduced sleep time of 60 seconds in the scripts so that by then Raspberry Pi is connected to the available network.

Then in next line we created the bot. Use your bot token. Refer this article to find out how to get the bot token.

Then run the command hostname -I and collect its output and send it to the channel.


Scheduling Script:

 - Once script is ready, run it manually inside the virtual environment using python3 to test the output.

 - Now edit the crontab using command crontab -e.

 - Append the below line in crontab.

@reboot ~/py3venv/bin/python3 ~/practice/startup_scripts/ip.py

Use the python3 path and script path accordingly.



Now this script will be executed at every reboot of Raspberry pi and the newly assigned IP address will be sent to you on your telegram channel which you can use to SSH into it.


In the screenshot below you can see, IP address reported by Python script and temprature of Raspberry Pi every 10 minutes.


telegram channel raspberry pi ip address and temprature


References:

 - How to create completely automated telegram channel with python


Purchase Raspberry Pi Starter Kit Here.





SUBSCRIBE
Please subscribe to get the latest articles in your mailbox.



Recent Posts:





© pythoncircle.com 2018-2019