const int TRIG_PIN = 26;
const int ECHO_PIN = 25;
int getDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(5);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
long cm = (duration / 2) * 0.0341; // multiply by 0.0343 or divide by 29.1
//long inches = (duration / 2) * 0.0135; // multiply by 0.0135 or divide by 74
return cm;
}
void setup() {
Serial.begin(115200);
Serial.println("Hello, ESP32!\n");
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
static int oldDistance = -1; // ensures first print
int distance = getDistance();
// if the distance changes more than 1 cm print new distance
if (distance > oldDistance + 1 || distance < oldDistance - 1) {
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm.");
oldDistance = distance;
}
delay(500); // slow the loop a little
}