/*This code is to measure distance using two HC-04 sensors that are mounted haorizontally and vertically in a breadboard. The time is measured after giving a pulse from the trigger pin and time is measured in ms to the echo pin. This time and speed of sound (340m/s at 20 degree celsius) is used to then calculate the distance to the target in front. We print this output in serial monitor as the distance. In the first iteration, we use one sensor just the calculate distance to target in front and in the second iteration, we add two sensors to calculate vertical distance as well. */ const int trigPin = 2; const int echoPin = 4; void setup() { // initialize serial communication: Serial.begin(9600); } void loop() { // establish variables for duration of the ping, // and the distance result in inches and centimeters: long duration, cm; // The sensor is triggered by a HIGH pulse of 10 or more microseconds. // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: pinMode(trigPin, OUTPUT); digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Read the signal from the sensor: a HIGH pulse whose // duration is the time (in microseconds) from the sending // of the ping to the reception of its echo off of an object. pinMode(echoPin, INPUT); duration = pulseIn(echoPin, HIGH); // convert the time into a distance cm = microsecondsToCentimeters(duration); Serial.print("Horizontal"); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100); } long microsecondsToCentimeters(long microseconds) { // The speed of sound is 340 m/s or 29 microseconds per centimeter. // The ping travels out and back, so to find the distance of the // object we take half of the distance travelled. return microseconds / 29 / 2; }