Make servo move 90 degrees based on ultra sonic input.

Hello,

I am kinda new so will need some help.

I want my servo to open (move 90 degrees) when my ultrasonic sensor reads anything between 1 and 10 centimers. And when the object is removed it want it to close again so move 90 degrees.

This is the code I have right now.

#include <NewPing.h>
#include <Servo.h>

const int Servopin = 11;
const int Triggerpin = 3;
const int Echopin = 2;

//100 = maxDistance
NewPing sonar(Triggerpin, Echopin, 100);
Servo servo;

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
servo.attach(Servopin);
}

void loop() {
int cm = sonar.ping_cm();
Serial.println (cm);

int angle = map(cm, 1, 10, 15, 90);
servo.write(angle);

delay(3000); // put your main code here, to run repeatedly:

}

Please let me know what i have to do since I am out of luck.

Thanks guys! :slight_smile:

Please don't cross-post. Once is enough.

Steve

You probably just need an if statement.

if (cm > 1 && cm < 10) servo.write(90);
else servo.write(0);

What you do is try to move the servo proportionally to the distance the object is away.