hi , I’m trying to use PIR to automatically switch on my relay but it isnt working .im using two nodemcu ESP01, one node for my pir and the second for my relay.
the code for the pir:
#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP8266.h>
// WiFi network info.
char ssid[] = "M";
char wifiPassword[] = "e";
// Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char username[] = "";
char password[] = "";
char clientID[] = "";
int inputPin = 15; // 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 pinSpeaker = 13; //Set up a speaker on a PWM pin (digital 9, 10, or 11)
void setup() {
pinMode(inputPin, INPUT); // declare sensor as input
pinMode(pinSpeaker, OUTPUT);
Serial.begin(115200);
Cayenne.begin(username, password, clientID, ssid, wifiPassword);
}
void loop() {
Cayenne.loop();
val = digitalRead(inputPin); // read input value
if (val == LOW) { // check if the input is HIGH
playTone(1000, 160);
// Serial.println("BUZZER ON");
delay(50);
if (pirState == HIGH) {
// we have just turned on
Serial.println("Motion DETECTED!");
// We only want to print on the output change, not state
pirState = LOW;
}
}
else {
playTone(0, 0);
delay(20000);
if (pirState == LOW){
// we have just turned ON
Serial.println("Motion ENDED!");
// We only want to print on the output change, not state
pirState = HIGH;
}
}
}
// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
duration *= 1000;
int period = (1.0 / freq) * 1000000;
long elapsed_time = 0;
while (elapsed_time < duration) {
digitalWrite(pinSpeaker,HIGH);
delayMicroseconds(period / 2);
digitalWrite(pinSpeaker, LOW);
delayMicroseconds(period / 2);
elapsed_time += (period);
}
}
CAYENNE_OUT_DEFAULT()
{
Cayenne.virtualWrite(0, val, "motion", "d");
}
the code for the relay;
#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP8266.h>
int relayPin = 4; // relay pin D2
// WiFi network info.
char ssid[] = "M";
char wifiPassword[] = "e";
// Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char username[] = "";
char password[] = "";
char clientID[] = "";
void setup() {
pinMode(D2, OUTPUT);
Serial.begin(115200);
Cayenne.begin(username, password, clientID, ssid, wifiPassword);
}
void loop() {
Cayenne.loop();
digitalWrite(D2, LOW);
/* digitalWrite(pinOut, LOW);
delay(2000);
digitalWrite(pinOut, HIGH);
delay(25000);
*/
}
CAYENNE_IN(1)
{
digitalWrite(D2, getValue.asInt());
}
I’m new at programming , pls go through this