// Ultrasonic sensor
/*
Working principle
i. The ultrasound transmitter (trig pin) emits a high-frequency sound (40 kHz).
ii. The sound travels through the air. If it finds an object, it bounces back to the module.
iii. The ultrasound receiver (echo pin) receives the reflected sound (echo).
iv. distance to an object = ((speed of sound in the air)*time)/2

Pin connection
trig - GPIO5
echo - GPIO18
*/
const int trigPin = 5;
const int echoPin = 18;

#define SOUND_SPEED 0.034 // sound speed in cm/us
#define CM_TO_INCH 0.393701

long duration;
float distanceCM;
float distanceInch;

void setup() {
  // put your setup code here, to run once:
  pinMode (echoPin, INPUT);
  pinMode (trigPin, OUTPUT);
  Serial.begin (115200);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite (trigPin, LOW);
  delayMicroseconds (2);
  digitalWrite (trigPin, HIGH);
  delayMicroseconds (10);
  digitalWrite (trigPin, LOW);
  
  duration = pulseIn (echoPin, HIGH); // measure duration from HIGH to LOW
  distanceCM = (duration * SOUND_SPEED)/2;
  distanceInch = distanceCM * CM_TO_INCH;

  Serial.print ("Distance(cm): ");
  Serial.println (distanceCM);
  Serial.print ("Distance(inch): ");
  Serial.println (distanceInch);
  delay (1000);
}