SunFounder GalaxyRVR Kit for Arduino, Release 1.0
float distance = duration * 0.034 / 2;
• Report the Findings: Our superhero sensor then reveals the result of its mission, printing the distance to the
Serial Monitor for us to see.
// Print the distance to the serial monitor
Serial.print("The distance is: ");
Serial.print(distance);
Serial.println(" cm");
• Rest & Ready: Every superhero needs a rest, so our sensor takes a short pause before the next mission. This
allows the sensor to “reset” before we ask it to start another measurement.
delay(200);
Here’s the complete code that turns our sensor into a superhero:
Step 4: Programming the Ultrasonic Module to Drive the Mars Rover
Now that we’ve equipped our Mars Rover with an ultrasonic sensor module, it’s time to program it to respond based on
the sensor’s measurements.
• For easier reading, we have created a function called readSensorData(). This function encapsulates all the
code required to read the distance from the ultrasonic sensor.
float readSensorData() {
// A 4ms delay is required, otherwise the reading may be 0
delay(4);
//Set to OUTPUT to send signal
pinMode(ULTRASONIC_PIN, OUTPUT);
// Clear the trigger pin
digitalWrite(ULTRASONIC_PIN, LOW);
delayMicroseconds(2);
// Trigger the sensor by sending a high pulse for 10us
digitalWrite(ULTRASONIC_PIN, HIGH);
delayMicroseconds(10);
// Set the trigger pin back to low
digitalWrite(ULTRASONIC_PIN, LOW);
//Set to INPUT to read
pinMode(ULTRASONIC_PIN, INPUT);
// pulseIn returns the duration of the pulse on the pin
float duration = pulseIn(ULTRASONIC_PIN, HIGH);
// Calculate the distance (in cm) based on the speed of sound (340 m/s or 0.034␣
˓→cm/us)
float distance = duration * 0.034 / 2;
return distance;
}
3.7. Lesson 7: Enhancing Rover Navigation with Ultrasonic Module 63