ESP32 Smart Home Automation using Alexa and Google Assistant

Published  November 29, 2023   0
ESP32 Home Automation using Alexa and Google Assistant

If you are new to smart home automation and are looking to build your first project to control your lights and fans with voice commands, then this article is right for you. In this Internet of Things (IoT) project, I'll guide you through creating a smart home control system that can be controlled using both Google Assistant and Alexa, using an ESP32 and Sinric Pro. If you are an ESP32 home automation enthusiast and completely new here, then do check out our collection of all the Home Automation Projects and ESP32 Projects that we have built here previously on CircuitDigest.

 

What is ESP32 Home Automation and How Does It Work?

Now coming back to this project, we are using Sinric Pro so that we can effectively control home appliances (like Light bulbs or fans) by seamlessly integrating voice commands through Google Assistant and Alexa, as well as using manual switches for control. But once you understand the basic principle here, you can control every electrical appliance in the house using relays. 

Consider using the ESP32 home automation, which enables the creation of smart control systems for appliances that utilise the WiFi functionality of the ESP32 microcontroller. Gone are the days of an Arduino requiring an extra module for WiFi, as ESP32-based home automation projects offer integrated wireless connectivity, dual-core processing, and a large number of GPIOs all in one affordable package.

The discussed IoT home automation technique utilises the phenomenal capabilities of ESP32, having 240MHz dual-core processors, 30 GPIO pins, and built-in WiFi/Bluetooth connectivity. This allows for a far more responsive and feature-packed smart home control system that is way cheaper than commercial ones and possibilities far more in customisation.

As always, we have given you the complete code and circuit diagram for this project, and all the software used here in this project is free and readily available. That being said, let's get started...

ESP32 Home Automation using Alexa and Google Assistant with Sinric Pro

Now, we need a platform that can bind our ESP32 with Google Assistant and Alexa, and for that, we have used something called Sinric Pro. It is very easy to use this platform, and it is free for limited use. For this project, you can just use the free plan of Sinric Pro, but if you want to control more devices from the same app, you might wanna consider upgrading to a paid plan. In this ESP32 smart home project, we are going to control an AC bulb using Google Assistant, Alexa, and a manual switch, all using Sinric Pro. 

esp32 sinric pro with alexa and google assistant

This means you have the flexibility to control your load using Google Home and the Amazon Alexa App, regardless of your location. And if there is no internet, you can still manage your appliances through the manual switches, without the need for additional devices like Google Nest or Amazon Echo Dot. This project brings the convenience of smart home automation to your fingertips.

Components Required for ESP32 Home Automation

Building a successful ESP32 home automation system requires carefully selected components that work together seamlessly. 

  • ESP32 Development Board

  • 1-channel 5V SPDT Relay Module

  • Manual Switch

  • 5V - 2A  AC/DC SMPS

  • Light bulb

  • Connecting wires or PCB (Printed Circuit Board)

ESP32 Home Automation Circuit Diagram

The ESP32 home automation circuit diagram is very simple. I have used the D22 GPIO to control the relay module, and the D12 GPIO is connected with a manual switch to control the relay module manually. The circuit below produces an ESP32 Google Assistant Integrated smart circuit, and allows for manual circuitry operation via a physical switch. The complete circuit diagram for IoT-based home automation using ESP32 is shown in the image below. 

Circuit Diagram for ESP32 Smart Home Automation

I have used a 5V 2Amp Switched-Mode Power Supply (SMPS) to convert AC to DC power, and this 5V supply is provided to both the ESP32 and the relay module. Based on the provided code, when the control pins of the relay module receive a LOW signal, the respective relay will turn on. Conversely, the relay will turn off when a HIGH signal is applied to the control pin. If you prefer to use pushbuttons, simply connect the pushbuttons between the GPIO pin and the GND pin instead of using switches.

ESP8266 Home Automation with Google Assistant & Alexa using Sinric Pro

