Light Control by Voice Command

Iot Source code for voice control project .



// ESP32 Google Assistant + Alexa + Manual Home Automation with Sinric Pro

#include "Arduino.h"     //please replace the '' '' to <> before and after of "Arduino.h" and install the library

#include "WiFi.h"       //please replace the '' '' to <> before and after of "Wifi.h" and install the library

#include "SinricPro.h"                        //Install SinricPro Library

#include "SinricProSwitch.h"

#include "map"          //please replace the '' '' to <> before and after of "map" and install the library

// Uncomment the following line to enable serial debug output

//#define ENABLE_DEBUG

#ifdef ENABLE_DEBUG

       #define DEBUG_ESP_PORT Serial

       #define NODEBUG_WEBSOCKETS             

       #define NDEBUG

#endif

#define WIFI_SSID         "*****************"      //Enter Wi-Fi Name

#define WIFI_PASS         "****************"      //Enter Wi-Fi Password

#define APP_KEY           "********************************"                  //Enter APP-KEY

#define APP_SECRET        "*****************************************************"     //Enter APP-SECRET

//Enter the device IDs here

#define device_ID_1   "************************"  //SWITCH 1 ID

#define device_ID_2   "************************"  //SWITCH 2 ID

#define device_ID_3   "*************************"  //SWITCH 3 ID

// define the GPIO connected with Relays and switches

#define RelayPin1 15  //D15

#define RelayPin2 2  //D2

#define RelayPin3 4  //D4

#define SwitchPin1 23  //D23

#define SwitchPin2 22  //D22

#define SwitchPin3 21  //D21

#define wifiLed   2   //D2

//uncomment the following line if you use Push Buttons to toggle Relays

//#define TACTILE_BUTTON 1

#define BAUD_RATE   9600

#define DEBOUNCE_TIME 250

typedef struct {      // struct for the std::map below

  int relayPIN;

  int flipSwitchPIN;

} deviceConfig_t;

std::map"String, deviceConfig_t" devices = {     //please replace the '' '' to <> before and after of "String, deviceConfig_t" and install the library

    //{deviceId, {relayPIN,  flipSwitchPIN}}

    {device_ID_1, {  RelayPin1, SwitchPin1 }},

    {device_ID_2, {  RelayPin2, SwitchPin2 }},

    {device_ID_3, {  RelayPin3, SwitchPin3 }},

};

typedef struct {      // struct for the std::map below

  String deviceId;

  bool lastFlipSwitchState;

  unsigned long lastFlipSwitchChange;

} flipSwitchConfig_t;

std::map"int, flipSwitchConfig_t" flipSwitches;   //please replace the '' '' to <> before and after of "int, flipSwitchConfig_t" and install the library 
                                                  // this map is used to map flipSwitch PINs to deviceId and handling debounce and last flipSwitch state checks
                                                  // it will be setup in "setupFlipSwitches" function, using informations from devices map

void setupRelays() {

  for (auto &device : devices) {           // for each device (relay, flipSwitch combination)

    int relayPIN = device.second.relayPIN; // get the relay pin

    pinMode(relayPIN, OUTPUT);             // set relay pin to OUTPUT

    digitalWrite(relayPIN, HIGH);

  }

}

void setupFlipSwitches() {

  for (auto &device : devices)  {                     // for each device (relay / flipSwitch combination)

    flipSwitchConfig_t flipSwitchConfig;              // create a new flipSwitch configuration

    flipSwitchConfig.deviceId = device.first;         // set the deviceId

    flipSwitchConfig.lastFlipSwitchChange = 0;        // set debounce time

    flipSwitchConfig.lastFlipSwitchState = false;     // set lastFlipSwitchState to false (LOW)--

    int flipSwitchPIN = device.second.flipSwitchPIN;  // get the flipSwitchPIN

    flipSwitches[flipSwitchPIN] = flipSwitchConfig;   // save the flipSwitch config to flipSwitches map

    pinMode(flipSwitchPIN, INPUT_PULLUP);                   // set the flipSwitch pin to INPUT

  }

}

bool onPowerState(String deviceId, bool &state)

{

  Serial.printf("%s: %s\r\n", deviceId.c_str(), state ? "on" : "off");

  int relayPIN = devices[deviceId].relayPIN; // get the relay pin for corresponding device

  digitalWrite(relayPIN, !state);             // set the new relay state

  return true;

}

