So you're a Noob? Post your questions here until you graduate! Don't be shy.

User avatar
By JarlTetrazepam
#93390 Hi folks. I was attempting to build a sound level meter and ran into an issue that I was unable to resolve through googling so far. The rest of the projects code don't matter too much, as the problem appears even when I enter fixed values. Therefore I'm going to skip the setup stuff for the OLED display and other things:
Code: Select alllong levelDb = 0;

levelDb = 20 * log(30 / 220) + 60

display.print("Decibel: ");
display.println(levelDb);


Expected result: 20
Returned result: -2147483648

I assume this is some sort of overflow but I don't quite understand why it would happen, since levelDb is a long. This keeps happening with all values for 30, until the calculation inside the logarithm is >=1, after which it returns the desired results. Could somebody explain to me why this happens and if you're feeling generous, how to fix it?

Many thanks in advance!
User avatar
By btidey
#93392 I think your problem is with log (30/220).

The 30/220 will be calculated using integer arithmetic and will be rounded to 0. log(0) is not a valid expression.

You need to ensure that the division in the log is done with floating point arithmetic. I think if you did 30.0/220.0 that should work. However, that is dependent on how the compiler pre-processes arithmetic expressions. Safer would be to have the numerator and divisor as floating point variables so the calculation is done at run time, or if these are truly fixed numbers then calculate the result yourself log(0.1363634)