The above image shows the backside of my project board. You can see that I used a higher gauge wire for the AC and have maintained proper distance and insulation (was added later) between the phase and neutral line. Caution: Working with AC mains requires prior knowledge and experience. Please be careful and take adult supervision if needed. 

In this tutorial video, I have covered the Assembly of the hardware with the required components and control relay with Google Assistant, Alexa and a switch. The image below shows the final product after wiring, soldering, and assembly.

ESP8266 Home Automation with Google Assistant & Alexa using Sinric Pro

 

ESP32 Pin Layout for Home Automation Projects

ESP32 GPIO PinFunctionConnection DetailsSignal TypeCode Reference
GPIO 22Relay Control OutputConnect to Relay Module IN pinDigital Output (Active LOW)#define RELAY_PIN 22
GPIO 12Manual Switch InputSwitch terminal with internal pullupDigital Input (INPUT_PULLUP)#define SWITCH_PIN 12
GPIO 2WiFi Status LEDBuilt-in LED or external LEDDigital Output (Status indicator)#define wifiLed 2
VIN (5V)Power InputSMPS 5V positive output terminalDC Power Supply (5V)Power rail
GNDGround ReferenceCommon ground for all componentsGround Connection (0V)Ground rail

 

Setting up Sinric Pro for ESP32 Google Home Integration

In this home automation project, I used a Sinric Pro Free account, which can control up to 3 loads for free. To get started, you'll need to add devices to your Sinric Pro account. I'll guide you through the process step by step, including creating a free account and adding your devices in Sinric Pro.

Another platform that is similar to Sinric Pro is Blynk. Previously, we have also built many projects using Blynk l like the IoT-based smart Fan speed controller. But in recent times, Blynk has put limitations on free accounts, which is why we have used Sinric Pro. I have already written an article on the Difference Between Sinric Pro and Blynk. You can also read that if interested. 

With Sinric Pro, you can easily connect with Google Home and Amazon Alexa App with ESP8266, NodeMCU, or ESP32 microcontroller to control any appliance with Google Assistant and Alexa. So, you can easily make any IoT-based home automation project with Sinric Pro. As per their current plan, you will get 3 devices for free. First visit sinric.pro/register.

Login Sinric Pro and Add Devices

Then enter all the required details and click on Register. Then enter the email ID and password, and click on login.

Create a Room in Sinric Pro

Before adding the devices, first, you have to create a room in the Sinric Pro.

Create a Room in Sinric Pro

To create a room in the Sinric Pro account, follow the steps. Go to Rooms in the left side menu. Click on the Add Room button. Enter the Room Name and Description. Click on Save.

Create a New Room in Sinric Pro

In this way, you can create multiple rooms as per your requirements.

How to Add Devices in Sinric Pro

If you use a Sinric Pro free account, then you can add 3 devices for free.

Add Devices in Sinric Pro

Please follow the steps to add devices to the Sinric Pro account.

Step 1 to Add Devices in Sinric Pro

First, select the Devices from the left side menu, then click on the Add Device button.

Step 2 to Add Devices in Sinric Pro

Enter the Device Name and Description. Then select the Device Type as per the requirement. Here, I have selected the device type as Switch, as I will control the SPDT relay. Then select the Room for the device. After that, click on Next.

Step 3 to Add Devices in Sinric Pro

This field is optional. If you want any push notifications related to this device, then you can turn on the notifications. Click on Next.

Step 4 to Add Devices in Sinric Pro

Again, this field is optional. If you want to set any timer to Auto On or Auto Off the device, after the predefined time, then you the set it here. Click on Next.

Step 5 to Add Devices in Sinric Pro

This is another optional field. You can define the wattage rating of the connected appliance to get the energy consumption estimation. Now, Click on Save. Now, you have successfully added one device to Sinric Pro.

How to Get Sinric Pro API KEY, API SECRET & Device_ID

Before uploading any example sketch to ESP8266 or ESP32, you have to enter the Sinric API KEY and API SECRET. To get the API KEY and API SECRET, you have to go to Credentials from the left side menu.

