Search code examples
32-bit16-bitfloating-point-conversioncodesysstructured-text

Converting 32-Bit Real to 2x 16-Bit Bytes


I'm trying to send a 32-Bit Real across a CAN communications (IFM) but the CAN comms only accepts a 16-Bit value.

If the value I'm trying to send goes above 255, it resets back to 0 and continues in that pattern. I therefore need to split the 32-Bit Real value in to two 16-Bit values and then reassemble on the other side of the comms.

I just can't seem to get my head around how to do it in structured text.

Any help would be appreciated


Solution

  • I know I am a little late to the party but wanted to add this as a solution.

    VAR
      rRealVar  :   REAL;
      awWordArray   :   ARRAY[0..1] OF WORD;
      pTemp     :   POINTER TO REAL;
      pTemp2        :   POINTER TO REAL;
    END_VAR
    
    // Get a pointer to the REAL variable
    pTemp := ADR(rRealVar);
    
    // Get a pointer to the ARRAY base
    pTemp2 := ADR(awWordArray);
    
    // Assign the value of the REAL variable into the ARRAY base
    pTemp2^ := pTemp^;
    
    (* Index 0 := Bits 15-0
       Index 1 := Bits 31-16
    

    This is similar to Felix Keil's answer but it makes use of 2 pointer variables and a word array to retrieve the information directly.