I want to make a gate using 360 servo and ultrasonic sensor, here I use if else. when ultrasonic conditions >= 10 cm the servo should rotate one time to the right for 5 seconds, and vice versa. but when it reaches the condition >= 10 cm where the servo continues to rotate without stopping, how to make it stop in 1 rotation? and also i need distance data from ultrasonic sensor to display. I'm a beginner in this, I will be very grateful for the help.
this is my code :
#include <Wire.h>
#include <Servo.h> //Servo library
#define echoPin 3 //triger pin, echo pin
#define triggerPin 4
int waktu;
int jarak;
int hasiljarak;
Servo servo;
void setup()
{
Serial.begin(9600);
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop()
{
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
waktu = pulseIn(echoPin, HIGH);
jarak = waktu * 0.034 / 2;
Serial.print(jarak);
Serial.print(" CM");
delay(100);
servo.attach(9);
if(jarak<=10)
{
servo.write(2000);
delay(5000);
}
else if(jarak>=30)
{
servo.write(1000);
delay(5000);
}
else
{
servo.write(1500);
delay(1000);
}
servo.detach();
}