Get Sinric Pro API KEY , API SECRET & Device_ID

After that, copy the APP KEY and APP SECRET and paste them into the code. Also, enter the device ID in the code. You will find the Device ID from the Devices menu. This device ID is unique for each device. If you create 3 devices, then there will be 3 unique device IDs.

Add Devices in Sinric Pro

Required Libraries for ESP32 Google Home Programming

Before you begin writing the code, there are several steps you need to follow to install essential libraries.

Update the Preferences –> Additional boards Manager with the below URL

URLs:https://dl.espressif.com/dl/package_esp32_index.json, http://arduino.esp8266.com/stable/package_esp8266com_index.json

Then install the ESP8266 board from the Board manager or manually download the ESP8266 board, then download the required libraries from the following links

  • Sinric Pro by Boris Jaeger (Open Library Manager search for Sinric Pro and click install for ESP8266 & ESP32)

  • WebSockets by Markus Sattler (minimum Version 2.3.5)

  • ArduinoJson by Benoit Blanchon (minimum Version 6.12.0)

 

Library NameMinimum VersionInstallation MethodPurpose
SinricPro2.10.0+Arduino Library ManagerCloud communication and device management
WebSockets2.3.5+Manual ZIP installationReal-time bidirectional communication
ArduinoJson6.12.0+Arduino Library ManagerJSON parsing and serialisation
ESP32 Board Package2.0.0+Board ManagerESP32 core functionality and WiFi stack

Note: Download the latest versions of the libraries from the provided links. Afterwards, install the libraries by going to Arduino IDE -> Sketch -> Include Library -> Add Zip Library.

Technical Summary And GitHub Repository 

You can also get the code files from CircuitDigest's GitHub page. The link for the repo is given below 

code and SchematicsDownload

ESP32 Home Automation Programming Guide

The ESP32 home automation code for Google Home and Alexa is straightforward. When we send the 'on' and 'off' commands using a smartphone, the signals are sent to the relay module, which in turn controls the light bulb, turning it on and off. I have used the INPUT_PULLUP function in Arduino IDE instead of using the pull-up resistor with a switch. This cloud platform eliminates the complexity of creating custom server infrastructure while providing robust API services for ESP32 Google Home programming and Alexa integration.

Make sure to replace "YourWiFiSSID", "YourWiFiPassword", "YourAppKey", and "YourAppSecret" with your actual credentials.

#define WIFI_SSID     "YOUR-WIFI-NAME"
#define WIFI_PASS     "YOUR-WIFI-PASSWORD"
#define APP_KEY       "YOUR-APP-KEY"
#define APP_SECRET    "YOUR-APP-SECRET"

Additionally, replace "yourDeviceId" with your actual device ID. You can find the Device ID in the Devices menu of your Sinric Pro account. When you add a device in Sinric Pro, a unique ID is assigned to that device.

#define device_ID   "SWITCH_ID_HERE"

Sinric Pro Device ID

Code Explanation and Key Functions

This ESP32 home automation code is a full solution for controlling appliances with Google Assistant, Alexa, and manual switches. The code is designed for easy customisation, reliability, and security for all ESP32 home automation projects. Understanding the code structure is essential for customising your ESP32 home automation system. This section breaks down each major component and explains how they work together to create a reliable smart home control system.

#include <Arduino.h>
#include <WiFi.h>
#include "SinricPro.h"
#include "SinricProSwitch.h"

In this block, the necessary libraries are included in Arduino.h The core library for Arduino. WiFi.h The library for Wi-Fi connectivity. SinricPro.h The main SinricPro library for IoT integration. SinricProSwitch.h The library for creating a switch device using SinricPro.

