#include <Servo.h>
#define ECHO_PIN 4
#define TRIG_PIN 5
int servoPin = 3;
Servo servo;
int angle = 0; // servo position in degrees
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
Serial.begin(9600);
servo.write(LOW);
servo.attach(servoPin);
}
void loop() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
float distance = duration * 0.034 / 2;
int y = (2E-06*distance*distance) + (1.0051*distance) + 0.0575;
Serial.print("Jarak: ");
Serial.println(y);
delay(100);
if(y < 20 ){
servo.write(90);
delay(15);
}
else{
servo.write(0);
}
}