//BY IRFXN.ISMAIL-ADAM IZZAT-ZAFRAN
#include <Servo.h>
#define TRIG_PIN 3 // The Arduino Nano pin connected to the TRIG pin of the HC-SR04
#define ECHO_PIN 2 // The Arduino Nano pin connected to the ECHO pin of the HC-SR04
#define SERVO_PIN 9
float duration_us, distance_cm;
Servo servo;
void setup() {
// Begin serial communication
Serial.begin(9600);
// Configure the trigger pin as an output
pinMode(TRIG_PIN, OUTPUT);
// Configure the echo pin as an input
pinMode(ECHO_PIN, INPUT);
servo.attach(SERVO_PIN);
}
void loop() {
// Produce a 10-microsecond pulse to the TRIG pin
digitalWrite(TRIG_PIN, LOW); // Set the TRIG pin low for a short time to ensure a clean pulse
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH); // Set the TRIG pin high for 10 microseconds to generate a pulse
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW); // Set the TRIG pin low again
duration_us = pulseIn(ECHO_PIN, HIGH);
distance_cm = 0.01715 * duration_us;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
if(distance_cm < 20)
{
servo.write(45);
}
else {
servo.write(180);
}
delay(100); // Delay 500 milliseconds before the next measurement
}