#define WIFI_SSID         "YOUR-WIFI-NAME"    
#define WIFI_PASS         "YOUR-WIFI-PASSWORD"
#define APP_KEY           "YOUR-APP-KEY"      // Should look like "de0bxxxx-1x3x-4x3x-ax2x-5dabxxxxxxxx"
#define APP_SECRET        "YOUR-APP-SECRET "   // Should look like "5f36xxxx-x3x7-4x3x-xexe-e86724a9xxxx-4c4axxxx-3x3x-x5xe-x9x3-333d65xxxxxx" 
#define device_ID   "SWITCH_ID_HERE"

In this block, you define your Wi-Fi network credentials (WiFi_SSID and WiFi_PASS) and the credentials for your SinricPro IoT application (APP_KEY and APP_SECRET). And also, you define the device_ID, which represents the device ID associated with your switch in the SinricPro platform. Make sure to replace it with the actual device ID you've created.

#define RELAY_PIN    22 // D22
#define SWITCH_PIN   12 // D12
#define wifiLed   2   //D2

This block defines the GPIO pins used for the relay, switch, and the Wi-Fi LED indicator. RELAY_PIN is the pin connected to the relay, SWITCH_PIN is the pin connected to the manual switch, and wifiLed is the pin used to indicate Wi-Fi connection status.

bool lastSwitchState = true;
unsigned long lastSwitchChange = 0;
bool relayState = false;

 Here, you declare global variables that will be used throughout the sketch lastSwitchState keeps track of the previous state of the manual switch. lastSwitchChange records the time of the last switch state change. relayState represents the current state of the relay.

bool onPowerState(const String& deviceId, bool &state) {
  relayState = state;
  digitalWrite(RELAY_PIN, !relayState);
  return true;
}

This function is a callback that is called when the power state of the switch changes, either manually or through the SinricPro service. It toggles the relay's state (relayState) and returns true.

void handleSwitch() {
  unsigned long currentMillis = millis();
  bool switchState = digitalRead(SWITCH_PIN);
  if (switchState != lastSwitchState) {
    if (currentMillis - lastSwitchChange > DEBOUNCE_TIME) {
      if (switchState) {
        relayState = !relayState;  // Toggle the relay state
        digitalWrite(RELAY_PIN, relayState);
        SinricProSwitch &mySwitch = SinricPro[device_ID];
        mySwitch.sendPowerStateEvent(relayState);
      }
      lastSwitchChange = currentMillis;
    }
    lastSwitchState = switchState;
  }
}

The handleSwitch function is responsible for monitoring the manual switch for state changes. It uses the global variables to keep track of the switch state changes and debounce the switch. When a change is detected, it toggles the relay state and sends a power state event to SinricPro to keep it in sync.

void setupWiFi()
{
  Serial.printf("\r\n[Wifi]: Connecting");
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.printf(".");
    delay(250);
  }
  digitalWrite(wifiLed, HIGH);
  Serial.printf("connected!\r\n[WiFi]: IP-Address is %s\r\n", WiFi.localIP().toString().c_str());
}

The setupWiFi function is responsible for connecting to your Wi-Fi network. It prints a connection progress message. It waits until a successful connection is established and then prints the device's IP address.

void setupSinricPro() {
  SinricProSwitch& mySwitch = SinricPro[device_ID];
  mySwitch.onPowerState(onPowerState);
  SinricPro.begin(APP_KEY, APP_SECRET);
  SinricPro.restoreDeviceStates(true);
}

This function is responsible for setting up the Sinric Pro service for your IoT project. Here's what it does. SinricProSwitch&mySwitch = SinricPro[device_ID]. This line creates an instance of the SinricProSwitch class with the provided device_ID. This class represents the switch you want to control using Sinric Pro. mySwitch.onPowerState(onPowerState) Here, you register the onPowerState function as the callback for handling power state changes. When a command is sent to turn the switch on or off, this function will be called. SinricPro.begin(APP_KEY, APP_SECRET) Initializes the Sinric Pro service with your APP_KEY and APP_SECRET, which are unique identifiers for your Sinric Pro account. SinricPro.restoreDeviceStates(true). This line tells Sinric Pro to restore the device's state upon connection.

void setupRelay() {
  pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN,HIGH); // Initialize relay in the OFF state

