Rpi Projects

From Network Security Wiki

Playing with GPIO for first time

My setup for GPIO LED test

Source: GPIO Examples

  • Install wiringPi.
  • Run following command to verify GPIOs:
gpio readall
  • Connect a LED & ~1000Ω resistor to GPIO.0(Pin 11) & 0V(Pin 6).
  • Boot Pi On.
  • Run the following commands:
gpio mode 0 out
gpio write 0 1
gpio write 0 0
  • LED should flash On & Off.
  • To automate this process, use the following python code:
nano ledtest.py
 import RPi.GPIO as GPIO
import time

# Use physical pin numbers
# Set up header pin 11 (GPIO17) as an input
print "Setup Pin 11"
GPIO.setup(11, GPIO.OUT)

print "Start loop"
while var==1 :
  print "Set Output False"
  GPIO.output(11, False)
  print "Set Output True"
  GPIO.output(11, True)
  • Now run the following command to check:
sudo python ledtest.py
  • LED should alternatively switch on & off.
  • Press Ctrl+C to stop this code.

Control Raspberry Pi with IR Sensor

Source: AdaFruit, Weedpi

LIRC Rpi control
LIRC Schematic
  • CHQB IR Receiver is used here. Other IR Receiver like TSOP38238, etc also work.
  • Connect Pins as follows:
Pin 1 Pin 12 GPIO 18 Data
Pin 2 Pin 6 GND Gnd
Pin 3 Pin 1 3.3v Vcc
  • Installing LIRC
sudo apt-get install lirc
  • Test the IR Reveiver:
sudo modprobe lirc_rpi
sudo kill $(pidof lircd)
mode2 -d /dev/lirc0

If pressing remote key produces similar to the following output, the IR receiver is working correctly:

space 9025951
pulse 286
pulse 2314773
pulse 2277668
space 446984
  • Edit /etc/modules file & add:
lirc_rpi gpio_in_pin=18
  • Change your /etc/lirc/hardware.conf file to:
# /etc/lirc/hardware.conf
# Arguments which will be used when launching lircd

# Don't start lircmd even if there seems to be a good config file

# Don't start irexec, even if a good config file seems to exist.

# Try to load appropriate kernel modules

# Run "lircd --driver=help" for a list of supported drivers.
# usually /dev/lirc0 is the correct setting for systems using udev

# Default configuration files for your hardware if any
  • Restart lircd:
sudo /etc/init.d/lirc stop
sudo /etc/init.d/lirc start
  • List of allowed key names when programming the remote
irrecord --list-namespace
  • Follow the instructions to map the remote
irrecord -d /dev/lirc0 ~/lircd.conf
  • Once complete copy the lircd.conf file to /etc/lirc directory
sudo cp ~/lircd.conf /etc/lirc
  • Restart LIRC
sudo /etc/init.d/lirc restart
  • Test the new remote conf file

Following output should appear on pressing 1, 2 and 3 keys on the remote:

0000000000fd08f7 00 KEY_1
0000000000fd08f7 01 KEY_1
0000000000fd08f7 02 KEY_1
0000000000fd8877 00 KEY_2
0000000000fd8877 01 KEY_2
0000000000fd8877 02 KEY_2
0000000000fd48b7 00 KEY_3
  • To assign actions when keys are pressed create a file named lircrc in the /etc/lirc directory
sudo nano /etc/lirc/lircrc

Paste the following lines:

prog = irexec
button = KEY_0
config = sudo halt
repeat = 0

prog = irexec
button = KEY_1
config = omxplayer -o local --vol -2000
repeat = 0

prog = irexec
button = KEY_5
config = sudo killall omxplayer.bin
repeat = 0

“remote” is the name you will find in your lircd.conf file you created before. If you do not have multiple remotes you can skip this variable and it will use the default remote. “button” is the value that you assigned to button when you configure your remote usiong irrecord utility “config” is the executable (with its parameters) to be run when the button is pressed

  • Once you save this file stop and start the lircd deamon as follows
