# Motion sensor and Servo Part II

So i previously posted a topic about how would i get a servo to do a certain string of actions with a PIR sensor now i’ve kind of got it working but i’d like someone to help me with the final bit of the code.
i’m using an Arduino Uno SMD Rev3 with Arduino 1.0.5 programming environment.

What i’m trying to do is to have a servo move 180 degrees and back on loop but when the PIR detects motion make the servo snap to 90 degrees from any position it was in at the time. unfortunately i don’t have the knowledge to do it but i’d be great if someone could help me.
people have recommended using millis instead of delay but i have no idea how to use it and incorperate it so if you know how to it would be awesome if you could show me.

my code is here

``````void loop()                               // the loop routine runs over and over again forever
{{
for(pos = 180; pos>=1; pos-=1);          // servo to move 180 degrees from 0 in 1 step increments
myservo.write(pos);                      // Move servo to postion
delay(300);                              //  take 300milliseconds to get to position
for(pos = 0; pos < 180; pos+=1)          // Servo to move from 180 to 0 in 1 step increments
myservo.write(pos);                      // move servo to position
delay(300);                              // Take 300milliseconds to get to position
}{int sensor_1 = digitalRead(motion_1);    // the sensor detects variable motion
if (sensor_1 == HIGH)                    // if PIR sensor detects motion
digitalWrite (light_1, LOW);             // Turn LED on
for(pos = 90; pos < 180; pos+=1         // servo to move to 90 from 180 in 1 step increments
myservo.write(pos);                     // move servo to postion
delay(50);
}}
``````

If you could help that’d be greatly appreciated, thank you.
-Tryndus

This is the pseudo code that I put in the other thread to which I have added more comments.

``````define the interval between servo movements  //unsigned long interval = 10; //adjust value to suit
set time of previous servo movement to now //prevMoveTime = millis();
start of loop
read the PIR and if activated call the action() function
is it time to move the servo yet ?  //if( millis() - prevMoveTime > interval)
if yes
check the servo position and direction and move it appropriately
save the time of the movement  //prevMoveTime = millis();
end of if
end of loop

action() function
actions to be taken when the PIR detects movement
end of function
``````

Compare it with the BlinkWithoutDelay example and you should see the principle being used. You will need extra variables to hold the servo position and the direction that it should be moved in. If it has reached either end of its range, change the direction variable before updating the servo position variable.

Did you look at and understand the BlinkWithoutDelay example ?