This function is for setting up the relay pin pinMode(RELAY_PIN, OUTPUT). It configures the RELAY_PIN as an output pin, which is typically connected to a relay module that controls your light bulb. digitalWrite(RELAY_PIN, HIGH). It initialises the relay in the OFF state by setting the pin to HIGH.

void setupSwitch() {
  pinMode(SWITCH_PIN, INPUT_PULLUP);
}

This function is for setting up the manual switch pin pinMode(SWITCH_PIN, INPUT_PULLUP). It configures the SWITCH_PIN as an input pin with a pull-up resistor. This setup is common for manual switches.

void setup() {
  Serial.begin(BAUD_RATE);
  pinMode(wifiLed, OUTPUT);
  digitalWrite(wifiLed, LOW);
  setupRelay();
  setupSwitch();
  setupWiFi();
  setupSinricPro();  
}

The setup() function is where the initial setup of your IoT project takes place. Here's what happens: It initialises the serial communication for debugging Serial.begin(BAUD_RATE) It sets up the LED wifiLed to indicate the status of the Wi-Fi connection. Calls setupRelay() to configure the relay pin. Calls setupSwitch() to configure the manual switch pin. Calls setupWiFi() to connect to the Wi-Fi network. Calls setupSinricPro() to initialise the Sinric Pro service.

void loop() {
  SinricPro.handle();
  handleSwitch();
}

The loop() function is the main execution loop of your IoT project. It does the Calls SinricPro.handle() to handle incoming messages from Sinric Pro. Calls handleSwitch() to monitor the state of the manual switch and update the relay accordingly. This function is not explicitly defined in the code snippet you provided, but it is likely defined elsewhere in your code to manage manual switch input.

This code sets up your ESP32 home automation project to work with Sinric Pro, handles relay control, and monitors the manual switch for state changes. It allows you to control a connected device using both Sinric Pro and the manual switch.

ESP32 Alexa Home Automation

First, download and install the Amazon Alexa App from the Google Play Store or App Store.

Sinric Pro with Google Home and Alexa

Before connecting the Alexa, it is necessary to include devices in the Sinric Pro platform. In the Alexa App, tap More, then select Skills & Games. Search for Sinric Pro, and choose Sinric Pro from the results. Enable usage by tapping ENABLE TO USE. Input the email address and password associated with the Sinric account, and then proceed by tapping Sign in.

After connecting the Sinric Pro account, follow the steps below to add devices. 

Adding Device in Sinric Pro with Google Home & Alexa App

Tap on CLOSE. Tap on DISCOVER DEVICES. Now, Alexa will look for new devices. This may take some time. After that, go to Devices, then select Plug. You will find all the connected devices.

Now, if the ESP32 is connected to the Wi-Fi, then you can control the appliances from the Alexa App. You can also say “Alexa, Turn ON the light” to control the appliances with voice commands.

ESP32 Google Home Integration

First, download and install the Google Home App from the Google Play Store or App Store. The Google Home app serves as the primary interface for managing your ESP32 Google Assistant integration.  Integrating your ESP32 home automation system with Google Assistant requires connecting the Google Home app to your Sinric Pro account.

Google Assistant Integration with sinric pro

In the Google Home App, follow the following steps to create a Home. Click on the “+” icon (upper left corner). Tap on Create new home. Enter the Home nickname and address. Then tap on Continue. The Home is created. Now again tap on the “+” icon to add devices.

Create Home in Google Home Integration

After setting up your Home in the Google Home app, you can establish a connection between Sinric Pro and the Google Home app. Before connecting with Google Home, ensure that you have added devices to Sinric Pro. Follow the steps below to add devices.

Click on the “+” icon, then choose Set up device. Select Works with Google and search for Sinric Pro, then click on Sinric Pro. Input the email ID and password associated with your Sinric account, then click Sign in. Afterwards, return to the home screen of the Google Home app. You will now be able to view all the devices in your Google Home app.

