PeterSK
September 25, 2023, 3:47pm
1
I am trying to read the current with acs712. And when I get close to zero then sometimes I get negative values. Why is that ?
#define AnPin 7
float vall;
float current, vallRMS, vallLowPass;
void setup() {
pinMode(7, INPUT);
Serial.begin(115200);
}
void loop() {
for ( int i = 0; i < 10; i ++) {
vall += sq((float)(analogRead(AnPin) - 507) * 0.004887586);
}
vallRMS = sqrt(vall * 0.1) ;
vallLowPass = vallLowPass * 0.95 + vallRMS * 0.05;
current = vallLowPass * 10 - 0.0288;
if ( current < 0.0 ) { current = 0; }
/* vall = analogRead(AnPin);
vallRMS = vall * 5 / 1023.0;
current = (vallRMS - 2.4877)*5.405405405;*/
Serial.print("vall:");
Serial.print (vall,12);
Serial.print("\t");
Serial.print ("current:");
Serial.println(current, 4 );
vallRMS = 0;
vall = 0;
current = 0;
}
Here an example of the values. Prud is current. :
|vall:0.000071665496|prud:nan|
|vall:0.000023888497|prud:nan|
|vall:0.000071665496|prud:nan|
|vall:0.000023888497|prud:nan|
|vall:0.000047776994|prud:nan|
|vall:0.000071665496|prud:nan|
|vall:0.000023888497|prud:nan|
|vall:0.000000000000|prud:nan|
|vall:0.000000000000|prud:nan|
|vall:0.000023888497|prud:nan|
|vall:0.000119442486|prud:nan|
|vall:0.000000000000|prud:nan|
|vall:-0.000047776994|prud:nan|
|vall:0.000047776994|prud:nan|
|vall:0.000071665496|prud:nan|
|vall:0.000071665496|prud:nan|
Please post code that will compile without errors and demonstrates the problem.
"prud" is not declared or defined in the posted code.
Also, from the sq() reference page , "Because of the way the sq()
function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results."
2 Likes
kolaha
September 25, 2023, 4:17pm
4
#define AnPin 7
void setup() {
Serial.begin(115200);
}
void loop() {
int16_t vall = 0;
static float current = 0;
for ( int i = 0; i < 10; i ++) {
vall += analogRead(AnPin));
delay(1);
}
vall = abs(vall-5120);
current = vall / 255.75;
Serial.print("vall:");
Serial.print (vall);
Serial.print("\t");
Serial.print ("current A:");
Serial.println(current, 3 );
}
PeterSK
September 25, 2023, 4:21pm
5
Just replace prud with current. I wanted to replace the prud with current so it makes more sense and I forget to do it in some places.
Please fix the code as requested, and as pointed out above, DO NOT use sq() with functions like analogRead(). Use the multiplication operator instead.
1 Like
Your assignment of vallLowPass depends on the previous value of vallLowPass. But the first time through loop(), vallLowPass doesn't have an assigned value. That's bad.
vallLowPass is global and is initialized to zero at program startup.
However, it is always best not to rely on such behavior and explicitly initialize all variables.
Printing ALL of (vall, vallRMS, vallLowPas, and current) might get you closer to understanding what's happening.
system
Closed
March 23, 2024, 7:58pm
11
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.