#define TRIG_PIN 12  // Trigger pin
#define ECHO_PIN 13  // Echo pin


void setup() {
  Serial.begin(9600);         // Initialize serial communication
  pinMode(TRIG_PIN, OUTPUT);  // Set the trigger pin as an output
  pinMode(ECHO_PIN, INPUT);   // Set the echo pin as an input
}

void loop() {
  float distance = measureDistance();
  // Print the average distance to the Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(1000);  // Delay before taking another set of measurements
}

float measureDistance() {
  long duration;
  float distance;
  // Clear the trigger pin
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);

  // Send a 10µs pulse to trigger the sensor
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Measure the time of the echo pulse
  duration = pulseIn(ECHO_PIN, HIGH);

  // Calculate the distance (speed of sound is 34300 cm/s)
  distance = (duration * 0.0343) / 2;
  return distance;
}
Loading
st-nucleo-c031c6