Let there be light! …when there’s motion

Razberry on Raspberry Pi + Milight + Fibaro motion sensor + Domoticz

The usual way of operating the lights in your home today is that when you step into a room you turn the lights on by pressing a switch (usually a wall switch) and you turn them off when you leave the room by pressing the switch again. But wouldn’t it be awesome if all this happened automagically, without the need to go to the switch and press it? Well, it can be done if you have some lights which are capable of being automated. But even if you have such lights, how can you automate them exactly and how can it be decided when to turn them on or off? There are many approaches to this problem. The one that we’ll discuss here is using a motion sensor to detect presence in the room and to switch the lights based on the presence. Detecting presence is a complex topic in its own because even if you’re not moving, you can still be in the room (maybe sleeping or sitting inactive). Also it’s not easy distinguishing between human and animal presence and large moving objects (curtains blown by the wind, moving pendulums, etc.) can also be a problem. But in the first step we’re going to take the easy approach and assume that there are no complications. In this context we only need to worry about two things:

  1. Turning on the lights when movement is detected
  2. Turning off the lights if no movement is sensed for a while

 

Components

Razberry on Raspberry Pi + Domoticz + Fibaro motion sensor + Milight bulb

So let’s see what we need exactly in order to achieve the above goal: turning the lights on or off based on motion (or the lack of it) in the room.

  1. First of all we obviously need some kind of smart lights or smart light bulb sockets, which can be operated remotely by some signal.
  2. The second thing that we need is a motion sensor, which sends a signal when movement is detected and stops the signal when the motion disappears.
  3. Finally we need some kind of home automation server which is running all the time and is processing events, making sure that when the motion appears or disappears, the light is switched accordingly. Note that this component is not absolutely necessary in the case when the motion sensor can communicate with the lights directly. The usual case, however, is that they can’t interact directly and that a home automation server needs to mediate between them.

Let us examine each component in detail. For the sake of easier understanding we’ll start with the home automation server and continue with the smart lights and the motion sensor.

 

The home automation server software

Domoticz logo

The home automation server software that we will be using for this project is the free and absolutely marvelous Domoticz software. To discover how to set it up and configure it on a Raspberry Pi, read this article.

 

The home automation server hardware

Razberry on Raspberry PiThe home automation server that we’re going to discuss here will be a Z-Wave server. To learn about Z-Wave and find out how to put together a nice and cost effective Z-Wave server based on the Raspberry Pi, read this article.

 

The motion sensor

Fibaro motion sensor

The motion sensor used for this project will be the Fibaro motion sensor. One of the most important features that make it a good choice for automating the lights in a room is that it contains a built in light sensor too (along with the motion sensor, a temperature sensor and an acceleration sensor). Since we don’t want to mess with our lights (trying to turn them on or off) during day time, when there’s enough natural light in the target location, it’s important to be able to measure the level of light intensity. It is also convenient because it helps us avoid trying to turn the light on after it has already been turned on or off after it’s already switched off. Obviously, we could use a regular motion sensor and a separate light sensor instead, but filling the room with sensors might look ugly. The Fibaro motion sensor, on the other hand, is very discrete and quite beautiful in its own way. Another important capability of the Fibaro motion sensor which makes it a good choice for this project is being able to change the length of the time period for which it keeps reporting its state as “on” after motion is detected. This is also useful, by the way, if you wish to use it in a home alarm system because this time frame can be used to define the duration of the alarm. Last but not least it is a good fit for our purposes because it can automatically filter out minor movement (like animal movement).

To find out more about this device, read this article.

 

The smart lights

MiLight Bulb E27

We could use any kind of smart light bulbs in order to turn them on/off automatically, or even regular bulbs in remote-controlled sockets, but in this example we will be using the Milight/LimitlessLED/EasyBulb smart LED lights that we have examined in the past in this article. Learn about configuring the Milight LED bulbs in Domoticz in this article.

 

Turning the lights on automatically

To turn the lights on automatically when motion is detected in the room we are going to start using an advanced function of Domoticz: Events. You can access this function from the menu, by going to Setup -> More Options -> Events.

