Using PIR sensor to control 360 servo cw and ccw

I’m trying to figure out how to use a PIR sensor to control a servo motor.
I would like the servo to not rotate when the PIR doesn’t sense anything, then when it does activate, rotate the servo one way for a second then back for a second. Basically, I want it to open and close a valve then repeat when the PIR goes off again.

This is what I’ve got so far.

#include <Servo.h>
Servo myServo;
int led=13;
int pir=2;

void setup()
  myServo.writeMicroseconds(1500);  // Stop


void loop()
  int val = digitalRead(pir);
    myServo.write(180); //open
myServo.write(1500); //Stop
    myServo.write(0); //close
myServo.write(1500); //Stop


Big thanks to anyone that can help :slight_smile:

You may need to re-think your approach as a standard servo does not rotate 360 degrees.
More like 180 degrees or less.
This is the standard rc servo with position feedback so you can send it to a certain position.

There are continuous rotation servos but they don't normally have the same feedback for position.
They would also be driven hard on, not via the servo command.
You could use similar to this but perhaps add a limit switch at each end of travel, rather than time basis as thie latter could change depending on supply voltage and load conditions.
As it is 360 degrees, I'd imagine you would have to carfully think how you would achieve the limit points as well.

Good job using code tags. Have a look at Autoformat, or Ctrl T, in the IDE!
And what is happening?

You didn't say what's (not-) happening, but assuming your servo is capable of doing what you want, I'm guessing your problem is due to the fact that you're looking at val to be high or low, and acting on whichever it is. So it's always going to be doing something.

But what you need to do is look for a low=>high or high=>low transition, ie you need to look for val to become high or low, not be high or low.

In the IDE, look at File / Examples / 2 Digital / StateChangeDetection and make another variable called say oldval and compare that to val, then see which way it changed if it changed, and do one thing or the other.