Strange behavior when compiler converts from float to double

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?


  • 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]; ?

    链接地址: http://www.djcxy.com/p/13786.html

    上一篇: C ++中'struct'和'typedef struct'的区别?

    下一篇: 编译器从float转换为double时的奇怪行为