The idea behind this feature is that you can tell Domoticz how to react to certain changes in the system (events). It can intercept the state changes of some sensors and it can change the states of other devices in response. It can also send email, SMS, etc to notify you about the changes. It’s a fairly versatile mechanism for defining what should happen in the system when certain events occur. The funky part of it is that you, as the user, can define the automation rules graphically! Yepp, that’s right. The event editor in Domoticz, called Blockly, is a visual programming interface which basically makes it possible to create simple functions of how devices should interact to each other’s state changes by using graphical blocks. To be more exact, Blockly is an open-source web-based visual programming editor made by Google. It’s amazingness lies in the fact that people who are not well versed in software development can still create simple programming rules. And that is what Domoticz events are all about!

Let’s take an example:

Simple kitchen light automation event

The rule in the image is as simple as it looks. It tells Domoticz that if the motion sensor in the kitchen is on (it detects movement) and the light intensity in the kitchen (measured by the light intensity sensor) is below 10 lux, then it should set the state of the kitchen lights to on. And it was all dragged together in just a few seconds using the Blockly visual programming editor. Note that you see 4 main puzzle-like blocks in the image:

  • Kitchen MS Motion is the name of the motion sensor Domoticz device
  • Kitchen MS Light is the name of the light intensity sensor Domoticz device
  • Kitchen Lights is the name of the kitchen lights device in Domoticz
  • 10 is a user constant which could have any value you like

And of course you could change the names of your Domoticz devices to anything you want, even if they are already participating in event rules. Just go to the devices and rename them in the Switches, Temperature, Weather or Utility main menus.

To create an event rule of your own in Domoticz, open up the visual editor (Setup -> More Options -> Events) and start dragging in the different pieces of the puzzle from the left side menu:

  • Control – conditions
  • Logic – value comparisons, complex conditions, setters, user constants
  • Time – time constants and comparisons
  • Messages – strings, URLs, emails, SMS messages
  • Security – related to the built in home alarm system of Domoticz
  • User variables – Domoticz user variables and constants
  • Debug/log – writing to the log of Domoticz
  • Devices – the list of your Domoticz devices (switches, sensors, lights, meters, etc.)

The pieces of the puzzle can be combined into ever more complex larger pieces and this way some really intricate automation rules can be defined.

When you’re done, give the event a name in the upper right corner of the page, check the “Event active” check box and Save it.

That’s it! If you set up everything right, your lights will now turn on automatically whenever the motion sensor detects movement.

 

Turning the lights off automatically

So now that your lights turn on automatically, it’s time to make them also turn off automatically and forget that you ever had to switch them on/off manually. This, however is more tricky then turning them on, because when motion is detected in the room it’s obvious that there is presence and the lights should be turned on, but the length of period of inactivity after which they can be turned off depends on your preference, on the type of the room, etc. For example you know that you move around a lot in the kitchen and that means that if there was no movement for 2 minutes, it’s safe to assume that the lights can be switched off. But you may be sitting or lying down in the living room frequently and there you may wish to turn them off only after 15 minutes of inactivity. This way if the lights turn off but you did not want that (you’re still in the room and still need the light), you can wave your hand to turn them back on and you only have to take this corrective action every 15 minutes, not every 2 minutes.

If you have a versatile motion sensor like the Fibaro motion sensor, for which you can change the duration of the time frame for which it reports its state as “on” after it senses motion, you’re lucky. In this case you can simply configure the duration in the sensor settings and add one more Domoticz event rule, which does the opposite of the one we have examined earlier: it turns the lights off when the sensor reports an “off” state (regardless of the light intensity levels). For this specific sensor you can configure the motion alarm duration parameter like this:

  1. Go to Setup->Hardware in Domoticz
  2. Select the Razberry Z-Wave controller from the hardware list and click Setup next to it.
  3. Now select the Fibaro motion sensor in the device list, find the parameter named “Motion alarm cancellation delay” and change it to the desired value.
  4. Finally click “Apply configuration for this device” at the bottom of the page.

If you want to set a value which the sensor will not accept or if you have a less configurable sensor, then it’s time to take out the big guns and start using one of the most advanced home automation features of Domoticz: lua scripts.

Writing a script in the lua programming language is considerably harder than creating a graphical event using Blockly, but no reason to start getting scared, it’s not extremely complex either. However you do need some minimum programming skills and Linux command line knowledge, because the first thing that needs to be done is to create a new text file for the script in the correct sub-directory of the Domoticz installation folder. So find the folder where you have installed Domoticz (for example: /home/pi/domoticz) and enter the scripts/lua sub-directory. Here you need to create a new text file with the appropriate name. By appropriate I mean that the file name of the lua scripts executed by Domoticz determines when and how they are executed. In our case the intent is to create a script which is executed once every minute and checks the state of the motion sensor. This is needed because the script will count the minutes elapsed since there was no movement and it will turn off the lights when enough minutes have passed. The file name of such a script must have 3 components separated by underscore:

  1. script (fixed!)
  2. time (fixed!)
  3. any name you like

