#include #define RX 0 #define TX 1 SoftwareSerial serial(RX, TX); #define echoPin 17 #define trigPin 16 // defines variables long duration; int distance; void setup() { pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT serial.begin(9600); serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor } void loop() { // Clears the trigPin condition digitalWrite(trigPin, LOW); delay(1000); // Sets the trigPin HIGH (ACTIVE) for 10 microseconds digitalWrite(trigPin, HIGH); delay(1000); 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.print("Distance: "); serial.print(distance); serial.println(" cm"); }