Search code examples
cmathembeddednxp-microcontroller

Calculating Percentage Remaining in C Program


I am developing code for an NXP MCU board. I have to use the C programming language.

My Goal: To measure distance using an ultrasonic sensor. Pre-defined distance = 180cm. The output should be the distance remaining in percentage. For example: if the distance measured by the sensor is 100cm, then the output after calculation should be: 44.44% If the distance measured is 180+, then the output after calculation should be a negative percentage.

Problem: I developed the following code. Before doing math (number manipulation) in the code, the sensor gave output in cm as intended, which was observed on TeraTerm. But when I added few math-related lines to the code, the output is now blank. The sensor is working fine but after adding formulas to the code, I am not getting the calculated output. Following is my code:

#include "mbed.h"
#include "hcsr04.h"

HCSR04  usensor1(A4,A5);
unsigned int distance;
float dist_remaining;
float dist_percent;

int main()
{
    int a = 180;
    while(1)
    {
        usensor1.start();
        wait_ms(500); 
        distance = usensor1.get_dist_cm();
        dist_remaining = a-distance;
        dist_percent = (dist_remaining/180)*100;
        printf("\n\rPercent remaining: ", dist_percent );
    }
}

Output: Output Screenshot

Can you please check and let me know if there is anything wrong with calculating the int distance obtained from the sensor here? I am not very familiar with the C programming language. Hence, I will appreciate any help that you will provide. Thank you for your time and assistance.


Solution

  • Thanks to Dmitri, changing the following printf line worked:

    printf("\n\rPercent remaining: %f\n", dist_percent);
    

    Thanks to FredK and Yunnosch as well. Appreciate your guy's help.