So the file name must look something like this: script_time_TurnOffKitchenLightsIfNoMotion.lua

Let’s go ahead and create (or open) this script:

nano script_time_TurnOffKitchenLightsIfNoMotion.lua

Now let’s see an example of such a script and try to understand how it works:

-- script_time_TurnOffKitchenLightsIfNoMotion.lua

local deviceName_MotionSensor = 'Kitchen MS Motion'
local deviceName_Lights = 'Kitchen Lights'
local userVariableName_NoMotionCounter = 'KitchenNoMotionCounter'
local userVariableName_NoMotionMaxMinutes = 'KitchenNoMotionMinutesMax'

commandArray = {}

currentMinutesWithoutMotion = tonumber(uservariables[userVariableName_NoMotionCounter])
maxMinutesWithoutMotion = tonumber(uservariables[userVariableName_NoMotionMaxMinutes])

if (otherdevices[deviceName_MotionSensor] == 'Off') then
 currentMinutesWithoutMotion = currentMinutesWithoutMotion + 1
else
 currentMinutesWithoutMotion = 0
end

commandArray['Variable:' .. userVariableName_NoMotionCounter] = tostring(currentMinutesWithoutMotion)

if (currentMinutesWithoutMotion >= maxMinutesWithoutMotion) then
 print('<font color="blue">Turning OFF ..deviceName_Lights.. due to no motion.</font>')
 commandArray[deviceName_Lights]='Off'
end

return commandArray

At the beginning of the script we need to specify the name of two Domoticz devices: the name of the motion sensor device and that of the lights device. There are two additional names that we must customize, two user variable names. These are the names of the two Domoticz user variables that we will set up a bit later (see below). The first one (userVariable_NoMotionCounter) is a temporary variable which is used by the script to count the elapsed minutes since there was no motion sensed and the second one (userVariable_NoMotionMaxMinutes) is a user defined constant which tells the script how many minutes must elapse before the lights are turned off. Basically this second variable is how you define the length of the period after which it turns off the lights.

The rest of the script only needs to be changed if you want to do some very heavy customization to how it works, but if you’re set out to do that, then there’s no need to explain to you how it works, because you already understand 😉

The final step to making the bulbs switch off automatically is to create the two user variables that the lua script needs. Go to Setup->More Options->User Variables in Domoticz and add two variables:

  • name = userVariable_NoMotionCounter, type = Integer, value = 0
  • name = userVariable_NoMotionMaxMinutes, type = Integer, value = 2

Note that for the second variable you should add your own desired value instead of 2. This will control the duration (in minutes) of the time frame after which the lights turn off.

Domoticz - Adding user variables

If everything was set up correctly, your lights should now automatically turn off after the specified amount of minutes of no movement. If it does not work, go to Setup->Log in Domoticz and try to find out what is happening. You may add debug messages to the lua script using the print statement. You can find an example of this in the script itself.

 

Final word

The methods discussed above to turn on and off the lights automatically are likely to be suitable for many needs. However there may be situations where you would not want this kind of automation. For example it would not be a good thing if the lights turned on by themselves in your bedroom whenever you made a small movement in the bed at night. Also, you might not like the lights to turn off too often in a room where you stay a lot but make little movement. Otherwise, it should be fun to play with this. Enjoy!

 


Comments

Let there be light! …when there’s motion — 3 Comments

  1. Very nice tutorial!
    However the script returns an error:
    at line 21: if (currentMinutesWithoutMotion >= maxMinutesWithoutMotion) then

    The error: attempt to compare nil with number

    Any ideas?

    • So I discovered that my motion sensor sends a No Motion instead of Off and I corrected this in the script. Then I get a new error in line 14:
      2016-12-14 10:14:00.504 Error: EventSystem: in /home/pi/domoticz/scripts/lua/script_time_TurnOffKitchenLightsIfNoMotion.lua: …ripts/lua/script_time_TurnOffKitchenLightsIfNoMotion.lua:14: attempt to perform arithmetic on global ‘currentMinutesWithoutMotion’ (a nil value)

Leave a Reply

Your email address will not be published. Required fields are marked *