/**
ESP32 + DHT22 Example for Wokwi
https://wokwi.com/arduino/projects/322410731508073042
*/
#include <WiFi.h>
#include "ThingSpeak.h"
const int LED_PIN = 13;
const char* WIFI_NAME = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
const int myChannelNumber = 2261689;
const char* myApiKey = "Z9K3UNKOX26L4KEV";
const char* server = "api.thingspeak.com";
WiFiClient client;
const int PIR_input = 18;
int PIR_STATE = LOW;
int val = 0;
#define NTP_SERVER "pool.ntp.org"
#define UTC_OFFSET 0
#define UTC_OFFSET_DST 0
std::string printLocalTime() {
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
return "Connection Err";
}
char buffer[80]; // Assuming a maximum of 80 characters for the formatted time
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &timeinfo);
return buffer;
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
pinMode(PIR_input, INPUT);
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Wifi not connected");
}
Serial.println("Wifi connected !");
Serial.println("Local IP: " + String(WiFi.localIP()));
WiFi.mode(WIFI_STA);
configTime(UTC_OFFSET, UTC_OFFSET_DST, NTP_SERVER);
ThingSpeak.begin(client);
}
void loop() {
val = digitalRead(PIR_input);
if (val == HIGH)
{
ThingSpeak.setField(1, "Motion detected!!!");
std::string local_time = printLocalTime();
String localTimeString = String(local_time.c_str()); // Convert to String
ThingSpeak.setField(2, localTimeString);
Serial.println(localTimeString);
}
int x = ThingSpeak.writeFields(myChannelNumber, myApiKey);
if (x == 200) {
Serial.println("Data pushed successfull");
} else {
Serial.println("Push error" + String(x));
}
Serial.println("---");
delay(10000);
}