in this project I want to read out the distance from an ultrasonic sensor and calculate the distance in percentage, but somehow the result is always 0. Do you know why this could happen or do you find any other mistakes? Please let me know.
You are doing integer division here. so if the numerator is less than the calibration value, you will always get 0. Maybe cast to a float? or calculate a number from 0-100 rather than 0.0-1.0
int mapDistance() {
int percentage = calculateDistance() / calibrateSensor_high() ;
return percentage;
}
You declare "percentage" inside the function.
Then;
void loop() {
Serial.println(mapDistance());
}
You try to print it outside the function.
It would be easier for you to declare ALL the return values from your functions as GLOBAL, don't worry about returning the values.
Then use those variables as the print variable.
You would at this stage be worth calling ALL your functions in the void loop(), and serial print their values, to check your functionality.
That is not accurate. The println() function just prints the return value of mapDistance() which is perfectly fine. The variable percentage does go out of scope when the function exits, but its value is correctly used as the return value which then gets passed to println().
I think I should specify what my project is. I“m using the ultrasonic sensor in a trash can. There the bottom should be calibrated to 0 with this function:
And the maximum level which the trash is allowed to arrive is this function:
int calibrateSensor_high() {
if (digitalRead(cal_highPin) == true) {
int calibrate_high = calculateDistance();
return calibrate_high;
}
}
Between these two values I want to read out the trash level and serial print it in percentage where the bottom is 0 and the top is 100. Do you understand my idea?
I suspect your 'calibrate' inputs are reading HIGH all of the time so min and max are getting reset to 'distance' each time. How do you have them wired? How do you use them to 'calibrate' the two distances?
The way I use them is that I install the sensor and don“t move it anymore. Then I calibrate the way to the ground with "calibrateSensor_low()". After that I hold my hand two centimeters below the sensor and calibrate it with "calibrateSensor_high()". Is this enough information or do you need any other?
That's what I feared. Calibrate_low is the highest distance value and Calibrate_high is the lowest distance value. Let's try again, calling them Full and Empty instead of High and Low:
Wow! Thank you John for your help.
Now everything is working fine. But can you explain me why you gave "CalibrateFull" and "CalibrateEmpty" a value? Is it possible to declare it with zero?
unsigned CalibrateFull = 2; // cm
unsigned CalibrateEmpty = 60; // cm
You can, but then the sketch won't work right on power-up until you go through both calibration steps. If you change the '2' and '60' to your calibration values then the sketch will work as soon as you turn on power.