After linking Sinric Pro, go to the homepage of the Google Home app. You'll find the connected devices from Sinric Pro. If the ESP32 is connected to Wi-Fi, you can control the appliances through the Google Home app. You can also command Google Assistant by saying, “Hey Google, Turn ON the light” to control the appliances.

ESP32 Smart Home Automation with Google Assistant and Alexa

After doing all these steps, now you control the light bulb with the Manual Switch, Google Assistant and Alexa. Once your ESP32 Google Assistant integration is complete, you can control your smart home devices using natural language commands. 

ESP32 home automation project demonstration

To control the light bulb with a switch or push button, just turn on and off the button. And if the ESP32 is connected to the Wi-Fi, then you can monitor the real-time status in Google Home and the Alexa App.

ESP32 Alexa Home Automation Working Demo

If the ESP32 is connected to WiFi, then you can ask Alexa to turn on the light [“Alexa, Turn ON Light“]. Thus, you can control the light with voice commands using the Amazon Alexa App, and also monitor the current status of the switches from anywhere in the world from the Alexa App. This dual compatibility ensures your ESP32 home automation system works with the most popular voice assistants available.

ESP32 google assistant home automation working demo

You can also ask Google Assistant to turn on the light [“Hey Google, Turn ON the Light“]. Thus, you can control the light with voice commands using Google Assistant, and also monitor the current status of the switches from anywhere in the world from the Google Home App.

esp32 smart home automation alexa google assistant working demonstration

 

Frequently Asked Questions on Home Automation Using ESP32

⇥ How does ESP32 home automation work? 
ESP32 home automation works by putting in a WiFi connection to the microcontroller. Hence, platforms such as Sinric Pro work to bridge communication between the voice assistants (Google/Alexa) and the relay modules that serve to turn AC devices on or off. Those voice-controlled devices can also be controlled through a smartphone app, and at the same time, all of this is updated in real time.

⇥ Is it safe to control AC appliances with an ESP32? 
Yes, it is safe to use the ESP32 to control AC appliances with relay modules to provide electrical isolation. The ESP32 is a 5V DC processor while controlling relay switches that switch AC mains power. Therefore, by wiring it correctly, insulating all AC connections, and following all electrical safety requirements, you will be able to safely operate AC appliances.

⇥  What is Sinric Pro, and why is it useful for ESP32 projects?
Sinric-Pro is a cloud-based platform that allows ESP32 devices to communicate with Google Assistant and Alexa. It is available for free use with up to 3 devices and voice command processing, synchronisation of device status, and removal of the cumbersome server settings process.

⇥  Can ESP32 home automation be done without the internet?
ESP32 home automation can be done offline with manual switches to control physically. However, voice commands using Google Assistant or Alexa require an internet connection to communicate with Sinric Pro cloud services. Local MQTT servers could enable some automation functionality without the internet.

⇥ Would ESP32 be better than Arduino for home automation purposes?
ESP32 is better than Arduino due to the presence of a number of things-builtin WiFi/Bluetooth capabilities, a dual-core processor, a larger number of GPIO pins (30 against 14), lesser power consumption, and integrated wireless, among others. Conversely, Arduino would need wireless add-on modules, and these can surely complicate your project and your life.

 

With this, we have concluded this project. For more DIY smart home automation projects, check out our Arduino Voice Controlled Home Automation, Temperature-based Smart Fan and Bluetooth-controlled Smart Home. Hope you enjoyed reading this tutorial. If you have any questions, please feel free to write in our forums, and we will try our best to help you out. 

 

Projects Similar to Home Automation

These projects integrate sensors, actuators, and wireless technologies to build smarter living spaces and focus on improving comfort and security. If you want to know more about those topics, links are given below.

IOT based Voice Controlled Home Automation using ESP8266 and Android App

IOT-based Voice-Controlled Home Automation using ESP8266 and Android App

This IoT-based voice-controlled home Automation project is super easy to build and does not cost you much since it does not require you to buy any costly voice modules. The whole project took around 500INR (8 USD) for me to build it. 

