const int myLedPin = LED_BUILTIN;
const int myTriggerPin = 1; // D1
const int myEchoPin = 2; // D2
long myDuration;
float myDistanceCm;
void setup() {
Serial.begin(115200);
pinMode(myLedPin, OUTPUT);
pinMode(myTriggerPin, OUTPUT);
pinMode(myEchoPin, INPUT);
}
void loop() {
// Simple blink to show the loop is running
digitalWrite(myLedPin, LOW); // XIAO LEDs are usually active low
// Clear the trigger pin
digitalWrite(myTriggerPin, LOW);
delayMicroseconds(2);
// Send a 10 microsecond pulse
digitalWrite(myTriggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(myTriggerPin, LOW);
// Read the echo pulse duration in microseconds
myDuration = pulseIn(myEchoPin, HIGH);
// Calculate distance: (speed of sound is 0.034 cm/us)
myDistanceCm = myDuration * 0.034 / 2;
// Print results
Serial.print("Distance: ");
Serial.print(myDistanceCm);
Serial.println(" cm");
digitalWrite(myLedPin, HIGH);
delay(500);
}Loading
xiao-esp32-s3
xiao-esp32-s3
1kΩ (To Echo)
2kΩ (To GND)