4.5 1 1 1 1 1 1 1 1 1 1 Rating 4.50 (12 Votes)

User Rating: 5 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Active
 

Recently I've been involved into a PLC development environment not equipped to physical memory storage area such as Merker, DB, %T,... In that project, I had to acquire a 32 bit single precision floating point variable from remote I/O located not directly as REAL but as 2 WORDS: respectively  LSW ( Least Significant Word) and MSW (Most Significant Word). Then, starting from the floating definition (Wikipedia):

 IEEE753 32Single Wiki

     31------------------------MSW-------------------16 + 15----------------------LSW------------------------0

Usually, using someone of most common PLC environment as Simatic or Codesys,.. I solved the job by storing the LSW and MSW coming from remote IO into %M contiguous areas, then defining a REAL variable with offset=LSW. Something like this:

LSW AT %MW0 : WORD;

MSW AT %MW1 : WORD;

VarFLOAT AT %MD0 : REAL;

But I had not %M!! so..starting from the following expression:

 

Value[float]= (-1)^sign * 2^(Exponent-127) * 1.fraction

 

I translate that into Codesys v.3.5 SP4 Patch 2 as:

 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

FUNCTION WordsToFloat : REAL
VAR_INPUT
    LSW: WORD;
    MSW:WORD;
END_VAR
VAR
Sign:DINT;
Exponent:DINT;
Fraction:REAL;
END_VAR

 

Sign:=SHR(MSW,15);
Exponent:=SHR(SHL(MSW,1),8);
Fraction:=ANY_TO_REAL((SHR(SHL(MSW,9),9)*EXPT(2,16))+LSW)/EXPT(2,23);

WordsToFloat:=EXPT(-1,Sign)*EXPT(2,Exponent-127)*(Fraction+1.0);

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

 Here after a small video representing the function job: from one side the "VarFloat" mapped on %MD0 assigned (manually) by "MyValue"; to other side the "VarTest" flag as output of WordToFloat FC:

 

 Here follow I shared the Codesys source code hoping it can be useful for you!

If you have any question, suggestion, request, feel free to contact me

 

 

 

 

 

 

 

 

Attachments:
Download this file (WordsToFloat.7z)WordsToFloat PRJ[ ]30 kB943 Downloads2014-05-06 18:29