焦電センサとHueを使って部屋の照明を自動ON/OFFする

公開日時
更新日時

RaspberryPiと焦電(人感)センサPhilips Hueを組み合わせて、部屋の照明の自動制御ができるようにした。

Hueアプリにある「やる気を出す」という照明色をよく使っているが、元電源をOFFにして点け直すとデフォルトの暖色に戻ってしまうので都度アプリを起動して色の変更を行っていた。

焦電センサ導入により、自動ON時にAPIで「やる気を出す」モードの色を指定できるのでアプリを立ち上げる手間が省けた。

import RPi.GPIO as GPIO
import time
import requests
from datetime import datetime

PIN = 23
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.IN)

HUE_API = 'http://{hue_bridge_ip}/api/{user_id}/lights/{light_id}/state'

def now():
  return datetime.now().strftime("%Y/%m/%d %H:%M:%S")

def light_on():
  print('%s on' % now())
  requests.put(HUE_API, json = { "on": True, "bri": 254, "ct": 156 })

def light_off():
  print('%s off' % now())
  requests.put(HUE_API, json = { "on": False })

count = 0
try:
  while True:
    if (GPIO.input(PIN) == GPIO.HIGH):
      if (count < 0):
        count = 0
      count += 1
    else:
      if (count > 0):
        count = 0
      count -= 1

    if count == -300: # 1min
      light_off()
    if count == 10: # 5sec
      light_on()

    time.sleep(0.2)
except KeyboardInterrupt:
  GPIO.cleanup()

Hue APIのユーザID登録等は下記のデバッグ機能を使って行った。

http://{bridgeのip}/debug/clip.html

参考


Related #raspberry pi