Hello!
This is my first post here and I am very new to Arduino and programming in general. I am making a school project with 4 motion sensors and Arduino UNO. The problem is that this code works well when there is 2 sensors (obviously have to change it a little then) but when there is 4 sensors it doesnt behave correctly and starts randomly spamming Motion detected and Motion ended sometimes. How do I fix this? Also I never get "Motion detected!On sensors 1,2", so there is always only 1 sensor that detects. Any help would be much appreciated!
Here is the code(got it online when it was meant for 1 sensor and modified it for 4 sensors):
int ledPin = 13; // choose the pin for the LED
int inputPin = 3; // choose the input pin (for PIR sensor)
int inputPin2 = 4;
int inputPin3 = 5;
int inputPin4 = 6;
int pirState = LOW; // we start, assuming no motion detected
int val2 = 0; // variable for reading the pin status
int val3 = 0;
int val4 = 0;
int val5 = 0;
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
pinMode(inputPin2, INPUT);
pinMode(inputPin3, INPUT);
pinMode(inputPin4, INPUT);
Serial.begin(9600);
}
void loop(){
val2 = digitalRead(inputPin); // read input value
val3 = digitalRead(inputPin2);
val4 = digitalRead(inputPin3);
val5 = digitalRead(inputPin4);
if (val2 == HIGH && val3 == LOW && val4 == LOW && val5 == LOW) { // check if the input is HIGH
digitalWrite(ledPin, HIGH); // turn LED ON
if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected!1");
// We only want to print on the output change, not state
pirState = HIGH;
}
}
else if (val2 == LOW && val3 == HIGH && val4 == LOW && val5 == LOW) {
digitalWrite(ledPin, HIGH); // turn LED ON
if (pirState == LOW) {
Serial.println("Motion detected!2");
pirState = HIGH;
}
}
else if (val2 == LOW && val3 == LOW && val4 == HIGH && val5 == LOW) {
digitalWrite(ledPin, HIGH);
if (pirState == LOW) {
Serial.println("Motion detected!3");
pirState = HIGH;
}
}
else if (val2 == LOW && val3 == LOW && val4 == LOW && val5 == HIGH) {
digitalWrite(ledPin, HIGH);
if (pirState == LOW) {
Serial.println("Motion detected!4");
pirState = HIGH;
}
else if (val2 == HIGH && val3 == HIGH && val4 == LOW && val5 == LOW) {
digitalWrite(ledPin, HIGH);
if (pirState == LOW) {
Serial.println("Motion detected!On sensors 1,2");
pirState = HIGH;
}
}
} else {
digitalWrite(ledPin, LOW); // turn LED OFF
if (pirState == HIGH){
Serial.println("Motion ended!");
pirState = LOW;
}
}
}