#include <Servo.h>
#define button 2
#define echoPin 12
#define trigPin 13
Servo myServo;
int statusPortal;
void setup() {
// put your setup code here, to run once:
pinMode(button, INPUT);
pinMode(echoPin, INPUT);
pinMode(trigPin, OUTPUT);
myServo.attach(3);
}
float readUltrasonic() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(2);
digitalWrite(trigPin, LOW);
int durasi = pulseIn(echoPin, HIGH);
return durasi * 0.017;
}
void loop() {
// put your main code here, to run repeatedly:
float jarak = readUltrasonic();
int statusTombol = digitalRead(button);
if(statusPortal == 0 && statusTombol == HIGH){
myServo.write(0);
statusPortal ++;
} else if(statusPortal == 1 && jarak < 100){
myServo.write(0);
statusPortal ++;
} else if(statusPortal == 2 && jarak > 100){
myServo.write(90);
statusPortal = 0;
}
}