1

I have a function filledFunction() that returns a float filled:

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;
        }
    }
}

When I call this function with

while (1){
    fillLevel = filledFunction();
    int tofill = 500 - fillLevel;
    Serial.print("fillLevel:    ");
    Serial.println(fillLevel);
    Serial.print("tofill:       ");
    Serial.println(tofill);

The serial monitor should output two numbers that add up to 500 named fillLevel and tofill. Instead I get a repeating sequence of similar values:

https://i.stack.imgur.com/KxIoH.png

The First two values are correct (410.93 + 89 = 500), but the following 60ish values are unknown to me, and do not belong there.

I am using an arduino nano

1 Answers1

0

The filledFunction() function only returns a value if FreqMeasure.available() returns true AND count > 30. As stated in the answers to this question the C89, C99 and C11 standards all say that the default return value of a function is undefined (that is if the function completes without executing a return statement). Which really means that anything could happen, such as outputting arbitrary numbers.

In addition, the output that you're seeing starts off 'correct' with one of the numbers subtracted from 500, even when they have weird values such as 11699.00 and -11199 (which equals 500 - 11699.00). However, lower down in the output this seems to break down and the reason is that on Arduino Nano an int can only hold numbers up to 32767 and therefore the result of the subtraction is too big and 'overflows' to be a large negative number.

Fixing the filledFunction() function to explicitly return a value even if FreqMeasure.available() is false or count <= 30 and ensuring that it can't return a number greater than 500 will likely solve these issues.

Community
  • 1
  • 1
Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
  • I see, I'll stick an else statement to see if that solves it. And I did notice the the values reaching the data types limit, I just don't know what the value is or why it is changing as much as it is... Thanks anyway. – Pierre Taylor Apr 02 '15 at 23:31