#define TRIG_PIN 12 // Trigger pin
#define ECHO_PIN 13 // Echo pin
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
// Send a 10-microsecond pulse to trigger pin
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the duration of the echo pulse
long duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance (in cm)
float distance = duration * 0.034 / 2;
// Print the distance
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if an object (can) is detected
if (distance < 5) { // Adjust threshold as needed
Serial.println("Can detected!");
} else {
Serial.println("No can detected.");
}
delay(1000); // Wait for 1 second before the next reading
}