Function Arduino-等待函数会导致数字堆积
我有一个函数Function Arduino-等待函数会导致数字堆积,function,floating-point,arduino,return,Function,Floating Point,Arduino,Return,我有一个函数filledFunction(),它返回一个floatfilled: float filledFunction(){ if (FreqMeasure.available()) { sum = sum + FreqMeasure.read(); count = count + 1; if (count > 30) { frequency = FreqMeasure.countToFrequency(s
filledFunction()
,它返回一个floatfilled
:
float filledFunction(){
if (FreqMeasure.available()) {
sum = sum + FreqMeasure.read();
count = count + 1;
if (count > 30) {
frequency = FreqMeasure.countToFrequency(sum / count);
a = frequency * x;
b = exp (a);
c = w * b;
d = frequency * z;
e = exp (d);
f = y * e;
float filled = c + f;
sum = 0;
count = 0;
return filled;
}
}
}
当我用
while (1){
fillLevel = filledFunction();
int tofill = 500 - fillLevel;
Serial.print("fillLevel: ");
Serial.println(fillLevel);
Serial.print("tofill: ");
Serial.println(tofill);
串行监视器应输出两个总计500的数字,分别命名为fillLevel
和tofill
。相反,我得到了类似值的重复序列:
前两个值是正确的(410.93+89=500),但以下60ish值我不知道,不属于这里
我使用的是arduino nano函数filledFunction()
仅在frequemeasure.available()
返回true
和count>30时返回值。正如对C89、C99和C11标准的回答中所述,所有这些标准都表示函数的默认返回值未定义(即如果函数在未执行返回
语句的情况下完成)。这意味着任何事情都有可能发生,比如输出任意数字
此外,您看到的输出以从500
中减去其中一个数字开始“正确”,即使它们的值很奇怪,例如11699.00
和-11199
(等于500-11699.00
)。然而,在输出的下方,这似乎出现了故障,原因是在Arduino Nano上,int
只能容纳小于等于32767的数字,因此减法的结果太大,“溢出”不会是一个大的负数
修复filledFunction()
函数以显式返回值,即使FreqMeasure.available()
为false
或count,我将粘贴一条else语句以查看是否解决了此问题。我确实注意到这些值达到了数据类型的限制,我只是不知道这个值是什么,或者为什么它变化这么大。。。无论如何,谢谢你。