Thursday, September 23, 2010

Motion Detection (PIR) to Start Servo Code

This code is a combination of the Servo code from the Arduino guide and the PIR code from smartsurfaces.net/pir


#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
int ledPin = 9; // led connected to control pin 13
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object



 pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
 Serial.begin(9600); // use the serial port
}
int pirSensor = 0; // the passive infra red sensor will be plugged at analog pin 0
byte val = 0; // variable to store the value read from the sensor pin
int statePin = HIGH; // variable used to store the last LED status, to toggle the light
int THRESHOLD = 5; // threshold value to decide when detected motion is movement or not


void loop() {
  val = analogRead(pirSensor); // read the sensor and store it in the variable "val"
  if (val >= THRESHOLD) {
    statePin = !statePin; // toggle the status of the ledPin (this trick doesn't use time cycles)
    digitalWrite(ledPin, statePin); // turn the led on or off
    Serial.println("Motion Detected"); // send the string "Motion Detected" back to the computer, followed by newline
 for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
{ // in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
  }
  delay(150); // A delay to avoid overloading the serial port



}


Warning: some of the comments may no longer be in the correct places


1 comment:

  1. Try putting the if statement and the blinking inside the for loop. That should make it stop moving midway through the sweep if there is no motion.
    Another thing, I don't understand the THRESHOLD value. It was really difficult to stop the PIR from picking up movement. Did you have these problems?

    ReplyDelete