Strange behavior when compiler converts from float to double

家住魔仙堡 提交于 2019-12-11 13:43:15

问题


I have an array:

float foo[3];

In the ino file I have to send one of them to the PID as input.

double output;
PID myPID(&input, &output, &target, 1, 0.0, 1.1, DIRECT);
...
void loop(){
  input =foo[2];   
  myPID.Compute();
  Serial.print(output); //output: "nan"
...
}

The PID is as follow:

PID::PID(double* Input, double* Output, double* Setpoint,
        double Kp, double Ki, double Kd, int ControllerDirection)

It compiles but the output of the PID outvalue is nan.

However if I set the input to -1.2 then it works.

void loop(){
      input =foo[2];  
      input = -1.2;
      myPID.Compute();
      Serial.print(output); //output: "1200"
    ...
    }

How can I fix this? The compiler should auto convert double the float. As in Mega 2560. I have also tried: input =double(foo[2]); without any success.


EDIT:

  Serial.print(foo[2]);  //Prints -9.2
  foo[2] = -9.2;         // I manually set foo[2] to -9.2  
  xAngle = foo[2];
  xPID.Compute();        //Computes perfectly.

I have to add that foo is in a custom library. This is so strange. Anyone got a clue about this?


回答1:


  • First of all, all AVR doubles are floats as described here or here. This makes doubles be the same as floats on Arduino Mega 2560. You can verify this by comparing sizeof(double); and sizeof(float); both will return 4.
  • Secondly, if you want to cast one type to another the syntax is (targetType)sourceType, so if you do that sort of a thing, your assignment should look like this

    input =(double)foo[2];
    

or

    input =(double)(foo[2]);

However, this is irrelevant in this case since doubles and floats are identical.

I think most likely the problem comes from the fact that your PID controller does not like whatever value you have in foo[2] given the parameters you set. Have you tried foo[2]=-1.2 before assigning input = foo[2];?



来源:https://stackoverflow.com/questions/15954689/strange-behavior-when-compiler-converts-from-float-to-double

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!