Howdy,
I am able to get my servo to rotate, but for some reason it starts vibrating after it rotates. I have looked around online and saw that maybe servo.detach(); will work, but (as you can see in my code below), that doesn't really help because I can't set my servo back to another angle after that.
I am just trying to get the servo to rotate when there's motion detected by my PIR sensor:
/*
This will use a PIR, green LED, red LED, and a servo. When there is no movement detected, the LED will shine RED and the Servo will be at 0 degrees.
When movement is detected, the greed LED will light and the Servo will rotate 180 degrees.
*/
#include <Servo.h>
Servo myServo; // create a servo object
int servoAngle; //variable to hold theangle for the servo motor
int IRpin = 2; // choose the input pin (for PIR sensor)
int greenLed = 4; // choose the green LED
int redLed = 3; // choose the red LED
int pirState = LOW; // we start, assuming no motion detected
int val = 5; // variable for reading the pin status
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(greenLed, OUTPUT);
pinMode(redLed, OUTPUT);
pinMode(IRpin, INPUT);
delay(5000);
myServo.attach(9); // attaches the servo to pin 8 on the arduino.
myServo.write(1); //Start the Servo at 0 degrees
Serial.begin(9600);
}
void GreenOn(){
digitalWrite(greenLed, HIGH); // turn the green LED on (HIGH is the voltage level)
myServo.attach(9); // start sending signals to servo
myServo.write(179); // rotate the Servo 180 [really 179] degrees
myServo.detach(); // stop sending signals to servo
Serial.println("Motion detected at: ");
}
void GreenOff () {
digitalWrite(greenLed, LOW);
}
void RedOn() {
digitalWrite(redLed, HIGH); // turn the green LED on (HIGH is the voltage level)
myServo.attach(9); // start sending signals to servo
myServo.write(0); // puts the Servo back at 0 degrees
myServo.detach(); // stop sending signals to servo
}
void RedOff() {
digitalWrite(redLed, LOW);
}
// the loop routine runs over and over again forever:
void loop() {
val = digitalRead(IRpin); //read the input value from the IR sensor
if (val == HIGH) { //check if the input is HIGH (i.e. detects motion)
RedOff();
GreenOn();
}
else { // if there's no movement, stay RED
GreenOff();
RedOn();
}
}
Thanks for any help/ideas!