Problem with ultrasonic sensor code

Hey I'm having problems with my code when trying to format the distance reading from my sensor as a float. Please excuse my probably stupid question I'm quite new but why won't it work. I've managed to get the inches value as a float but I don't know how I did.


  • Date: 13/04/2020
  • Aim: To use Ultrasonic sensor to measure the distance between objects. Intergrate physics and maths as the speed of sound is required
    • 343m/s. It requires a pulse for atleast 2microseconds to generate a signal which is read by the Tx. The equation S = D/T is used to calculate
  • the distance.

//Declare the variables to send/receive signal
#define OUT 10
#define IN 13

//Declare the variables to calculate the distance
long Duration;
float DistanceCM;

void setup()
// put your setup code here, to run once:
//Initialise serial communications

//Declare the pins as outputsd and inputs
pinMode(OUT, OUTPUT);
pinMode(IN, INPUT);


void loop()
// put your main code here, to run repeatedly:
//Send out a signal by providing a volatge for at least 2 microseconds
digitalWrite(OUT, LOW);

digitalWrite(OUT, HIGH);

digitalWrite(OUT, LOW);

//Use the pulse in function to get the time in ms whilst Pulse is High
Duration = pulseIn(IN, HIGH);

//Call function to calculate the distance in cm
DistanceCM = CalcDistanceCm(Duration);

//Print the values to the console - make sure it is within range of 2 - 400cm
if(DistanceCM > 400 || DistanceCM < 2)
//Print error
Serial.println("Out of Range");
Serial.print("The object is: ");
Serial.print("cm or ");
Serial.print(DistanceCM/2.54);//divide for inches
Serial.println("In away.");

}//end main

long CalcDistanceCm(long Duration)
//Calculate the distance by D = S x T
DistanceCM = 0.0343 * (Duration/2.0);//Remember the time is double as it goes out then comes back

//Calibrate by adding 1cm
DistanceCM = DistanceCM + 1.0;

//return the value
return (DistanceCM);

}//end function to return the value in cm

Here, have these [code][/code]

but why won't it work. I've managed to get the inches value as a float but I don't know how I did.

I have no idea what that is supposed to mean.

You forgot to say exactly what the problem is. But maybe it's related to the fact that you first declare DistanceCM as a float but then you populate it with a long returned from CalcDistanceCm(). Long is an integer type.