sudo /etc/init.d/lirc stop
sudo /etc/init.d/lirc start

LED controlling using LIRC

Source Ozzmaker

LIRC LED control
LIRC LED Schematic
  • Wire the circuit around a breadboard as shown in the diagram.
  • Install wiringPi.
  • Save the following code as "lirc-led.c":
#include <wiringPi.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <lirc/lirc_client.h>
#include <time.h>

void flipLED (int led);

//The WiringPi pin numbers used by our LEDs
#define LED1 2
#define LED2 3
#define LED3 4
#define LED4 5
#define LED5 6

#define ON 1
#define OFF 0

int main(int argc, char *argv[])
        struct lirc_config *config;

        //Timer for our buttons
        int buttonTimer = millis();

        char *code;
        char *c;

        //Initiate WiringPi and set WiringPi pins 4, 5 & 6 (GPIO 23, 24 & 25) to output. These are the pins the LEDs are connected to.
        if (wiringPiSetup () == -1)
            exit (1) ;

        pinMode (LED1, OUTPUT);
        pinMode (LED2, OUTPUT);
        pinMode (LED3, OUTPUT);
        pinMode (LED4, OUTPUT);
        pinMode (LED5, OUTPUT);

        //Initiate LIRC. Exit on failure

        //Read the default LIRC config at /etc/lirc/lircd.conf  This is the config for your remote.
                //Do stuff while LIRC socket is open  0=open  -1=closed.
                        //If code = NULL, meaning nothing was returned from LIRC socket,
                        //then skip lines below and start while loop again.
                        if(code==NULL) continue;{
                                //Make sure there is a 400ms gap before detecting button presses.
                                if (millis() - buttonTimer  > 400){
                                        //Check to see if the string "KEY_1" appears anywhere within the string 'code'.
                                        if(strstr (code,"KEY_1")){
                                                printf("MATCH on KEY_1\n");
                                                buttonTimer = millis();
                                        else if(strstr (code,"KEY_2")){
                                                printf("MATCH on KEY_2\n");
                                                buttonTimer = millis();
                                        else if(strstr (code,"KEY_3")){
                                                printf("MATCH on KEY_3\n");
                                                buttonTimer = millis();
                                        else if(strstr (code,"KEY_4")){
                                                printf("MATCH on KEY_4\n");
                                                buttonTimer = millis();
                                        else if(strstr (code,"KEY_5")){
                                                printf("MATCH on KEY_5\n");
                                                buttonTimer = millis();
                        //Need to free up code before the next loop
                //Frees the data structures associated with config.
        //lirc_deinit() closes the connection to lircd and does some internal clean-up stuff.
void flipLED (int led)
        //If LED is on, turn it off. Otherwise it is off, so thefore we need to turn it on.
                digitalWrite(led, OFF);
                digitalWrite(led, ON);
  • Compile the above code with;
gcc -o lirc-led lirc-led.c -lwiringPi -llirc_client
  • Create an empty lirc file, if it already not exists:
touch /etc/lirc/lircrc
  • Execute it:
sudo ./lirc-led


Source: Piscope

PiScope running

Using Raspberry Pi as an Oscillator.

Download executable at Laptop/Desktop
wget http://abyz.co.uk/rpi/pigpio/piscope.tar
tar xvf piscope.tar
make x86_64
Install pigpio in Raspberry Pi
wget abyz.co.uk/rpi/pigpio/pigpio.zip
unzip pigpio.zip
make install
Launch the pigpio daemon On the Pi
sudo pigpiod
On Desktop

export PIGPIO_ADDR= && ./piscope

Digital Clock using 7 Segment Display

7 segment 4 digit display(China made)
7 Segment Clock Diagram
Digital Clock

Source: Hackyourmind.org

I have used a 7 Segment 4 digit display commonly available in china made MP3 players for this project.

Rpi-hw Library Install
sudo apt-get install g++-4.7 cmake
sudo ln -fs /usr/bin/g++-4.7 /usr/bin/g++
git clone https://github.com/Wicker25/Rpi-hw
cd Rpi-hw*
sudo make install
Create mytime.hpp file
nano /home/pi/Clock/mytime.hpp
#include <iostream>
#include <ctime>

int get_time() {

time_t raw = time(0);
struct tm *now = localtime( &raw );

return now->tm_min + 100 * now->tm_hour;
Create timer.cpp file
nano /home/pi/Clock/timer.cpp
// Include Rpi-hw headers
#include <rpi-hw.hpp>
#include <rpi-hw/time.hpp>
#include <rpi-hw/iface/decoder-out.hpp>
#include <rpi-hw/display/m7seg.hpp>

#include "mytime.hpp" // Function `get_time` seen above

// Use Rpi-hw namespace
using namespace rpihw;

main( int argc, char *args[] ) {

// Create the display controller
display::m7seg dev( 1, 4, 18, 15, 14, 0, 17, 23 );

iface::decoderOut enabler( { 25, 24, 22, 21 } );
dev.setDisplays( 4, enabler );

// Set the updating frequency (Hz)
//dev.setFreq( 100.0 );

// Main loop
for ( ;; ) {

// Update the current time
dev.set( get_time() );

// Wait a second

return 0;
g++ `pkg-config --libs --cflags rpi-hw` -o timer timer.c
sudo ./timer

Eyesight protection system

Source: Universal Raspberry Pi Remote & Ultrasonic Distance Measurement

        This section is under construction.

This project is used to turn off TV when a child is sitting too close to the Television Screen.

Requirements(apart from Raspberry pi)
  1. IR LED
  2. HC-SR04 Ultrasonic Range Sensor
  3. NPN Transistor
  4. Resistor
Wiring up the circuit diagram
Testing LIRC setup

List all of the commands that LIRC knows for 'samsung_tv'

irsend LIST samsung_tv ""

Send the KEY_POWER command once

irsend SEND_ONCE samsung_tv KEY_POWER
Testing HC-SR04 Distance Sensor
#include <wiringPi.h>
# ultrasonic_2.py
# Measure distance using an ultrasonic module
# in a loop.
# Author : Matt Hawkins
# Date   : 28/01/2013

# -----------------------
# Import required Python libraries
# -----------------------
import time
import RPi.GPIO as GPIO

# -----------------------
# Define some functions
# -----------------------

def measure():
  # This function measures a distance
  GPIO.output(GPIO_TRIGGER, True)
  GPIO.output(GPIO_TRIGGER, False)
  start = time.time()

  while GPIO.input(GPIO_ECHO)==0:
    start = time.time()

  while GPIO.input(GPIO_ECHO)==1:
    stop = time.time()

  elapsed = stop-start
  distance = (elapsed * 34300)/2

  return distance

def measure_average():
  # This function takes 3 measurements and
  # returns the average.
  distance = distance1 + distance2 + distance3
  distance = distance / 3
  return distance

# -----------------------
# Main Script
# -----------------------

# Use BCM GPIO references
# instead of physical pin numbers

# Define GPIO to use on Pi
GPIO_ECHO    = 24

print "Ultrasonic Measurement"

# Set pins as output and input
GPIO.setup(GPIO_ECHO,GPIO.IN)      # Echo

# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER, False)

# Wrap main content in a try block so we can
# catch the user pressing CTRL-C and run the
# GPIO cleanup function. This will also prevent
# the user seeing lots of unnecessary error
# messages.

  while True:

    distance = measure_average()
    print "Distance : %.1f" % distance

except KeyboardInterrupt:
  # User pressed CTRL-C
  # Reset GPIO settings

Run the code as:

sudo python ultrasonic_2.py
Final script for the project
        This code being compiled

Pi On-Off Shutdown Button

Source: element14.com, howchoo.com, howchoo.com

Switch Layout
Switch installed
  • We will create a Python Script to turn off the Pi when GPIO 3 state is changed to Down by shorting it to Ground Pin(5).
  • These Two pins (5 & 6) can be again momentarily shorted to wake the Raspberry Pi from the halted state.
  • Recent changes to the bootcode.bin file will now allow the Raspberry Pi to be started by momentarily connecting pins 5 & 6.
  • Be careful as power pins are located right next to these pins and you could permanently damage your Raspberry Pi if you accidentally short a pin to the 5v power pin.

  • Creating a Python Script
mkdir scripts  
cd scripts  
touch shutdown_pi.py  
nano shutdown_pi.py  
  • Paste the following
import RPi.GPIO as GPIO
import time
import os

# Use the Broadcom SOC Pin numbers
# Setup the Pin with Internal pullups enabled and PIN in reading mode.
GPIO.setup(3, GPIO.IN, pull_up_down = GPIO.PUD_UP)

# Our function on what to do when the button is pressed
def Shutdown(channel):
  os.system("sudo shutdown -h now")

# Add our function to execute when the button pressed event happens
GPIO.add_event_detect(3, GPIO.FALLING, callback = Shutdown, bouncetime = 2000)

# Now wait!
while 1:
  • Test the Script
sudo python shutdown_pi.py
  • Adding it to startup
sudo nano /etc/rc.local
sudo python3 /home/pi/scripts/shutdown_pi.py &
  • Enable the GPIO serial port to enable Status LED Support

Newer versions of Raspbian Jessie have the GPIO serial port disabled by default:

sudo nano /boot/config.txt

Pi Console Access

Source elinux.org

Pi Console Access
  • Use USB To RS232 TTL Adapter such as this one found on ebay.in
  • Connect the Apapter to the Rpi GPIO's as below
RPi Pin no Adapter Cable Function
Pin 6 Black GND
Pin 8 White Tx
Pin 10 Green Rx
  • You should be a member of the dialout group to access this port:
ls -l /dev/ttyUSB0
  • To find out if you are a member of group dialout:
  • If you do not see dialout listed, add yourself:
sudo usermod -a -G dialout username
  • For Raspberry pi 3 you need to enable UART:
sudo nano /boot/config.txt
  • Now run GNU Screen:
sudo screen /dev/ttyUSB0 115200

To exit GNU screen, type Control-A k.

  • Alternatively you can use Minicom:
minicom -b 115200 -o -D Port_Name

You can exit Minicom with Control-A x

Thingspeak Temperature Logger

Source: iotleague.com

import http.client, urllib.request, urllib.parse, urllib.error
import time

key = 'XMM5GRL6YP741HBN'

while True:
        temp = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3
        params = urllib.parse.urlencode({'field1': temp, 'key':key })
        headers = {"Content-typZZe": "application/x-www-form-urlencoded","Accept": "text/plain"}
        conn = http.client.HTTPConnection("api.thingspeak.com:80")
            conn.request("POST", "/update", params, headers)
            response = conn.getresponse()
            print(temp, response.status, response.reason)
            data = response.read()
            print("connection failed")

Thingspeak Resources Logger


0 * * * * sudo python3 /home/pi/thingspeak.py
@reboot sudo python3 /home/pi/thingspeak.py

import socket
import json
from time import strftime,localtime,sleep
import requests
import os
import logging

key = "XMM5GRL6YP741HBN"

#Create and configure logger
logging.basicConfig(filename="/var/log/rpistats.log", format='%(asctime)s %(message)s', filemode='a')

# Check Internet connectivity
def is_connected():
    host = socket.gethostbyname("www.google.com")
    s = socket.create_connection((host, 80), 2)
    return True
    return False

def cpu_utl():
    last_idle = last_total = 0
    with open('/proc/stat') as f:
        fields = [float(column) for column in f.readline().strip().split()[1:]]
    idle, total = fields[3], sum(fields)
    idle_delta, total_delta = idle - last_idle, total - last_total
    last_idle, last_total = idle, total
    utilisation = 100.0 * (1.0 - idle_delta / total_delta)
    return '%5.1f' % utilisation

def count_files():
    x = os.popen('ls /home/pi/Downloads/ | wc -l').read().strip()
    y = os.popen('ls /home/pi/Incoming/ | wc -l').read().strip()
    return int(x) + int(y)

def thing():
    #cpu = int(100 - float(os.popen('top -bn1 | head -n 3 | grep "Cpu"').read().split()[7]))
    #temp = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3
    cpu = cpu_utl()
    temp = int(float(os.popen('/opt/vc/bin/vcgencmd measure_temp').read().split('=')[-1].strip('\'C\n')))
    mem = os.popen('free -m').read().split()[-9]
    swap = os.popen('free -m').read().split()[-2]
    hdd = os.popen('df -m /').read().split()[-2].strip('%')
    load = os.popen('cat /proc/loadavg').read().split()[0]
    uptime = "{0:0.1f}".format(float(os.popen('cat /proc/uptime').read().split()[0])/3600)
    count = count_files()
    ctime = strftime("%Y-%m-%d %H:%M:%S +0530", localtime())

    logger.info(str(("Data Fetched=",ctime, " Temp=",temp, " cpu=",cpu, " mem=",mem, " swap=",swap, " hdd=",hdd, " load=",load, " Count=",count)))

    # Upload Temperature Data to thingspeak.com
    payload = {"write_api_key":key,"updates":[{"created_at":ctime,"field1":temp,"field2":cpu,"field3":mem,"field4":swap,"field5":hdd,"field6":load,"field7":uptime,"field8":count}]}
    url = 'https://api.thingspeak.com/channels/512987/bulk_update.json'
    headers = {'content-type': 'application/json'}
    response = requests.post(url, data=json.dumps(payload), headers=headers)
    return response

while True:
    if is_connected():
        response = thing()
        if response.status_code == 202:
            logger.info(("Data successfully uploaded= ", str(response.status_code)))
            logger.error(("HTTP Error Code= ", str(response.status_code)))
        logger.error('Error: Internet Connection down, Retrying after 60 seconds\n')


Virtual Pin read random Data

Source github.com

  • Create a project in Blynk App.
  • Copy Auth Code received via email.
  • Drag a Value Display Widget in Blynk.
  • Set the Pin to Virtual Pin 11.
  • Change the Read Rate from PUSH to 5 Seconds.
  • Go to Raspberry Pi & create a file:
nano blynk_vread.py
  • Paste the below code & change the Auth Code:
import blynklib
import random

BLYNK_AUTH = 'YourAuthToken'

# initialize blynk
blynk = blynklib.Blynk(BLYNK_AUTH)


# register handler for virtual pin V11 reading
@blynk.handle_event('read V11')
def read_virtual_pin_handler(pin):
    blynk.virtual_write(pin, random.randint(0, 255))

while True:

Virtual Pin read SenseHat Data

from sense_hat import SenseHat
import blynklib

sense = SenseHat()

blynk = blynklib.Blynk(BLYNK_AUTH)

@blynk.handle_event('read V11')
def read(pin):
    HUM = '{:.2f}'.format(sense.humidity)
    PRES = '{:.2f}'.format(sense.pressure)
    TEMP = '{:.2f}'.format(sense.temperature)
    blynk.virtual_write(11, HUM)
    blynk.virtual_write(12, PRES)
    blynk.virtual_write(13, TEMP)
    print(HUM,'% ',PRES,'mb ',TEMP,'C')

while True:

{{#widget:DISQUS |id=networkm |uniqid=Rpi Projects |url=https://aman.awiki.org/wiki/Rpi_Projects }}