void handleFlipSwitches() {

  unsigned long actualMillis = millis();                                          // get actual millis

  for (auto &flipSwitch : flipSwitches) {                                         // for each flipSwitch in flipSwitches map

    unsigned long lastFlipSwitchChange = flipSwitch.second.lastFlipSwitchChange;  // get the timestamp when flipSwitch was pressed last time (used to debounce / limit events)

    if (actualMillis - lastFlipSwitchChange > DEBOUNCE_TIME) {                    // if time is > debounce time...

      int flipSwitchPIN = flipSwitch.first;                                       // get the flipSwitch pin from configuration

      bool lastFlipSwitchState = flipSwitch.second.lastFlipSwitchState;           // get the lastFlipSwitchState

      bool flipSwitchState = digitalRead(flipSwitchPIN);                          // read the current flipSwitch state

      if (flipSwitchState != lastFlipSwitchState) {                               // if the flipSwitchState has changed...

#ifdef TACTILE_BUTTON

        if (flipSwitchState) {                                                    // if the tactile button is pressed

#endif     

          flipSwitch.second.lastFlipSwitchChange = actualMillis;                  // update lastFlipSwitchChange time

          String deviceId = flipSwitch.second.deviceId;                           // get the deviceId from config

          int relayPIN = devices[deviceId].relayPIN;                              // get the relayPIN from config

          bool newRelayState = !digitalRead(relayPIN);                            // set the new relay State

          digitalWrite(relayPIN, newRelayState);                                  // set the trelay to the new state

          SinricProSwitch &mySwitch = SinricPro[deviceId];                        // get Switch device from SinricPro

          mySwitch.sendPowerStateEvent(!newRelayState);                            // send the event

#ifdef TACTILE_BUTTON

        }

#endif     

        flipSwitch.second.lastFlipSwitchState = flipSwitchState;                  // update lastFlipSwitchState

      }

    }

  }

}

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()

{

  for (auto &device : devices)

  {

    const char *deviceId = device.first.c_str();

    SinricProSwitch &mySwitch = SinricPro[deviceId];

    mySwitch.onPowerState(onPowerState);

  }

  SinricPro.begin(APP_KEY, APP_SECRET);

  SinricPro.restoreDeviceStates(true);

}

void setup()

{

  Serial.begin(BAUD_RATE);

  pinMode(wifiLed, OUTPUT);

  digitalWrite(wifiLed, LOW);

  setupRelays();

  setupFlipSwitches();

  setupWiFi();

  setupSinricPro();

}

void loop()

{

  SinricPro.handle();

  handleFlipSwitches();
}
}

AC Light Control By Voice Command

Arduino source code to run a 7 Segment display.



   // Define pin numbers for convenience

const int pin3 = 3;

const int pin12 = 12;

const int pin4 = 4;

const int pin11 = 11;

const int pin5 = 5;

const int pin10 = 10;
    
void setup() {

  // Set the pin modes for input (for 3, 4, 5) and output (for 10, 11, 12)

  pinMode(pin3, INPUT);

  pinMode(pin12, OUTPUT);

  pinMode(pin4, INPUT);

  pinMode(pin11, OUTPUT);

  pinMode(pin5, INPUT);

  pinMode(pin10, OUTPUT);

}

void loop() {

  // Check if the signal on pins 3, 4, or 5 is high

  if (digitalRead(pin3) == HIGH) {

    digitalWrite(pin12, HIGH);

  } else {

    digitalWrite(pin12, LOW);

  }

  if (digitalRead(pin4) == HIGH) {

    digitalWrite(pin11, HIGH);

  } else {

    digitalWrite(pin11, LOW);

  }

  if (digitalRead(pin5) == HIGH) {

    digitalWrite(pin10, HIGH);

  } else {

    digitalWrite(pin10, LOW);

  }

  // Add a small delay to debounce the inputs

  delay(50);

}
}

Smart Gas And Fire Detection & Monitoring System

Arduino source code for Rain sensor Project.


                 

/#include "Adafruit_GFX.h"          //please replace the '' '' to <> before and after "Adafruit_GFX.h" and install the library

#include "Adafruit_SSD1306.h"         //please replace the '' '' to <> before and after "Adafruit_SSD1306.h" and install the library

#include "DHT.h"                     //please replace the '' '' to <> before and after "DHT.h" and install the library

// OLED Display Settings

#define SCREEN_WIDTH 128

#define SCREEN_HEIGHT 64

