#include <WiFi.h>
#include <ThingSpeak.h>
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
WiFiClient client;
unsigned long myChannelNumber = 2072481;
const char * myWriteAPIKey = "0L3GIZCJMV1N7IYF";
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()
{
Serial.begin(115200);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
}
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, val);
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);
}