Introduction: Multi-purpose Room Lighting and Appliance Controller With Alexa Voice Control and Automatic Timer Functionality. Now With MQTT, Local OLED Display and Integrated Temp/humidity/pressure Measurements
July 2020 - Edit - the Alexa functionality is currently broken after a recent Amazon upgrade that the ESP8266 library has not kept up with - I will fix ASAP.
Recently, I moved into a new build house in Cape Town only to discover that the nameless electrician responsible for wiring up the building was a bit of a maniac control freak. At least this is my assumption as the distribution of lighting and switching made no sense at all - in my lounge diner space alone, there are 16 wall switches controlling 27 lights distributed over the ground floor space. If the number of the switches wasn't enough to deal with, their wall location around the living space made no logical sense at all with the often need to walk deep into the room space from the various entrances or other rooms to locate the correct switch before being able to switch it one! The installed two way switching schemes again was just in the wrong places and lacking in others..
To add to my woes, several family members and visitors are not familiar with the concept of switching lamps OFF when they leave a room resulting in lamps and ceiling lamps and fans being left on making me take on the role of "lamp policeman".
Short of re-routing the house wiring, this was screaming out for some level of "house automation" to make it people friendly and kind to my electricity bills.
Too many switches in one wall box make it sometimes difficult to identify which switch belongs to what lamp so voice control would be nice to allow quick and easy addressing of a switch especially when on the go. On the other hand, it is total overkill and impractical (not to mention potentially expensive) to put voice control onto every electrical device in the house so a single configurable automation device was favoured to mix and match the appropriate type of control method per controlled item as I did not want a range of different designs scattered throughout the house.
The result, I present here - unable to come up with a cool name, I refer to it as "The Device" consisting of a single multipurpose mains powered circuit board accommodating up to 3 control relays, up to 3 input switches and a single configurable "one fit" firmware that allows you to control independently the relay switches via Amazon Alexa Voice control and/or a combination of up to three Passive Infra Red (PIR) movement sensors (to switch lights based on presence) , manual switches and 2 independent programmable 7 day timers per output.
For the more forgetful user, each switch output can be programmed to turn off after a period of 1 to 240 minutes regardless of how it was switched on.
Since I wanted to integrate several of these into my house lighting, the 100 x 60 mm circuit board has a form factor to suit a standard plastic South African wall mounting light switch box however it can fit into any suitable sized housing (See figures)
The firmware is a single program that you can just upload "as is" using the Arduino IDE. Configuration is initially using the IDE serial console to set up the basic configuration (number of relays and inputs, WiFi login details and a password for the Device web server access point to allow you to further online set up the control settings for each input (timer values, Alexa names, input modes (manual switch, PIR and pump protection (explained later)). After this set up, you can also change the WiFi login and other control details at will using the same web server feature. All parameters are stored in non-volatile EEPROM and loaded on power up and/or reset so nothing is hardcoded into the firmware. These are all explained in detail later in this instructable.
This is not just a "theoretical project" as I have 6 Devices controlling 14 lamps now working for 3 years in my lounge, bedroom, dining and home office space plus I have a Device mounted inside a mains socket box to allow remote control of a floor mounted lamp standard and another controlling my swimming pool pump. Shortly the arrival of two more Amazon Echo units will allow 5 more Devices to be installed to complete full house control coverage.
I should add that although a full PCB artwork layout is provided with this project, if you do not want to source and build your own PCB, it is easy to implement the firmware on one of the many available standard proprietary ESP8266 circuit boards on the market (Link Node R4?). All you need to ensure is that depending on your required application, you have up to 4 outputs (Relay 1,2 & 3 + LED) and up to 4 inputs (3 manual buttons/PIR inputs and the configuration button) available and at worst all you should need to do is re-assign the correct IO pins in the code listing before compilation. This approach may prevent you from using the hardware watchdog unless you build a small add-on board with the watchdog components requiring you to run with the software watchdog only however it would be possible to build on standard strip board as an add-on.
EDIT . 27th April 2020. The software and hardware design have proven themselves to be so stable that I have been running all of these units now for over 18 months with the hardware watchdog disabled with no issues what so ever so all new builds do not use it making the use of proprietary boards easier.
Any photo's of the circuit board (PCB) used in this instructable are of the original Version 1 board. This shows some changes to some of the copper track due to a serious error with the ESP12 component template supplied with the Fritzing PCB software that I used to layout the board. The artwork layouts provided here are for a corrected version 2 board that also contains some improvements learned from the original project build namely the re-orientation of the power supply and the IO connectors.
If you need any clarification, further explanation or find any mistakes or gaps, please message me and I will answer as soon as I can.
Step 1: The Schematic and Some Hardware Functions
As far as circuits go, the schematic is quite simple. The heart is the now ubiquitous ESP8266 microcontroller in the form of an ESP12 module. This component probably presents the biggest "challenge" in adding to the circuit board in that you need to add wire links to the 16 edge connections before mounting to the board. Having said that, it is not that difficult and a section specifically covers the process. Just take your time, I have done it many times without a single mishap.
The rest of the circuitry is conventional and straightforward.
You can save time and cost by only fitting those components that your application requires so:
For one relay fit:
- Relay 1, Terminal block TB1, diode D1, transistor Q1, Resistor R1
For two relays, fit the components for Relay 1 plus:
- Relay 2, Terminal block TB2, diode D2, transistor Q2, Resistor R2
For three relays, fit the components for Relays 1 & 2 plus:
- Relay 3, Terminal block TB3, diode D3, transistor Q3, Resistor R3
One significant circuit module is the inclusion of a hardware watchdog circuit built around the components:
- 555 timer IC, R4, R5, C1, C4, C5, D4, D5, R8
This is essentially an astable oscillator that if allowed, would produce a short reset pulse to the ESP12 via D5 every 2.5 seconds. This is prevented by transistor Q4 that is AC coupled to the Heatbeat output (GPIO2). So long as the Heartbeat flashes regulary within a 2.5 second window, the astable is locked out. Any malfunction or deliberate pause in the Heart beat output will result in a forced hardware reset.
Now the use of the hardware watchdog is optional and the default software setting is NOT to use it. You will select this at initial configuration. Take care with this setting because if you select "hardware watchdog" in set up but do not fit all of these components including the board watchdog link (discussed in the "Programming" and "Initial setup" sections) then the program WILL hang up at some time in the operation forcing you to power off or hit the "Reset" button.
A reasonable question would be "Why or when would I fit the hardware watchdog" (is that one or two questions?)
A watchdog is designed to reset the microcontroller if the program malfunctions. Taking the RST pin low momentarily presents a "clean" reset independent of any programming dependencies and so has been considered as the most secure form of resetting a microcontroller BUT the ESP8266 has an internal watchdog timer and the ESP.Reset() command to provide the same function internally so why use a hardware watchdog at a small but nevertheless increased build cost? My answer is "security" - This unit is designed to switch mains voltages with currents up to around 10 amps (the relay rating), the risk of local electrical transient noise is high. Add this to the reality that you may be installing this device in the roof or some other inaccessible space and the last thing you want is the need to access the unit to hit the reset button! The hardware gives you a comfortable feeling that no matter what the Device will reliably reset itself automatically if the unit trips. Also during configuration the unit will need to reset itself automatically to ensure that the new configuration parameters are loaded into working memory and restarts with a clean configuration. I simply prefer a hardware reset over a software reset for maximum security.
If you do not agree with this logic then simply do not fit the components but make sure you select software reset in the configuration and then see how you go. You can always add the components and reconfigure later if you need to ...
Programming of the ESP12 using the Arduino IDE requires a reset of the board with the GIO0 input set to 0 during the reset so we fit two miniature board mounting push button switches to manage this task. Operation is simple, press and hold the "Flash-Config" button and then press and release the "Reset" button before releasing the "Flash-Config" button. The ESP12 will boot up in the programming mode for upload from the IDE.
The "Flash-Config" button has a secondary function that is useful during bench testing. During normal running (after the Device has booted up and logged in to the WiFi network, pressing this button for 5 to 7 seconds will initiate the built in Configuration Access Point web server. Pressing it for greater than 10 seconds will force a Device reset. After installation, you can connect an external switch to GPIO0 and 0V via IO2 connector pins 1 & 6 to allow you to perform this function externally (this is expanded further in the installation and setup section).
Note 1: If you are using the software watchdog method - you MUST reset the unit with the "Reset" button once after the program upload is finished. This is due to a bug in the ESP8288. If you fail to do this, the next time the unit needs to do a software reset (software watchdog or ESP.reset(), the unit will hang). If this does happen, the only solution is a power off/on cycle or hitting the reset button. This button reset is a one time requirement after each program upload..
Note 2: If you are using the hardware watchdog, you must disable it first by removing the W.dog link beforehand otherwise the hardware watchdog will reset the board soon after you have set the programming mode - this of course is what it is designed to do as you have left the normal run mode! Remember to refit the W.dog link after program upload.
There are two header style single row connectors used for IO connections to the board - IO1 and IO2. These allow all ESP12 IO ports to be used externally if desired. IO2 is also used for the serial connection to the Arduino IDE so is always fitted but IO1 only need to be fitted if a PIR or control button is required for Relay 3.
- IO2 - pin 4 = GPIO5 (labelled 5 on the PCB) & pin 1 (marked 0V) = Button 1 => Activation of Relay 1
- IO2 - pin 5 = GPIO4 (labelled 4 on the PCB) & pin 1 (marked 0V) = Button 2 => Activation of Relay 1
- IO1 - pin 1 = GPIO16 (labelled 16 on the PCB) & pin 6 (marked -) = Button 3/PIR3 => Activation of Relay 3
Serial connection (for program uploading, initial configuration and diagnostic checks)
Connector IO2 also carries the three connections for the serial interface connection to the Arduino IDE setup on the computer. You need one of the many available FTDI interface connection circuit boards to provide a conversion from the ESP8266 serial port pins to the computer USB connection. I use a FTDI232 board available from Amazon, Ebay and many other online providers. Remember to make sure that the board is 3.3V compatible (rather than 5V) and you only need TX,RX and OV pins to be connected - some boards are also able to provide a 5V or 3.3V power source to the circuit under test - do NOT connect this!
- IO2 - pin 1 = 0V
- IO2 - pin 2 = Tx of FTDI connector
- IO2 - pin 3 = Rx of FTDI connector
Note 3. The Tx and Rx markings on IO2 refer to the FTDI232 pin idents and not the ESP12 pins They are in fact cross connected to the Tx and Rx pins of the ESP12!
HeartBeat LED (HBeat)
As explained previously, the HeartBeat output of the ESP12 keeps the hardware watchdog "asleep" during normal operation. It also functions as a simple indicator of the Device "healt" and to a extent, the speed of its flash rate also indicates the current function of the Device ....
- Initial startup awaiting WiFi connection - Fast = 50mS ON, 50 mS OFF
- Connected successfully to the WiFi but not yet updated the internal clock via the internet NTP server - 150 mS ON, 1000 mS OFF
- Connected successfully and the clock is now updated .... normal operation - 1000 mS ON, 150 mS OFF
- Lost connection after an initial successful connection - 50 mS ON, 300 mS OFF
I discovered late into the software development phase that the blue LED integrated onto the ESP12 module is in fact connected to GPIO2 this making a onboard LED unnecessary! Its use lives on though if you wish to take a flying lead connection off the board and mount the LED externally as it does can a useful operational function. Otherwise do not fit.
The schematic and current PCB layout was designed with several applications in mind so there are just a few components included that are not used in this Device implementation.
- 3 way connector marked ADC,GND,RST => If fitted, this provides access to the ESP12 A/D convertor input and the reset input
- 4 way connector market Buzzer => fitted instead of Relay 2 and TB2. This provides a transistor switched output for use for such things as a piezo buzzer.
Step 2: Components
These components are specific to the board layout and size supplied with this project. If you produce your own circuit board or build on strip board then the component sizing and pin spacing can vary to suit your own requirements. Component list below if for a full 3 relay board with all IO connectors and the hardware watchdog. Read the Schematic section to identify optional components for different configurations
- 555 General purpose bipolar Timer, package dil-08; chip ne555
- C1 Ceramic Capacitor, spacing 200 mil, voltage 6.3V; capacitance 100 nF
- C2 Capacitor, pin spacing 5mm
- C3 Capacitor, polarized, capacitance 470 or 1000uF
- C4 Ceramic Capacitor, spacing 200 mil, voltage 6.3V; capacitance 100 nF
- C5 Capacitor Polarized, voltage 25v; capacitance 10uF
- D1,2,3,4,5 Diode 1N148 or similar
- Flash-Config Pushbutton 6 x 6 x 6 mm miniature
- Reset Pushbutton 6 x 6 x 6 mm miniature
- IO2 IO connector 6 way, pin spacing 100 mil, Single Row;
- IO1 IO Connector 8 way, pin spacing 100mil; Single Row;
- W.dog IO connector 5 way, pin spacing 100mil; Single Row;
- Mains IN Screw terminal block 2 pins, Pin spacing 0.2in (5.08mm) (See figure)
- TB1,3 Screw terminal block 3 pins, Pin spacing 0.2in (5.08mm)
- (45 degree angle recommended - see figure)
- TB2 Screw terminal block 3 pins, Pin spacing 0.2in (5.08mm - see figure)
- Q1,2,3 PNP-Transistor, package TO92, (EBC); 2N3906 or similar
- Q4 NPN-Transistor, package TO92, (EBC) 2N3904 or similar
- R1,2,3 1.5kΩ Resistor, tolerance ±5%; pin spacing 400 mil
- R4 330kΩ Resistor, tolerance ±5%; pin spacing 400 mil (See notes)
- R5 47kΩ Resistor, tolerance ±5%; pin spacing 400 mil
- R6 1kΩ Resistor, tolerance ±5%; pin spacing 400 mil
- R7 4.7kΩ Resistor, tolerance ±5%; pin spacing 400 mil
- R8 100Ω Resistor, tolerance ±5%; pin spacing 400 mil
- HBeat LED, Red, green, blue or yellow spacing 3 mm - Optional external HeatBeat LED
- R9 3.3kΩ Resistor, tolerance ±5%; pin spacing 400 mil - Optional external HeartBeat LED
Relay 1,2,3 PCB Power Relay, Switching circuit SPDT; voltage 3.3V,
contact rating 125VAC @ 10 AMP / 30VDC @ 8 AMP; SRD-03VDC
Power supply 3.3v 600mA 240 V AC-DC Power module (See figure & Note 1)
Circuit board See the last section for artwork Gerber files that can be uploaded to a manufacturer. I used OSH Park in the US (including shipping , it was still a lot cheaper for 12 boards than a local supplier in South Africa!) and I was very happy with their quality, service and pricing. There are also a lot of Chinese manufacturers offering an online service. You can also create your own of course and it is possible to build this circuit on strip board although you will find the spec'ed relays do not fit a regular strip board without some hole drilling - alternative use relays with a strip board compatible pin layout.
You cannot fail to notice that the included board layout has two rather "excessive" 14 mm holes in it! These are there solely to allow the board to be fitted into a South African plastic wall mounting light switch enclosure. If you are 3D printing an enclosure, you could use these to facilitate mounting otherwise I recommend simply using quality 2 sided tape to secure the board in any other housing arrangement.
Note 1. I recommend that you test the purchased power supply module BEFORE you mount it on the main PCB as there are several versions of this module with different output voltages available, all similar in appearance (I accidentally fitted a 5V version to one of my boards and then wondered why the ESP12 got VERY hot!!).
Apart from this mishap, I built 7 builds successfully without testing the supply before hand but then had 3 successive fails due to poor power supply quality however in my experience, if they work then they are reliable thereafter.
Step 3: Build Tips
As I mentioned earlier, board build is pretty straightforward with the possible exception of mounting the ESP12 module. the key is the right tools, a fine soldering iron and a steady hand. I found a magnifying inspection glass also a great help but I also managed without it so it is not essential.
You only have two hands so I strongly recommend the use of a "third hand" accessory as shown in the diagrams, it is excellent for holding the ESP12 module in any required plane whilst adding and soldering wires.
I suggest that the order of assembly be;
- All low lying components first such as resistors, diodes, small capacitors.
- Push buttons followed by the 555 timer chip and then the transistors and then the larger capacitors
- The header pin connectors
- The ESP12 module as described below.
- The relays and screw terminal blocks
- The power supply module
Take care that the LED, transistors, diodes and electrolytic capacitors are all orientation sensitive.
ESP12 preparation and mounting.
The key is to solder a 15 mm (approx) length of thin bare copper wire (e.g. telephone cable) to each of the 16 lead outs of the module.
Then take the wired module in the correct orientation and slowly insert one side of 8 wires into the pin holes of the PCB - the antenna end of the module is next to the two push button switches. Be patient and take your time and do not be frightened of using a pair of tweezers and/or small pointed pliers to help guide the wires into each hole.
Once all eight wires of one side are located, take a small piece of double sided tape and place it on the lower side of the module - the intention is to produce an insulating spacer between the module and PCB when you have located the wires on the other side.
Now turn the ESP12 module so that it is raised a distance off the board but is parallel with the board. with a pair of pointed nose pliers and/or tweezers take each wire on the non-inserted side, bend it gently guiding the open end into the correct board pin hole. Repeat for each hole until all 16 extended lead out wires are inserted into the correct board pin hole. gently push the module down towards the board whilst gently pulling each of the wires through the board so that eventually the module is lying above the board with the double sided tape between the module and board.
It sounds far more complicated than it actually is so just take your time. This method also allows you to mount the module on standard strip board should you want to.
When you are happy that everything is located correctly, solder the wires onto the board and cut off the excessive lengths.
The power supply is a complete sub-module and on some builds I soldered very short fly leads to the power supply and then to the main board and again used a small piece of double side tape as insulator between the two boards.
In later builds, I had good success with soldering a header connector with any unused pins pulled out of the connector using pliers - see picture, this made it easier to mount the sub-board onto the main board.
Step 4: Setting Up the Arduino IDE for the ESP8266 and the Program Upload.
There are countless instructable projects describing how to set up the Arduino IDE for use with the ESP8266 range of microcontroller boards. Rather than repeat the whole procedure again, I include a link here to my own previous instructable and ask you to refer to Section 2 for the instruction.
ESP-12 Toolbox - Seamless Integration of Multiple Sensor Measurements, Alarm Detection, Time Stamping, Email & Twitter Notification, Push to the Cloud and Plenty of Room for Your Application, All in One ESP-12 Module
Set up the Arduino as stated and then you can move onto the program upload.
Download the software zip file from the File download section and save it to the sketch storage directory of the Arduino IDE. If you do not know where this is, open your Arduino IDE, select "File" and then "Preferences" from the menu. refer to the diagram to determine the name and location of the sketch directory. I also recommend you tick the "line numbers" check box to aid readability of the program file. Close the program before proceeding.
Open the Sketch directory and extract all of the files in this compressed file. It should create a sub-directory with all of the files that you need for the compilation
As already stated, you will need a USB to serial convert to connect the Device to your computer. I use the FTDI232 but there are plenty on the market. I have never had a problem installing the necessary drivers for them as Windows has always installed them automatically when I plug in the USB.
- Remove the Watch dog jumper link on the W.Dog header connector before uploading
- The console baud rate is set to 115200, and the line ending is set to Carriage return
- The processor type settings etc are as per the diagram
- Hold the "Flash-Config" button down when you press the "Reset" button and then release the "Flash Config" button AFTER you have released the "Reset" button.
- Compile and upload the program. After compilation you should see the blue LED on the ESP12 and the Watchdog LED (if fitted) flashing during the upload cycle. If the LEDS do not flash and you get an "fail to upload" error from the IDE, try again after checking that the Tx, Rx and 0V connections on IO2 are correct and make sure that the 2 buttons are pressed in the correct sequence
After a successful upload, refit the watch dog link if used and press the reset button once to get past the well known "bug" associated with the ESP8266. The Device should now start up, the HeatBeat LED / blue ESP12 LED will start to flash, you will see a boot up message on the serial console and you are now ready to start the initial setup. .....
I am not including any discussion re the details of the software itself as there is a lot of it, the software is very well documented and the reality is that you do not need to change anything in the code unless you want to "jump in" and change things. Nevertheless if you do want any explanation and/or support just message me. (My email address is also in the first lines of the software list - Access-Point.h
Step 5: Initial Set Up Using the Serial Console
The function of the initial setup is primarily to set the board up to your hardware input & output requirements and get it to a stage where it can successfully log onto your home network.
- Number of relays fitted
- No if inputs being used
- WiFi SSID, password and Device name
So on the very first boot up, the device will detect that it is the first boot up and it will automatically store default values in the EEPROM and reboot.
The IDE console display should read something like Figure 1 on the console.
It will attempt to log in to the WiFi but will be unable to since it has no meaningful login data. After a short while it will automatically start the configuration Access Point (AP) which is again of no use to us at this point.
within 10 seconds you will see "NTP failed" messages which may repeat every 10 seconds - this is normal
As soon as the AP start up message is finished type in lowercase l followed by the key.
Figure 2 - Follow the screen instructions and enter the required WiFi login SSID, password and the name that you want to give to your Device - all entries are limited to 20 characters with no spaces (use - or underscore if you want to separate words).
The Device Name has 2 uses.
- It is the name that you see in the wifi connected client list of your modem
- It is the name given to the Device Configuration Access point. So when you start up the AP, you will see a new network created, it's SSID will be the Device name that you created followed by "- Setup". Eg. a Device with the name "Lounge" will create a access point called "Lounge - Set Up". This allows every Device in your home set up to have its own unique name.
Press Uppercase R followed by the key and the Device will reboot and this time after some seconds it should connect successfully taking you to Figure 3 and after 10 seconds we should see "NTP = xx:xx".
It is not uncommon for the NTP server access to fail and we will see the failure message again. If this happens the Device will try again every 10 seconds until it gets a valid reading. Thereafter it will recheck the NTP every 3 hours. A failed NTP update will again result in 10 second retries until it gets a good result.
It should be noted that the internal soft clock will not be set until we have at least 1 successful NTP interrogation.
Any reset or power interruption will effectively kill the internal clock until the NTP connection is successful.
The default number of relays is set to 1 with no inputs enabled so you next need to set the number of relays to suit your configuration by typing lowercase n followed by
To set the number of inputs by typing lowercase p followed by and then respond to the prompt with 1 to 3 to suit your requirements.
The last setting is the password that you want to use for the configuration Access point. the default is password so you should change it to suit. A single word comprising 8 to 20 letters and numbers is required.
Type lowercase b followed by and follow the prompt.
Again, press Uppercase R followed by the key and the Device will reboot and load in the new values.
Once connected, pressing lowercase d followed by will display the current set up. Lowercase H followed by will display a list of the commands available. These commands can all be accessed through the configuration access point later we will leave at this point.
Initial set up is now complete so you can move onto the main setup.
You can rerun any of the commands listed in the help page (h) as many times as you need but the following parameters all require a reset before loading to working memory:
- Alexa voice control
- Number of relays
- WiFi SSID, password and device name
- Access point password
- Hardware type selection
- Set EEPROM to defaults (the EEPROM will be changed but not reloaded to working memory)
Step 6: Secondary Setup Using the Configuration Access Point
The built in webserver handles all of the operational settings and is called automatically if the initial login fails and can also be called at will by holding the Flash-Config button (GPIO0) down for 5 to 8 seconds (take care holding it down for 10 seconds will initiate a reset!). An external momentary switch connected to GPIO0 on header connector IO2 can also be used to initiate the AP in the same way.
Once started, you must connect your computer or mobile phone to the network, open your web browser and enter the webserver address of 192.168.8.200 to open up the webserver home page - see figure 1
You can use the webserver to set up or change the following:
- Figure 2 - WiFi SSID, password and device name. the Device will need manually resetting before the new values are loaded.
- Figure 3 - Relay ON timers. This is time in minutes (0 to 240) that a relay switch will stay ON once it has been triggered - this will override a timer controlled switch! 0 turns teh timer off and the relay switch will be indefinite until an activated timer turns it off.
- Figure 4 - Alexa names for each relay output (20 characters max) - these will be used for the voice control. Do not use spaces but instead separate words with the hyphen E.g. Lounge, Dining-Room, Lamp. You may need to play with these names to find what works best for your voice and Alexa. Short is good!
Also on this page you can enable or disable each output so that it is only timer and button controlled. Ticking the "Alexa Enable" checkbox will enable voice control for that output only.
The Device will automatically reset after any detail is changed here.
- Figure 5 - Remote time control of each relay - each relay output has independent two timers. Each timer has a start time and an end time followed by the individual days Sunday through to Saturday that it is activated.
- Time control on each relay (both timers) can be independently switched on and off - default is OFF.
- An output switched ON by a timer will not be switched off by the relay ON timer (See 2 above) - it will only be switched off by the timer OFF setting, a voice command or an AUX switch command
- If the relay has been switched ON by Alexa or the AUX input (PIR or switch), if it is ON and an activated timer OFF switchpoint is reached, the relay will be switched off (in other words, the timer OFF instruction will override the relay ON timer
- Manually switch any relay ON or OFF
- Manually reset the Device. This will close the webserver access point.
- Inspect the diagnostic flags and some important variables to assess the operational integrity of the unit.
See next section
- Manually switch off the Webserver access point - highly recommended at the end of a viewing session if a reset is not instigated.
Step 7: Diagnostic Page (both Webserver Access Point and Console Accessible)
The diagnostic page gives us the opportunity to look at some of the program control flags and variables and thus gives us an opportunity to assess how well the device is running. Access to it is gained from the home page of the Configuration access point and also if the serial console (Arduino IDE) is connected, we can look at it on the console after typing lower case f followed by
The view points are:
- Number of relays configured to run - this may be different from the physical number of relays
- Number of AUX inputs that are enabled
- Soft Access Point - the software flag that enables the AP - if it is on then it should be possible to see it in the wifi network list of your modem and/or mobile phone.
- Current time interval between scheduled NTP clock updates in mS. If all is well, it should be 1068000. If the last NTP update has failed, it will be 10000.
- The last NTP update report flag - now a reinforcement of the interval value above - if the clock has been updated at the last attempt then it will read "successful".
- Diagnostic messages control flag. If this is set, the Device will produce a diagnostic message via the serial console port. Very useful for debugging or investigating. This defaults to ON but is recommended to be turned off once the Device is running without the serial console connected. This can be toggled on and off by by typing lowercase m followed by and should be the last keyboard command before disconnecting the serial port.
- Current relay ON Timer values for relays 1, 2 and three if fitted. The boot up value is zero minutes. As soon as a relay is switched on, its ON timer is set to the value set by the Relay ON Timer parameter (0 to 240 mins)
- If the relay is ON and this value is indicating 0 then the relay was switched on by one of its remote timer setpoints or by an AUX button programmed to be a manual switch. This means that the relay can only be switched off by the timer or the same manual button
- If the relay is On and indicating a value, then it will have been switched on by either an AUX button acting as a PIR movement sensor or an Alexa voice control if enabled. This value will count down every minute until it reaches 0 and then the relay will switch off. Note the timer has higher priority and can also switch the relay off if the OFF switch point is reached.
- Automatic timer reset
This is a rather interesting feature of rather dubious origin but was forced on me by necessity. Any of you living in South Africa will know what I mean when I say that our normal internet access for the normal person is somewhat "special" - our big name providers love to tell us that we are paying for "lightening speed internet" (their words not mine" only for us to find that they are giving us a quoted 4 Mbs but often with speeds down (well) below 1 Mbps or even worse complete drop out for several seconds Now recently with the advent of LTE and fibre things are slowly getting better but only in selected "main stream" areas and then at a cost that is breath taking. Why does this matter to us here? Well firstly, if the WiFi or internet disappears then so does Alexa voice control and NTP access, then each relay control is in fact performed through its own TCP socket on the ESP12, add to this the NTP connection and the Access point and in fact the ESP is running at its limit and I have found that sometimes it does not like loosing its connection. It can recover and mostly does BUT sometimes it stops (the connection not the controller). I have found that the most "sensitive" installations were those at the limit of the WiFi coverage.and to be fair WiFi extenders are a solution but one unit in particular is at the range limit, is located outside and I am not inclined to buy yet another extender. My solution was to simply force a reset at a set time every 24 hours during the night when nothing was scheduled to happen - this 100% fixed my problem! I set the timer reset value on this page one minute before midnight (ie. 23:59). the unit resets, the clock re-initiates to 00:00 and so it is in fact only one minute short of the correct time so that IF the unit fails to update the clock due to an internet failure, it is still on track, the soft clock only needs one valid NTP update to get back on track and this will happen every 10 seconds ad infinitum until it is correct. not very "scientifc" or even "good engineering" but a pragmatic solution to a small but real problem. If you don't like it simply disable it and/or buy a WiFi extender and/or hopefully have a ISP that produces the goods.
- Last but not least on the diagnostic web page and via the serial console we can set the watchdog type to be software(default) or hardware. Make sure if you are running the hardware watchdog that you have fitted the W.dog link on the board otherwise the unit will hand up as some time.
Step 8: Installation - House Lights - Wall Mounting
The next challenge is to how to install into your current house wiring.
In general you will want to keep your existing wall switches in situ - otherwise a unit malfunction, loss of internet etc will put you into the dark and I assure you your wife and kids will not look at you kindly.
At this point, we have to note that shortly you will be coming up against mains electricity - that means DANGER! If you are not "electricity" savvy then consider getting in someone who is even if it means an electrician.
Single point switching
This means for normal wall switches you will wire each switch in parallel with the normally open contacts of its associated relay - see wiring diagram
Two way switching
For two way lighting, this means that there is one other switch that operates the light and the wall switch will be a SPDT switch rather than the normal SPST switch used for the other single switched lights. The easiest integration of the controller for a two way switched light is to completely disconnect the 3 wires currently connected to the wall switch and reconnect them to the change over contacts of the relay thus rendering the wall switch off line. Make sure that you connect normally closed, normally open and common contacts correctly.
The loss of the existing switch can be covered by the other switch of the two way switching circuit.
The pictures show a South African installation using local components. Other countries will probably have different dimensions, consumer parts and possibly legislation - this is my disclaimer .... check that you are within the rules both safety wise and legal.
The board fits inside an enclosure that is dug into the walls - with a drilled hole linking the side of the new enclosure with the existing wall switch. Again - safety alert - turn the lighting power OFF and pull out the wall switch cover and its wires to make sure that your drill does not hit the switch wires as you link the two boxes. I used a 12 mm sized drill bit.
Please study the wiring diagram and make sure that you do not cross wires etc.
To finish off the fitting, you fit a standard electrical blanking plate that suits the wall enclosure used.
Step 9: Appliance Control - Free Mounting
The Device is very easily usable as a one relay switching device for an standalone appliance such as a flow mounting lamp standard or fan.
The 100 mm x 60 mm fits with plenty of room in a plastic socket box in South Africa but you would need to check your local possibilities.
One "universal" method would be to fit the board in the smallest standard plastic housing (E.g 90 x 50 x 150 mm) with two cable glands for entry and exit cables. The entry wired directly to a house plug and the exit to your appliance either directly or via a suitable plug and socket. the photos show a free standing wall socket box and a plastic enclosure used for swimming pump control. The pump controller is in fact in two boxes as the actual driver for the pump is a 40A solid state relay with heat sink!
One thing that has not been mentioned in this and prior application is how to handle the buttons required for waking up the configuration web server pages and optionally manually operating the appliance or switches.
This is covered in the next section ...
Step 10: How to Handle the Manual Control and Configuration Switches
So far we have seen how to implement the electronic board and mount it in a variety of enclosures depending on the application but we know from the software functional description that we need a button to be able to wake up the configuration webserver and if we want manual control, we need up to three buttons easily accessible to the user.
The pump controller illustrated in the last section was easy - aesthetics was not important and so two normal SPST momentary action push buttons mounted on the enclosure were fine. Equally it would have been straightforward to bring the button wiring out on a wire loom and put the switches anywhere to suit. but what about the wall switches and lamp controller where options and space are limited and aesthetics is important?
My answer today lies with the TTP223 touch switch. This is a tiny PCB that has three connections ... +2.5-5V, Gnd and output. The output can be latching or momentary, active low or active high depending in the linked/unlinked status of the solder pad bridges A & B on the component side of the board and it is not expensive.
Linking A only will configure the switch to produce an active low output state when there is touch contact with the non-component side of the board. With this configuration and power applied to the +V and Gnd pins, the red LED on the component side of the board will light with no touch contact. Touching the other side of the board will result in the LED going out and the IO output going low.
So to prepare the switch you must solder three cables to the +V, IO and Gnd pins. I took 3 breadboard jumper cables that had female connectors on both ends (see picture), I cut one end off and soldered this to the board whilst the other end provided a ready made female connector to attach to the male headers on the device PCB.
Apply a solder bridge across pads A.
You can prepare as many of these touch switch boards as your application needs and arrange them to suit your requirements. I leave it to you how you mark the outside of the cover plate so that you know where the switches are. The minimum might be no marking with a switch in each corner!
- IO2 - pin 4 = GPIO5 (labelled 5 on the PCB) & pin 1 (marked 0V) = Button 1 => Activation of Relay 1
- IO2 - pin 5 = GPIO4 (labelled 4 on the PCB) & pin 1 (marked 0V) = Button 2 => Activation of Relay 1
- IO1 - pin 1 = GPIO16 (labelled 16 on the PCB) & pin 6 (marked -) = Button 3/PIR3 => Activation of Relay 3.
- IO2 - pin 6 = GPIO0 (labelled 0 on the PCB) & pin 1 (marked 0V) = wake up the configuration webserver
So, apply a small square of our double sided tape on the non component side of the touch switch PCB, apply the switch to the back side of the blank panel used to close off the enclosure .
Step 11: Update - November 2020 - Add Local OLED Display, Local Air Temperature, Humidity and Barometric Pressure Measurement and MQTT Communication
This is section serves as a replacement/supplement to the previous section as it presents an optional addon upgrade to the existing design.
With a firmware upgrade and employing the ESP8266 I2C bus (GPIO 4 & 5) , the controller can now measure the local temperature, humidity and barometric pressure using a readily available BME280 module and since information without output is useless, we can have a standard 0.96" OLED display to display the local measurements and also the status when any of the controller outputs are ON. In fact you have have one of the larger sized OLED now available but you will have to organise an alternative mounting arrangement.
I have also added MQTT communication to the controller thus allowing the unit to be both remotely controlled by an external device, the relay status and measurements can be relayed at a programmable interval to an external MQTT compatible system.
Now we have a display and MQTT, the sky is the limit and I have added the ability for an external sensor or device to send and display its own data on the local display - when more than one set of data is available for display the controller will scroll between its own display and up to 4 auxiliary screens - see figure 3 as an example when a controller is sharing its screen with my geyser controller and pool monitor.
The next section gives you the new down load files for the 3D printed OLED display mounting bezel and the mounting arrangement on the enclosure front panel.
Step 12: Mounting the OLED Display and BME280/TTP223 Modules on the Front Panel
Step 10 described how to mount the TTP223 touch switch on the main housing front panel. Now we take one step further and add the BME280 module to a convenient spot on the front panel - I took the other top corner. It, like the TTP223 can be stuck to the panel using a small piece of double sided tape or a small dab of glue.
Mounting the OLED display is a little more involved as we need to cut a hole to suit the bezel either your own or mine.
- There is a "risk" with using my supplied bezel as I discovered the hard way that there are several versions of this sized display on the market and they can have slightly different sized PCB and/or active display size and even can have the connection pins in a different order so beware - most times you are not ware what you are buying until you have it in your hands so you just may have to improvise with the bezel mounting kit - make your own if you can, modify mine with a small file if possible or buy something else on the market.
The concept of my bezel is simple - cut the 36 x 31mm square hole in your front panel at the place where you want to mount the display - take care to cut the hole aligned to sides of the front panel otherwise the display will be crooked. Figure 1 views A, B, C, B, E & F show how the bezel part B fits at the front the panel, the display and bezel part C fit behind the panel. The parts are secured with glue taking care not to apply too much so that it runs on the display front. Take your time and practice without the glue as it is can be tricky to align and fix at the same time. With regard to wiring, either solder wire leads to the display and BME280 before you attach them to the panel or do as I did and head header pins to the boards thus allowing the fitting and removal of connections at will (it is easier to fit the display without the complication of flying leads!). When glued and you are happy with the alignment, put the assembly to one side to allow the glue to set 100%.
The BME280, TTP223 and display should be wired as per figure 2 in the previous section taking care that you do not mix up the 3V3, 0V, SDA and SCK wires when you connect them together. Last but not least, these 4 wires and the IO output of the TTP223 touch switch must be connected to the main board as figure 2. It is recommended to keep these wires as short as practical and use IO connectors so that you can easily detach the front panel from the main enclosure.
You will also need to replace the firmware in the main board with the new version here (note that at present due to the issue with Amazon Alexa, the new firmware does not have the Alexa features described elsewhere. This will be fixed as soon as I can address the problems. The firmware is in two files Declarations.h and House_Node_MQTT_OTA_0V2.ino, you need to download both files and put them in a sub-directory House_Node_MQTT_OTA_0V2 of your Arduino sketches directory. I will shortly be upgrading the firmware even further so I will update the configuration instructions when I release that.
Step 13: Using the Device With Amazon Echo
EDIT - Update - as of July 2020, the Alexa functionality is not working (undiscoverable by ECHO devices) due to the Alexa ESP library not keeping pace with the Amazon upgrades - I am currently trying to fix this.
Once set up, controlling any number of Devices via the Amazon Echo family members is quite straightforward.
- Your house must be "Echo equipped". That is to say as all of your Echo devices registered to the same Amazon account should be connected to the same WiFi network as your Devices.
- Each Device must be WiFi connected, with each relay to be voice controlled configured with an Alexa name and be "Alexa Enabled" using the Device webserver configuration Alexa page.
- Make sure that you have chosen "sensible" Alexa names and hyphen words rather than leave spaces. Names that I have used successfully include Lounge, Dining-Room, Kitchen, Top, Corridor, Patio, Office, Sun-Room, Toilet, Bedroom, Bathroom, Garage, Lamp and Pump.
The Device emulates a Wemo switch and the Alexa skill is already installed so all you have to do is ask your Echo, Echo Dot, Echo Plus etc to "Search for connected devices". The echo will do the rest.
After the Echo has finished its discovery you will be able to switch your devices on and off with the commands "Alexa, Turn on XXXXXXX" and "Alexa, Turn off XXXXXXX" where XXXXXXX is the name that you have assigned to the relay.
- During your start up, if you have changed Alexa names more than once or added/deleted controls, I suggest that you open your Alexa App on your phone or computer and delete all of your "SmartHome", "Devices" entries as I have found that Alexa does not seem to like "letting go" of old devices and I have found her getting confused. Once deleted, do a new "Search for connected devices" for a fresh clean sweep when you are finally happy with your input names etc. I think this may be because unlike "real" Wemo devices, all of the Device devices do not go through the Wemo app.
- Only if you are using 3 Alexa relays on a single Device, I suggest that you configure the Device to be use the software watchdog rather than the hardware watchdog. This is because when the Echo runs its discovery routine either when you instruct it or when it checks in the background), the communication between the Echo and the Device gets a bit "intense" and there can be pauses of up to 11 seconds when the HeatBeat output does not tick. I do not know if this is caused by my WiFi, my internet performance or if it is inherent in the Wemo-Alexa protocol. By all means try it on your set up with the hardware watchdog - if the Device resets during Echo discovery then this is the problem. You can fix it by either re-configuring the device for software watchdog or keeping the hardware watchdog but increase the watchdog timing period from its current 2.5 seconds to around 10 or 11 seconds. The components are C5 (currently 10uF) and R4 (currently 330,000R) A starting point would be to try 22uF and 820,000R
- If you have a serial monitor (E.g Putty, Arduino IDE) connected to the Device serial port and the messages enabled, you will be able to see the Alexa induced communication including when you do a discovery routine which aids debugging
Step 14: Download Files
I used OSH Park in the US (including shipping , it was still a lot cheaper for 12 boards than a local supplier in South Africa!) and I was very happy with their quality, service and pricing.
There are also a lot of Chinese manufacturers offering an online service. You can also create your own of course and it is possible to build this circuit on strip board although you will find the spec'ed relays do not fit a regular strip board without some hole drilling - alternative use relays with a strip board compatible pin layout.