#define OLED_RESET    -1

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// DHT11

#define DHTPIN 4

#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

// Sensors Analog Pins

#define MQ2_PIN 34

#define MQ6_PIN 35

#define MQ135_PIN 32

#define FLAME_PIN 33

#define BATTERY_PIN 36  // ADC1_CH0 (VP)

// Voltage divider resistors (R1=100k, R2=100k)

#define BATTERY_RATIO 2.0

#define ADC_RESOLUTION 4095.0

#define REF_VOLTAGE 3.3

//BUZZER

#define BUZZER_PIN 5

void setup() {

  Serial.begin(115200);

  dht.begin();

 // Initialize OLED

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {

    Serial.println(F("SSD1306 allocation failed"));

    while (1);

  }

  display.clearDisplay();

 // Sensor pins

  pinMode(FLAME_PIN, INPUT);

  pinMode(BUZZER_PIN, OUTPUT);

}

void loop() {

  // Read Sensors

  float temperature = dht.readTemperature();

  float humidity = dht.readHumidity();

  int mq2 = analogRead(MQ2_PIN);

  int mq6 = analogRead(MQ6_PIN);

  int mq135 = analogRead(MQ135_PIN);

  int flame = digitalRead(FLAME_PIN);

  //BUZZER

    if (flame == LOW) { // Flame detected

    digitalWrite(BUZZER_PIN, HIGH);

    Serial.println("Flame detected! Buzzer ON.");

    display.println("Buzzer ON.");

  } else {

    digitalWrite(BUZZER_PIN, LOW);

    Serial.println("No flame. Buzzer OFF.");

    display.println("Buzzer OFF.");

  }

  // Battery voltage

  int rawADC = analogRead(BATTERY_PIN);

  float batteryVolt = (rawADC / ADC_RESOLUTION) * REF_VOLTAGE * BATTERY_RATIO;

  // Serial Monitor

  Serial.printf("Temp: %.1f C, Humidity: %.1f %%\n", temperature, humidity);

  Serial.printf("MQ2: %d, MQ6: %d, MQ135: %d, Flame: %s\n", mq2, mq6, mq135, flame == LOW ? "DETECTED" : "Safe");

  Serial.printf("Battery Voltage: %.2f V\n", batteryVolt);

 // OLED Display

  display.clearDisplay();

  display.setTextSize(1);

  display.setTextColor(SSD1306_WHITE);

  display.setCursor(0, 0);

  display.printf("Temp:%.1f C Hum:%.1f%%\n", temperature, humidity);

  display.printf("MQ2: %d\n", mq2);

  display.printf("MQ6: %d\n", mq6);

  display.printf("MQ135: %d\n", mq135);

  display.printf("Flame: %s\n", flame == LOW ? "ALERT!" : "Normal");

  display.printf("Battery: %.2f V\n", batteryVolt);

  display.display();

  delay(2000); // Refresh every 2 seconds

}


Smart Agriculture System

Arduino source code for Soil Moisture Sensor.




#include "Adafruit_GFX.h"              //please replace the '' '' to <> before and after of "Adafruit_GFX.h" and install the library

#include "Adafruit_SSD1306.h"         //please replace the '' '' to <> before and after of "Adafruit_SSD1306.h" and install the library

#include "DHT.h"                           //please replace the '' '' to <> before and after "DHT.h" and install the library

// OLED display setup

#define SCREEN_WIDTH 128

#define SCREEN_HEIGHT 64

#define OLED_RESET    -1

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// DHT11 setup

#define DHTPIN 4         // GPIO pin for DHT11

#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

// Pin Definitions

#define SOIL_MOISTURE_PIN 34  // Analog pin

#define RAIN_SENSOR_PIN    35  // Analog pin

#define RELAY_PIN          26  // Relay connected to pump

// Battery check (optional)

#define BATTERY_PIN        33  // ADC1 channel for battery voltage

void setup() {

  Serial.begin(115200);

// Initialize display

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {

    Serial.println("SSD1306 not found");

    for (;;);

  }

 display.clearDisplay();

  display.setTextSize(1);

  display.setTextColor(SSD1306_WHITE);

  dht.begin();

pinMode(RELAY_PIN, OUTPUT);

  digitalWrite(RELAY_PIN, LOW); // Keep pump off initially

 displayMessage("System Initializing...");

}

