The Setup

We are using the CircuitPython Libraries that are part of adafruit-blinka. See CircuitPython Libraries on Raspberry Pi to get a fresh Raspberry Pi setup.

If you have a running Raspberry Pi with an up to date copy of Raspbian you can simply run the following command to install adafruit-blinka. 

The software is exactly the same on all 40-pin and 20-pin Raspberry Pi models. 

$ sudo pip3 install adafruit-blinka

The Code

This project is possible the most over-engineered automatic light switch ever created. You really do not need a Raspberry Pi to turn on the Powerswitch, but the example can easily be adapted for other purposes. For example, you could use a combination of temperature, humidity, light, and perhaps some internet data on weather forecasts to turn on or off a heater, fan or humidifier.

# SPDX-FileCopyrightText: 2019 Mikey Sklar for Adafruit Industries
#
# SPDX-License-Identifier: MIT

import time
import board
from digitalio import DigitalInOut, Direction

pir_pin = board.D24
power_pin = board.D23

pir = DigitalInOut(pir_pin)
pir.direction = Direction.INPUT

power = DigitalInOut(power_pin)
power.direction = Direction.OUTPUT
power.value = False

while True:
    if pir.value:
        print("POWER ON")
        power.value = True
        time.sleep(20)
        print("POWER OFF")
        power.value = False
        time.sleep(5)
    time.sleep(1)

The program first sets up the two GPIO pins that are used, one as an input to the PIR sensor and one as an output for the Powerswitch Tail.

The main loop then just waits for the PIR sensor to sense movement and then prints a message and turns on the Powerswitch tail, waits 20 seconds then turns it off again.

It the output was turned on, it waits for 5 seconds to prevent immediate retriggering.

There is also always a 1 seconds delay each time around the loop.

This guide was first published on Feb 18, 2013. It was last updated on Mar 29, 2024.

This page (Software) was last updated on Mar 29, 2024.

Text editor powered by tinymce.