/*
   PIR sensor tester
*/
#include <WiFi.h>
#include <ThingSpeak.h>
#include "DHTesp.h"
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
WiFiClient client;
unsigned long myChannelNumber = 2080313;
const char * myWriteAPIKey = "SU93Z0L5ECOBG7U9";

int ledPin = 13;                // choose the pin for the LED
int inputPin = 2;               // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val = 0;                   // variable for reading the pin status
int statusCode;

void setup() {
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare sensor as input
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
  Serial.begin(9600);
}

void loop() {
  connectToCloud();
computeData();
writeData();
delay(1000);
}
void connectToCloud(){
if(WiFi.status() != WL_CONNECTED) {
Serial.print("Attempting to connect");
while(WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, pass);
for(int i=0;i<5;i++) {
Serial.print(".");
delay(1000);
}

}
Serial.println("\nConnected.");
}
}
void computeData(){
 val = digitalRead(inputPin);  // read input value
  if (val == HIGH) {            // check if the input is HIGH
    digitalWrite(ledPin, HIGH);  // turn LED ON
    if (pirState == LOW) {
      // we have just turned on
      Serial.println("Motion detected!");
      // We only want to print on the output change, not state
      pirState = HIGH;
    }
  } else {
    digitalWrite(ledPin, LOW); // turn LED OFF
    if (pirState == HIGH) {
      // we have just turned of
      Serial.println("Motion ended!");
      // We only want to print on the output change, not state
      pirState = LOW;
    }
  }
}
void writeData(){
ThingSpeak.setField(1, pirState);

statusCode = ThingSpeak.writeFields(myChannelNumber,myWriteAPIKey);
if(statusCode == 200) //successful writing code
Serial.println("Channel update successful.");
else
Serial.println("Problem Writing data. HTTP error code :" +
String(statusCode));
delay(15000); // data to be uploaded every 15secs
}