void loop() {

  delay(2000);

// Read DHT11

  float temp = dht.readTemperature();

  float hum = dht.readHumidity();

 // Read soil moisture (0 dry - 4095 wet for ESP32 ADC)

  int soilRaw = analogRead(SOIL_MOISTURE_PIN);

  float soilPercent = map(soilRaw, 4095, 0, 0, 100); // Calibrated for ESP32

 // Read rain sensor

  int rainRaw = analogRead(RAIN_SENSOR_PIN);

  bool isRaining = rainRaw < 2000; // Tune threshold as needed

// Battery voltage read (optional)

  float batteryVoltage = analogRead(BATTERY_PIN) * (3.3 / 4095.0) * 2; // if using voltage divider

// Show data on OLED

  display.clearDisplay();

  display.setCursor(0,0);

  display.printf("Temp: %.1f C\n", temp);

  display.printf("Hum: %.1f %%\n", hum);

  display.printf("Soil: %.0f %%\n", soilPercent);

  display.printf("Rain: %s\n", isRaining ? "Yes" : "No");

  display.printf("Pump: %s\n", (soilPercent < 30 && !isRaining) ? "ON" : "OFF");

  display.printf("Battery: %.2f V", batteryVoltage);

  display.display();

 // Pump control logic

  if (soilPercent < 30 && !isRaining) {

    digitalWrite(26, LOW);  // Turn on pump

  } else {

    digitalWrite(26, HIGH);   // Turn off pump

  }

}

void displayMessage(String msg) {

  display.clearDisplay();

  display.setCursor(0, 0);

  display.println(msg);

  display.display();

}
}

Smart Temperature Monitoring System

Arduino source code for Flame Sensor.



#include "Wire.h"            //please replace the '' '' to <> before and after of "Wire.h" and install the library

#include "Adafruit_GFX.h"         //please replace the '' '' to <> before and after of "Adafruit_GFX.h" and install the library

#include "Adafruit_SSD1306.h"       //please replace the '' '' to <> before and after of "Adafruit_SSD1306.h" and install the library

#include "DHT.h"                       //please replace the '' '' to <> before and after of "DHT.h" and install the library

#define SCREEN_WIDTH 128

#define SCREEN_HEIGHT 64

#define OLED_RESET    -1

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// DHT11 settings

#define DHTPIN 2     // Pin connected to DATA of DHT11

#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

    void setup() {

  Serial.begin(9600);

  dht.begin();

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {

    Serial.println(F("SSD1306 allocation failed"));

    for(;;);

  }

  display.clearDisplay();

  display.setTextSize(1);

  display.setTextColor(SSD1306_WHITE);

}

void loop() {

  // Read temperature and humidity

  float humidity = dht.readHumidity();

  float temperature = dht.readTemperature(); // Celsius

  // Check if any reads failed

  if (isnan(humidity) || isnan(temperature)) {

    Serial.println(F("Failed to read from DHT sensor!"));

    display.clearDisplay();

    display.setCursor(0, 20);

    display.println(F("Sensor Error"));

    display.display();

    delay(2000);

    return;

  }

  // Print to Serial Monitor

  Serial.print(F("Humidity: "));

  Serial.print(humidity);

  Serial.print(F("%  Temperature: "));

  Serial.print(temperature);

  Serial.println(F("°C"));

  // Display on OLED

  display.clearDisplay();

  display.setCursor(0, 0);

  display.println(F("Temp & Humidity"));

  display.setCursor(0, 25);

  display.print(F("Temp: "));

  display.print(temperature);

  display.println(F(" C"));

  display.setCursor(0, 45);

  display.print(F("Hum:  "));

  display.print(humidity);

  display.println(F(" %"));

  display.display();

  delay(2000); // Update every 2 seconds

}

Smart Weather Monitoring System

Arduino source code for DHT 11 Sensor.



#include "WiFi.h"            //please replace the '' '' to <> before and after of "Wifi.h" and install the library        

#include "HTTPClient.h"  //please replace the '' '' to <> before and after of "HTTPClient.h" and install the library

#include "DHT.h"        //please replace the '' '' to <> before and after of "DHT.h" and install the library

// fill in the * indication

// ---------- WiFi ----------

const char* ssid = "********************";    // write your wifi ssid

const char* password = "****************";   // write your wifi Password

// ---------- ThingSpeak ----------

String apiKey = "********************";     // write the apikey from thingspeak.com

const char* server = "http://api.thingspeak.com/update";

// ---------- DHT11 ----------

#define DHTPIN 4