Building a Voice Controlled Home Automation with Arduino

Building a Voice-Controlled Home Automation with Arduino

Voice-controlled home Automation Using Arduino is an exciting project that aims to automate home appliances with the power of voice commands. In this project, voice instructions will be recognised, and text-to-speech conversion will be performed using an Android app. 

Smart Phone controlled Home Appliances with Energy Meter using NodeMCU

Smart Phone-controlled Home Appliances with Energy Meter using NodeMCU

We have come up with a project that will make your home smart, energy-efficient, Increase convenience, it will also allow you to have greater control of your energy use, and provide a platform for communication between user and device. Project work on NodeMCU, which is used to control and monitor the data of sensors. 

Complete Project Code

//ESP32 Home Automation Code
//by CircuitDigest
#include <Arduino.h>
#include <WiFi.h>
#include "SinricPro.h"
#include "SinricProSwitch.h"
#define WIFI_SSID         "YOUR-WIFI-NAME"    
#define WIFI_PASS         "YOUR-WIFI-PASSWORD"
#define APP_KEY           "YOUR-APP-KEY"      // Should look like "de0bxxxx-1x3x-4x3x-ax2x-5dabxxxxxxxx"
#define APP_SECRET        "YOUR-APP-SECRET"   // Should look like "5f36xxxx-x3x7-4x3x-xexe-e86724a9xxxx-4c4axxxx-3x3x-x5xe-x9x3-333d65xxxxxx"
#define device_ID   "SWITCH_ID_HERE"
#define RELAY_PIN    22 // D22
#define SWITCH_PIN   12 // D12
#define wifiLed   2   //D2
 
#define BAUD_RATE    9600
#define DEBOUNCE_TIME 250
bool lastSwitchState = true;
unsigned long lastSwitchChange = 0;
bool relayState = false;
bool onPowerState(const String& deviceId, bool &state) {
  relayState = state;
  digitalWrite(RELAY_PIN, !relayState);
  return true;
}

void handleSwitch() {
  unsigned long currentMillis = millis();
  bool switchState = digitalRead(SWITCH_PIN);
  if (switchState != lastSwitchState) {
    if (currentMillis - lastSwitchChange > DEBOUNCE_TIME) {
      if (switchState) {
        relayState = !relayState;  // Toggle the relay state
        digitalWrite(RELAY_PIN, relayState);
        SinricProSwitch &mySwitch = SinricPro[device_ID];
        mySwitch.sendPowerStateEvent(relayState);
      }
      lastSwitchChange = currentMillis;
    }
    lastSwitchState = switchState;
  }
}
void setupWiFi()
{
  Serial.printf("\r\n[Wifi]: Connecting");
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.printf(".");
    delay(250);
  }
  digitalWrite(wifiLed, HIGH);
  Serial.printf("connected!\r\n[WiFi]: IP-Address is %s\r\n", WiFi.localIP().toString().c_str());
}
void setupSinricPro() {
  SinricProSwitch& mySwitch = SinricPro[device_ID];
  mySwitch.onPowerState(onPowerState);
  SinricPro.begin(APP_KEY, APP_SECRET);
  SinricPro.restoreDeviceStates(true);
}
void setupRelay() {
  pinMode(RELAY_PIN, OUTPUT);
  digitalWrite(RELAY_PIN,HIGH); // Initialize relay in the OFF state
}
void setupSwitch() {
  pinMode(SWITCH_PIN, INPUT_PULLUP);
}

void setup() {
  Serial.begin(BAUD_RATE);
  pinMode(wifiLed, OUTPUT);
  digitalWrite(wifiLed, LOW);
  setupRelay();
  setupSwitch();
  setupWiFi();
  setupSinricPro();  
}
 
void loop() {
  SinricPro.handle();
  handleSwitch();
}
Video

Have any question related to this Article?

Add New Comment

Login to Comment Sign in with Google Log in with Facebook Sign in with GitHub