#include <Servo.h>
// Constants won't change
const int TRIG_PIN = D2; // Arduino pin connected to Ultrasonic Sensor's TRIG pin
const int ECHO_PIN = D1; // Arduino pin connected to Ultrasonic Sensor's ECHO pin
const int SERVO_PIN = D13; // Arduino pin connected to Servo Motor's pin
const int DISTANCE_THRESHOLD = 50; // centimeters
Servo servo; // Create servo object to control a servo
float duration_us, distance_cm; // Variables will change
void setup() {
Serial.begin(9600); // Initialize serial port
pinMode(TRIG_PIN, OUTPUT); // Set Arduino pin to output mode
pinMode(ECHO_PIN, INPUT); // Set Arduino pin to input mode
servo.attach(SERVO_PIN); // Attach the servo on pin D13 to the servo object
servo.write(0); // Initialize servo position to 0 degrees (closed)
}
void loop() {
// Generate 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure duration of pulse from ECHO pin
duration_us = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance
distance_cm = 0.017 * duration_us;
if (distance_cm < DISTANCE_THRESHOLD) {
// Rotate servo motor to 90 degrees (open)
servo.write(90);
} else {
// Rotate servo motor to 0 degrees (closed)
servo.write(0);
}
// Print the value to Serial Monitor
Serial.print("Distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
delay(500);
}