This is an existing sketch I got from a motion tracking camera on instructables, I'm using it for a skeleton. I need to add a trigger when movement is detected to turn a sound on. I've tried to integrate bits and pieces from other sketches but it never compiles correctly. I'm at my wits end. Was only able to copy and paste the sketch. Sorry.
Here is my program. Pretty self explanatory. I assign each PIR pin to an array and in my main loop cycle through the array checking each PIR for a HIGH state. If it goes HIGH then move the servo to the corresponding PIR servo position.
I originally set it up for 5 PIRs but one of the wiring harnesses was bad so rather than tear it apart and fix it I went with just 4 PIRs.
The program does two other things. If the a PIR is HIGH and the servo is already at that PIRs corresponding position, dont move it.
Also, I use another array to track if the PIR has been used since it went HIGH. I only allow it to be used once for each HIGH state. If you don't do that you get added movement between adjacent PIRs that is not necessary.
I just turn on the LED whenever a PIR is HIGH so I can tell by looking at the Arduino if there is some activity in the PIRs.
#include <Servo.h>
// author: jim demello feb 2014 //
boolean pirStatus;
Servo servo1;
int servangle = 0; // servo angle variable
int pirNo[] = {3,4,5,6,7}; // pir pin numbers
int pirPrevLow[] = {1,1,1,1,1}; // previously low flag set to true
int pirPrevUsed[] = {0,0,0,0,0}; // has pir been on used before going low
int pirPos[] = {10,60,100,140,170}; // positions for servo (0-180)
int curPosPir = 0;
int pirPin = 3;
int ledPin = 13;
void setup(){
Serial.begin(9600);
servo1.attach(9);
for(int i=0;i<4;i++){
pinMode(pirNo*, INPUT);*
- }*
- pinMode(ledPin, OUTPUT);*
- delay(10000); // calibrate for about 10 seconds*
- // servo1.write(90); // put servo at center to begin*
- }*
////////////////////////////
//Main LOOP
//////////////////
void loop(){ - for(int j=0;j<4;j++){ // for each PIR*
- pirPin=pirNo[j];*
- pirStatus = digitalRead(pirPin);*
- if (pirStatus == HIGH) {*
- digitalWrite(ledPin, HIGH); //the led visualizes the sensors output pin state*
- if(pirPrevLow[j]) {*
- if (curPosPir != pirPin && pirPrevUsed[j] == 0) { // if high PIR is different than current position PIR then move to new position*
- servo1.write(pirPos[j]);*
- Serial.println(j);*
- delay(50);*
- curPosPir = pirPin; // keep current PIR*
- pirPrevUsed[j] = 1;*
- }*
- pirPrevLow[j] = 0; // pir is now not low*
- }*
- }*
- else {*
- digitalWrite(ledPin, LOW); //the led visualizes the sensors output pin state*
- pirPrevLow[j] = 1; // pir is now low*
- pirPrevUsed[j] = 0;*
- }*
- } // end j number of pirs loop*
- }// end infinite loop*