I’ve done this by putting a relay directly in the backlight circuit. Connect the PIR to 5V and a gpio pin, and the relay to 5V and another GPIO pin. Use wiring pi and a simple bash script to get the state of the PIR and energize/de-energize the relay appropriately. It’s really simpler than it sounds and requires little to no knowledge of electronics.
You need to first install wiring-pi
sudo wget https://project-downloads.drogon.net/wiringpi-latest.deb
sudo dpkg -i wiringpi-latest.deb
Here’t the script I run at startup to control it - works great.
#!/bin/bash
#
# Runs in the background to switch backlight on or off
# depending upon the state of the PIR motion sensor.
#
# Usage: nohup backlightd [-r|-f] 0<&- &>/dev/null &
# -r log on loghost
# -f log locally (default)
#
# Set as configured
PIR=18 # GPIO BCM number of PIR sensor
BACKL=15 # GPIO BCM number of backlight relay
OFF_DEL=60 # Minimum number of seconds to keep backlight om
ON_DEL=2 # Minimum number of seconds to keep backlight off
TIMO=3600 # Maximum number of seconds to wait for edge event
#
# Set for local policies
PRIO=local.info # if using rsyslog set priority
TAG=backlightd # and tag to use on loghost
LOGFILE=/var/log/backlightd.log # if using local syslog file
PATH=/bin:/usr/bin
# error handling
xit() { rlog "Line $1 Err $2 - $3 - exiting"; exit "$2"; }
die() { rlog "Exit signal received - exiting"; exit 0; }
# logging
case $1 in
-r) rlog() { /usr/bin/logger -p "${PRIO}" -t "${TAG}" "$1"; } ;;
*) rlog() { /bin/echo "$1" >>"${LOGFILE}" ; } ;;
esac
cd / || xit $LINENO $? "Cannot cd to / ?!?"
reset(){
# reset gpio pins, set initial conditions
gpio edge "$PIR" both \
|| xit $LINENO $? "Cannot set edge GPIO$PIR"
gpio export "$BACKL" out \
|| xit $LINENO $? "Cannot set export GPIO$BACKL"
PIR_STATE=$(gpio -g read "$PIR") \
|| xit $LINENO $? "Cannot read GPIO$PIR"
gpio -g write "$BACKL" "$PIR_STATE" \
|| xit $LINENO $? "Cannot write to GPIO$BACKL"
}
trap reset SIGUSR1
trap die SIGTERM
reset
while true
do
timeout "$TIMO" gpio -g wfi "$PIR" both ; STAT=$?
if [ "$STAT" -eq 124 ]; then
rlog "gpio wfi timed out after ${TIMO}s - respawning"
STAT=0
fi
[ "$STAT" ] || xit $LINENO $STAT "gpio wfi terminated abnormally"
PIR_STATE=$(gpio -g read "$PIR") \
|| xit $LINENO $? "Cannot read GPIO$PIR"
gpio -g write "$BACKL" "$PIR_STATE" \
|| xit $LINENO $? "Cannot write GPIO$PIR"
if [ "$PIR_STATE" ]
then sleep "$ON_DEL"
else sleep "$OFF_DEL"
fi
done