#define echoPin 12 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 13 //attach pin D3 Arduino to pin Trig of HC-SR04
#include <Servo.h>
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
const int servoPin = 9; // Pin kontrol servo motor
Servo myservo;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
Serial.println("with Arduino UNO R3");
myservo.attach(servoPin);
}
void loop() {
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
Serial.println(distance);
if (distance < 17) {
myservo.write(270); // Putar servo ke posisi 0 derajat (arah kanan)
Serial.println("buka pintu");
} else if (distance == 19) {
myservo.write(0); // Putar servo ke posisi 180 derajat (arah kiri)
Serial.println("tutup pintu");
} else {
myservo.write(0); // Putar servo ke posisi 90 derajat (arah tengah)
Serial.println("tutup pintu");
}
}