#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {

  Serial.begin(115200);

  dht.begin();

  WiFi.begin(ssid, password);

  Serial.print("Connecting");

  while (WiFi.status() != WL_CONNECTED) {

    delay(500);

    Serial.print(".");

  }

  Serial.println("\nWiFi Connected");

}

void loop() {

  float temp = dht.readTemperature();

  float hum = dht.readHumidity();

  if (isnan(temp) || isnan(hum)) {

    Serial.println("DHT Error");

    delay(2000);

    return;

  }

  if (WiFi.status() == WL_CONNECTED) {

    HTTPClient http;

    String url = server + String("?api_key=") + apiKey +

                 "&field1=" + String(temp) +

                 "&field2=" + String(hum);

    http.begin(url);

    int httpCode = http.GET();

    http.end();

    Serial.println("Data Sent to ThingSpeak");

  }

  delay(15000);   // ThingSpeak needs minimum 15 sec delay

}
}

ESP32 Gas Sensor Project

Arduino source code to connect OLED Display



#include "Adafruit_GFX.h"            //please replace the '' '' to <> before and after of "Adafruit_GFX.h" and install the library

#include "Adafruit_SSD1306.h"        //please replace the '' '' to <> before and after of "Adafruit_SSD1306.h" and install the library

#include "DHT.h"                     //please replace the '' '' to <> before and after of "DHT.h" and install the library

// OLED Display Settings

#define SCREEN_WIDTH 128

#define SCREEN_HEIGHT 64

#define OLED_RESET    -1

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// DHT11

#define DHTPIN 4

#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

// Sensors Analog Pins

#define MQ2_PIN 34

#define MQ6_PIN 35

#define MQ135_PIN 32

#define FLAME_PIN 33

#define BATTERY_PIN 36  // ADC1_CH0 (VP)

// Voltage divider resistors (R1=100k, R2=100k)

#define BATTERY_RATIO 2.0

#define ADC_RESOLUTION 4095.0

#define REF_VOLTAGE 3.3

//BUZZER

#define BUZZER_PIN 5

void setup() {

  Serial.begin(115200);

  dht.begin();

 // Initialize OLED

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {

    Serial.println(F("SSD1306 allocation failed"));

    while (1);

  }

  display.clearDisplay();

 // Sensor pins

  pinMode(FLAME_PIN, INPUT);

  pinMode(BUZZER_PIN, OUTPUT);

}

void loop() {

  // Read Sensors

  float temperature = dht.readTemperature();

  float humidity = dht.readHumidity();

  int mq2 = analogRead(MQ2_PIN);

  int mq6 = analogRead(MQ6_PIN);

  int mq135 = analogRead(MQ135_PIN);

  int flame = digitalRead(FLAME_PIN);

  //BUZZER

    if (flame == LOW) { // Flame detected

    digitalWrite(BUZZER_PIN, HIGH);

    Serial.println("Flame detected! Buzzer ON.");

    display.println("Buzzer ON.");

  } else {

    digitalWrite(BUZZER_PIN, LOW);

    Serial.println("No flame. Buzzer OFF.");

    display.println("Buzzer OFF.");

  }

  // Battery voltage

  int rawADC = analogRead(BATTERY_PIN);

  float batteryVolt = (rawADC / ADC_RESOLUTION) * REF_VOLTAGE * BATTERY_RATIO;

  // Serial Monitor

  Serial.printf("Temp: %.1f C, Humidity: %.1f %%\n", temperature, humidity);

  Serial.printf("MQ2: %d, MQ6: %d, MQ135: %d, Flame: %s\n", mq2, mq6, mq135, flame == LOW ? "DETECTED" : "Safe");

  Serial.printf("Battery Voltage: %.2f V\n", batteryVolt);

 // OLED Display

  display.clearDisplay();

  display.setTextSize(1);

  display.setTextColor(SSD1306_WHITE);

  display.setCursor(0, 0);

  display.printf("Temp:%.1f C Hum:%.1f%%\n", temperature, humidity);

  display.printf("MQ2: %d\n", mq2);

  display.printf("MQ6: %d\n", mq6);

  display.printf("MQ135: %d\n", mq135);

  display.printf("Flame: %s\n", flame == LOW ? "ALERT!" : "Normal");

  display.printf("Battery: %.2f V\n", batteryVolt);

  display.display();

  delay(2000); // Refresh every 2 seconds

}
    
Chip Craft Footer