HC-SR04 Specific Distance Measurements

Hi everybody.

I have my HC-SR04 sensor set up and it is outputting distances in terms of integers, such as 1 cm, 2 cm, and so on.

Is it possible to program the sensor to output distances such as 4.3 cm, 5.7cm, and the like?

Thank you.

What is the type of the variable where you’re saving the values from the sensor?

Maybe you’ve defined it as integer. Could you post the code?

Hello! I am very new to the program.

Here is my code:

// ---------------------------------------------------------------------------
// Example NewPing library sketch that does a ping about 20 times per second.
// ---------------------------------------------------------------------------

#include <NewPing.h>

#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
}

void loop() {
delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
Serial.print("Ping: ");
Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
Serial.println(“cm”);
}

rakis: What is the type of the variable where you're saving the values from the sensor?

Maybe you've defined it as integer.

He has (unsigned in fact).

But more importantly, that's exactly what the ping_cm method in NewPing.cpp returns anyway. So a change would presumably involve a change to the method in the library.

I imagine they did that for a reason: I'm inclined to think that decimals of cm is beyond the intrinsic ability of the sensor?

edit.... says here that the accuracy "can" be as good as 3mm. Implication is, that's not guaranteed. And even if it was guaranteed, that's 0.3cm so forcing output to 0.1 is going beyond the device's capability.

JimboZA: He has (unsigned in fact).

But more importantly, that's exactly what the ping_cm method in NewPing.cpp returns anyway. So a change would presumably involve a change to the method in the library.

I imagine they did that for a reason: I'm inclined to think that decimals of cm is beyond the intrinsic ability of the sensor?

As you said, in NewPing.cpp the function returns an unsigned integer.

unsigned int NewPing::convert_cm(unsigned int echoTime) { return NewPingConvert(echoTime, US_ROUNDTRIP_CM); // Convert uS to centimeters.