Skip to main content leehalls.net

PIR Controlled Pi Display

Dragelec did at one time update via socketio to a flask based website showing temperatures, electricity usage and local weather but rather than leaving the display on all the time i added a PIR to turn it on/off whenever a presence was detected, the following is the complete code;

python code snippet start

#!/usr/bin/env python

# PiDisplay v0.00 - PIR controlled display, turning backlight on/off
# to be run as a daemon by placing in the /usr/local/bin/mydaemon/
# folder, it borrowed heavily from:
# http://www.ofbrooklyn.com/2014/01/2/building-photo-frame-raspberry-pi-motion-detector/
# but on checking today [2019-08-10 Sat] it appears that site is dead.
# whilst transferring old content to new domain [2020-05-11 Mon 21:53], a check of links indicates the site is back up

import RPi.GPIO as GPIO
import time
import logging, logging.handlers
import argparse
import sys

#defaults
GPIO.setmode(GPIO.BCM)
PIR_PIN = 24
GPIO.setup(PIR_PIN, GPIO.IN)
offDELAY=600 # seconds
#daemonLOG='/tmp/backlight.log'
#logging.basicConfig(filename=daemonLOG,level=logging.DEBUG)
#loghandler = logging.handlers.TimedRotatingFileHandler(
#        daemonLOG, when="midnight", backupCount=3)

LOG_FILENAME = "/tmp/backlightPIR.log"
LOG_LEVEL = logging.INFO  # Could be e.g. "DEBUG" or "WARNING"

# Define and parse command line arguments
parser = argparse.ArgumentParser(description="My simple Python service")
parser.add_argument("-l", "--log", help="file to write log to (default '" + LOG_FILENAME + "')")


# If the log file is specified on the command line then override the default
args = parser.parse_args()
if args.log:
          LOG_FILENAME = args.log

# Configure logging to log to a file, making a new file at midnight and keeping the last 3 day's data
# Give the logger a unique name (good practice)
logger = logging.getLogger(__name__)
# Set the log level to LOG_LEVEL
logger.setLevel(LOG_LEVEL)
# Make a handler that writes to a file, making a new file at midnight and keeping 3 backups
handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when="midnight", backupCount=3)
# Format each log message like this
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
# Attach the formatter to the handler
handler.setFormatter(formatter)
# Attach the handler to the logger
logger.addHandler(handler)

# Make a class we can use to capture stdout and sterr in the log
class MyLogger(object):
  def __init__(self, logger, level):
    """Needs a logger and a logger level."""
    self.logger = logger
    self.level = level

  def write(self, message):
    # Only log if there is a message (not just a new line)
    if message.rstrip() != "":
      self.logger.log(self.level, message.rstrip())
      # Replace stdout with logging to file at INFO level
      sys.stdout = MyLogger(logger, logging.INFO)
      # Replace stderr with logging to file at ERROR level
      sys.stderr = MyLogger(logger, logging.ERROR)

def main():
  last_motion_time=time.time()
  turned_off=False
  while 1:
    if GPIO.input(PIR_PIN):
      last_motion_time=time.time()
      if turned_off:
        turned_off=False
        piDisplay(0) # turn on backlight
    else:
      if not turned_off and time.time()>(last_motion_time+offDELAY):
        turned_off=True
        piDisplay(1)

    time.sleep(1)

def piDisplay(val):
    file=open('/sys/devices/platform/rpi_backlight/backlight/rpi_backlight/bl_power','r+')
    current_status=int(file.read(1))
    logging.info('Setting BL 0=ON/1=OFF: %s @ %s' % (val,time.ctime()))
    file.seek(0)
    file.write(str(val))
    file.close


print('PIR Module Test (CTRL+C to exit)')
logging.info('backlight control service started@time: %s',(time.ctime()))
time.sleep(2)

try:
    main()
except KeyboardInterrupt:
  print('Quit')
  GPIO.cleanup()

python code snippet end