Lightsout
Lightsout

Reputation: 3757

Arduino double subtraction returning 0 erronously

I have a function that takes as parameter some double and does a subtraction operation on it. However I'm getting a result of 0 when one of the parameter is 0 for some reason.

int calcPID(double current, double desired, double k){

  double diff;

  diff = desired - current;

  Serial.print("desired = ");
  Serial.print(desired);
  Serial.print(" ,current = ");
  Serial.print(current);
  Serial.print(",diff = ");
  Serial.println(diff);

  int r = (int)diff;
  return r;
}

output

desired = 250.00 ,current = 1.69,diff = 248.31
desired = 250.00 ,current = 0.00,diff = 0.00

When the current is 0.00 the result(diff) is also 0.00 when it should be 250. Can someone tell me what's going on?

edit:

found out that I was getting a garbage value for current somehow that's not a double (I wrote 2 if conditions if current > 1 and if current <= 1 and neither of them were true).

Upvotes: 2

Views: 279

Answers (2)

Danny_ds
Danny_ds

Reputation: 11406

This is very strange indeed.

I would suggest to create a second, minimal function like this:

int calcPID2(double current, double desired){

    Serial.println(desired - current);

    return(1);
}

and then gradually changing it to your original version, and see where it goes wrong (if it goes wrong..).

I have had some strange things with the Arduino software too in the past. Maybe you should check if you have the latest version.

You might also want to check if there is no memory or stack problem (i.e. if you have enough free memory left).

Upvotes: 1

Cihan Kurt
Cihan Kurt

Reputation: 373

I think it's something with the floating point calculation. Have a look at this: https://www.arduino.cc/en/Reference/Float or google it and you will find pretty good answers :)

Upvotes: 0

Related Questions