I have a robotic arm (2DOF) which I activate based on the PIR sensor movement detection. The nano has the following connections:
Pin 6 - PIR Data
Pin 7 - Servo 1 Signal
Pin 8 - Servo 2 Signal
Pin 5V - VCC on Servo1, Servo2 && PIR
Pin GND- GND on Servo1,Servo3&&PIR
Its starts out fine, buteven if no movement it triggers after a few seconds, then it stops, but after a few more seconds it triggers again and so on. Triggering even gets faster after a while. Im powering the nano through a usb cable to a 5v/2A plug. I guess the servos are interfering or something with the nano, but Im not sure what or how to fix it. I even moved the attach() command out from setup to only upon triggering and added a detach() as well, to avoid the servos from drawing that quirky power they draw while attached but still.
Here is the code:
#include <Servo.h>
int pirPin = 6;
int state = LOW;
int val = 0;
Servo leftElbowServo;
Servo leftPincerServo;
void setup() {
Serial.begin(9600);
pinMode (pirPin, INPUT);
}
void loop() {
val = digitalRead(pirPin); // read sensor value
if (val == HIGH) { // check if the sensor is HIGH
digitalWrite(13, HIGH); // turn LED ON
delay(1000); // delay 100 milliseconds
Serial.println("motion...attach and run");
if (state == LOW) {
attachServos();
state = HIGH; // update variable state to HIGH
startRoutine();
}
} else if (val == LOW){ //if val=LOW
digitalWrite(13, LOW); // turn LED OFF
delay(2000); // delay 200 milliseconds
Serial.println("all is quiet");
detachServos();
if (state == HIGH){
state = LOW; // update variable state to LOW
}
}
}
void attachServos() {
// Setup Servos
//Servo1 - Left elbow
leftElbowServo.attach(7);
//Servo2 - Left Pincer
leftPincerServo.attach(8);
zeroOut();
}
void detachServos() {
zeroOut();
leftElbowServo.detach();
leftPincerServo.detach();
}
void startRoutine() {
//zeroOut();
//delay(1000);
liftLeft();
delay(1000);
openLeft();
delay(1000);
lowerLeft();
delay(1000);
closeLeft();
delay(1000);
}
void zeroOut(){
leftElbowServo.write(10);
leftPincerServo.write(10);
}
void liftLeft(){
leftElbowServo.write(150);
}
void lowerLeft(){
leftElbowServo.write(40);
}
void openLeft(){
leftPincerServo.write(150);
}
void closeLeft(){
leftPincerServo.write(40);
}