How could you measure the width of the object with the ultrasonic sensor?
@bhasakirobotech192615 күн бұрын
// Define the pins connected to the ultrasonic sensor const int trigPin = 9; const int echoPin = 10; // Variables to store the two distance measurements long distance1 = 0; long distance2 = 0; void setup() { Serial.begin(9600); // Start the serial communication pinMode(trigPin, OUTPUT); // Set the trigPin as an output pinMode(echoPin, INPUT); // Set the echoPin as an input } void loop() { // Take the first distance measurement at the first edge of the object Serial.println("Place sensor at the first edge and press any key..."); while (Serial.available() == 0) {} // Wait for user input distance1 = measureDistance(); Serial.print("Distance at first edge: "); Serial.print(distance1); Serial.println(" cm"); // Wait for user to move the sensor to the other edge Serial.println("Move the sensor to the other edge and press any key..."); while (Serial.available() == 0) {} // Wait for user input distance2 = measureDistance(); Serial.print("Distance at second edge: "); Serial.print(distance2); Serial.println(" cm"); // Calculate the width (distance traveled by the sensor) long width = abs(distance2 - distance1); Serial.print("Width of the object: "); Serial.print(width); Serial.println(" cm"); // Add a delay for readability delay(2000); } // Function to measure the distance using the ultrasonic sensor long measureDistance() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Read the echoPin and calculate the distance long duration = pulseIn(echoPin, HIGH); long distance = duration * 0.034 / 2; // Speed of sound is 0.034 cm/us return distance; }