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 ledPin = LED_BUILTIN;
unsigned long previousMillis = 0;
bool state = false;
void setup() {
// put your setup code here, to run once:
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("Connected to the WiFi network");
}
void loop() {
// put your main code here, to run repeatedly:
delay(125);
unsigned long currentMillis = millis();
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!");
if(state == true) return;
switchLight(1, true);
// We only want to print on the output change, not state
pirState = HIGH;
}
} else {
digitalWrite(ledPin, LOW); // turn LED OFF
if(state == false) return;
switchLight(1, false);
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 switchLight(byte room, bool current_state){
state = current_state;
HTTPClient http;
String req_string;
req_string = "http://";
req_string += ip;
req_string += "/api/";
req_string += user_name;
req_string += "/lights/";
req_string += light_id;
req_string += "/state";
Serial.println(req_string);
http.begin(req_string);
http.addHeader("Content-Type", "text/plain");
String put_string;
put_string = "{\"on\":";
put_string += (current_state)? "true" : "false";
put_string += "}";
int httpResponseCode = http.PUT(put_string);
if(httpResponseCode > 0){
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
} else {
Serial.print("Error on sending PUT Request: ");
Serial.println(httpResponseCode);
}
http.end();
}
a side from providing some of my personal info with is not in this code im having trouble turning the lights off when the sensor detects motion the light will come on however it will not turn off any thoughts?