我正在为NXP MCU板开发代码。我必须使用C编程语言。
我的目标:使用超声波传感器测量距离。预定义距离= 180厘米。输出应为剩余距离(以百分比表示)。例如:如果传感器测得的距离为100cm,则计算后的输出应为:44.44%如果测得的距离为180+,则计算后的输出应为负百分比。
问题:我开发了以下代码。在执行代码中的数学运算(数字处理)之前,传感器按预期提供以cm为单位的输出,这在TeraTerm上可以观察到。但是,当我在代码中添加了几行与数学相关的行时,输出现在为空白。传感器工作正常,但是将公式添加到代码中后,我无法获得计算出的输出。以下是我的代码:
#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 );
}
}
输出: 输出截图
能否请您检查一下,并让我知道int distance
此处计算从传感器获得的值是否有问题?我对C编程语言不是很熟悉。因此,感谢您提供的任何帮助。感谢您的时间和协助。
多亏了Dmitri,更改以下printf
行才有效:
printf("\n\rPercent remaining: %f\n", dist_percent);
还要感谢FredK和Yunnosch。感谢您的帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句