#include <Wire.h>
#include <DHT.h>
#include <ThingSpeak.h>
// Define pins
#define PIR_PIN 4 // GPIO pin for PIR motion sensor
#define BUTTON_PIN 16 // GPIO pin for smart switch (push button)
#define LED_PIN 17 // GPIO pin for LED
#define DHT_PIN 2 // GPIO pin for DHT22 sensor
// Define ThingSpeak parameters
const int THINGSPEAK_CHANNEL_ID =2383218; // Replace with your ThingSpeak channel ID
const char* THINGSPEAK_API_KEY ="X53XZTLGY7Q4T9GT"; // Replace with your ThingSpeak API key
// Create DHT sensor object
DHT dht(DHT_PIN, DHT22);
// Function prototype
void updateThingSpeak(float temperature, float humidity, int motionStatus, int switchStatus);
void setup() {
Serial.begin(115200);
// Initialize DHT sensor
dht.begin();
// Initialize GPIO pins
pinMode(PIR_PIN, INPUT);
pinMode(BUTTON_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
// Read sensor values
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
int motionStatus = digitalRead(PIR_PIN);
int switchStatus = digitalRead(BUTTON_PIN);
// Update ThingSpeak
updateThingSpeak(temperature, humidity, motionStatus, switchStatus);
// Your automation logic here
// Example: print sensor values to Serial Monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C, Humidity: ");
Serial.print(humidity);
Serial.print("%, Motion: ");
Serial.print(motionStatus);
Serial.print(", Switch: ");
Serial.println(switchStatus);
// Automation logic
if (motionStatus == HIGH) {
// Motion detected, turn on the lights
digitalWrite(LED_PIN, HIGH);
} else {
// No motion, turn off the lights
digitalWrite(LED_PIN, LOW);
}
delay(10000); // Adjust delay as needed
}
void updateThingSpeak(float temperature, float humidity, int motionStatus, int switchStatus) {
// Set ThingSpeak fields
ThingSpeak.setField(1, temperature);
ThingSpeak.setField(2, humidity);
ThingSpeak.setField(3, motionStatus);
ThingSpeak.setField(4, switchStatus);
// Update ThingSpeak
int status = ThingSpeak.writeFields(THINGSPEAK_CHANNEL_ID, THINGSPEAK_API_KEY);
if (status == 200) {
Serial.println("ThingSpeak update successful");
} else {
Serial.println("Error updating ThingSpeak. HTTP error code " + String(status));
}
}