Hey newbie here. I'm trying to make a project where servo points to the direction of movement detected by PIR sensor. Works just fine with 1 sensor but when I try to use 2 my servo just starts jerking between set states and won't stop. I'm using UNO, 9g servo and SR505 PIR.
Thanks for help!
My code :
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int led=13; // the pin that the LED is atteched to
int ledPin = 13; // choose the pin for the LED
int inputPin = 2; // choose the input pin (for PIR sensor)
int inputPin1 = 4; // choose the input pin (for PIR sensor1)
int pirState = LOW; // we start, assuming no motion detected
int S = 0; // variable for reading the pin status
int S1 = 0;
void setup() {
myservo.attach(9);
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
pinMode(inputPin1, INPUT); // declare sensor as input
Serial.begin(9600);
myservo.write(0);
delay(8000); //delay for PIR to setup
}
void loop(){
PIR1();
PIR2();
CLR();
}
void PIR1() //PIR1 loop
{
S = digitalRead(inputPin); // read input value
if (S == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, HIGH); // turn LED ON
myservo.write(90);
if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected sector 1!");
// We only want to print on the output change, not state
pirState = HIGH;
}
}
}
void PIR2() //PIR2 loop
{
S1 = digitalRead(inputPin1); // read input value
if (S1 == HIGH) { // check if the input is HIGH
digitalWrite(ledPin, HIGH); // turn LED ON
myservo.write(180);
if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected sector 2!");
// We only want to print on the output change, not state
pirState = HIGH;
}
}
}
void CLR() //No motion loop
{
S = digitalRead(inputPin); // read input value
if (S == LOW && S1 == LOW) { // check if the input is HIGH
digitalWrite(ledPin, LOW); // turn LED OFF
myservo.write(0);
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;
}
}
}