#define ECHO_PIN 2
#define TRIG_PIN 3
#include <Servo.h>
Servo myservo;
int potpin = 0;
int val;
float readDistanceCM() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
Serial.begin(115200);
myservo.attach(9);
}
void loop() {
int duration = pulseIn(ECHO_PIN, HIGH);
float distance = readDistanceCM();
Serial.print("Jarak: ");
Serial.println(readDistanceCM());
if(distance <= 10){
myservo.write(90);
delay(15);
}
else{
myservo.write(0);
}
}