Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
10 years, 4 months ago.
setting the precision of analogin ??
Hello, am trying to set the decimal places of AnalogIn when I read the voltage my code is:
#include "mbed.h" DigitalOut led1(LED1); DigitalOut led2(LED2); AnalogIn pot1(p19); AnalogIn pot2(p20); int main() { float p1,p2,sum,pc1=0.00,pc2=0.00; while(1) { p1=pot1.read()*3.3; p2=pot2.read()*3.3; sum=(p1+p2); if (p1 != pc1){ led1 = 1; pc1=p1;} else {led1=0;} if (p2 != pc2) {led2 = 1; pc2=p2;} else {led2=0;} wait(0.1); } }
the problem is that float have a large decimal places, and in if-statement, it compares unnecessary decimals. Is there a way to limit the reading "pot1.read()" or "float" to 2 or 3 decimal places ??
2 Answers
10 years, 4 months ago.
Hello Mohammed Almoosawi,
is rounding the answer you are looking for? http://en.wikipedia.org/wiki/Rounding The math header file contains functions for rounding as floorf or ceil, depending on your goal (rounded up/down?)
float number; number = 4.6678; number = floor(number * 100) / 100; // number = 4.66
Regards,
0xc0170
10 years, 4 months ago.
Martins answer is the correct answer to what you asked however looking at your previous question I'm not sure if it's exactly what you want to do.
I think that what you want to do is detect when the input has increased by a meaningful amount rather than just increased a tiny amount due to random noise. If all you do is round to 2 decimal places then you will still count a change from 1.99499 to 1.995000 as change since the rounded number will go from 1.99 to 2.0.
What you may want to do is to check if the new value is over a certain amount different from the old one. e.g. something like this
// threshold to detect changes. You may need to try different values. #define threshold 0.05 int main() { float p1,p2,sum,pc1=0.00,pc2=0.00; while(1) { p1=pot1.read()*3.3; p2=pot2.read()*3.3; sum=(p1+p2); // if new value is more than old plus threshold or less than old minus threshold if ( (p1 >= (pc1+threshold) || (p1 <= (pc1 - threshold)) ) { led1 = 1; pc1=p1; } else { led1=0; } if ( (p2 >= (pc2+threshold) || (p2 <= (pc2 - threshold)) ) { led2 = 1; pc2=p2; } else { led2=0; } wait(0.1); } }
There will be a certain amount of trial an error in setting the threshold at a reasonable level. Too low and you'll get false triggers, too high and you may not see small changes.