Ping controlled servo switch?

So I'm quite new and ran into an issue with my most recent project. basically, I have a ping sensor controlling a sg90 servo. I'm trying to make the servo move up to flick on a light switch when the ping is closer than 5", then return back to 0 when triggered again to turn the switch off. Any help would be great thanks!


Of course, I am able to make the servo move to 120 degrees. My goal is to make it return to 0 when the same distance is sensed again to turn off the light switch

#include <Servo.h>
#define trigPin 9

#define echoPin 7

Servo servo;

void setup()


Serial.begin (9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);



void loop()


long duration, distance;

digitalWrite(trigPin, LOW);


digitalWrite(trigPin, HIGH);


digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distance = (duration/2) / 29.1;

if (distance < 5)






HC-SR04 ping sensor, sg90 servo, Arduino Uno. All the connections are fine I'm just not sure how I would code the return to 0 part ONLY when the same distance is tracked. Like walking through a doorway.

What you currently have is if distance < 5 send servo to 120 then do nothing for 400mS.

So exactly when do you want to send the servo back to 0? After 400ms if the distance is still <5 ? Or when, under what conditions? “Like walking through a doorway” is not a specification that I could code to.


My apologies! I'll try to be more specific. I would like to send the servo to 120 degrees (turning light switch on) when the ping detects an object >5" (walking through a doorway with ping)and stay at 120 until it detects another object >5" (walking out of doorway) which will return the servo back to 0 (Turing light switch off). I am able to get the servo to move to 120 degrees and stay there. I am unsure of how to make the servo return to 0 when a distance of >5" is detected. I'm not sure how else I can word it.

I guess you know what you’re thinking about but I don’t.

For example, don’t you need to work out how the program will tell the direction of travel? I.e. that the “object” is walking out of the doorway and it’s not a different “object” walking in (when presumably the light should stay on) ? Or is this a “doorway” to somewhere that only one “object” can ever be in at a time?

Perhaps after you have switched the light on you can check that distance has increased to greater than some value and only after that has happened wait for the next time distance is <5 then switch off?