Wednesday, September 10, 2014

Algotithm to Convert 4 byte Hex to 32 bit float


 I really struggled hard to find out some sorts of algorithm to convert 4 hex bytes to 32 bit float for my requirement on some analysis of MODBUS protocol. I didn't find it and it tok me nearly 2 days to design this. Here is the algorithm..


float ModbusRead(byte id,byte msbAddress,byte lsbAddress,byte msbCrc,byte lsbCrc)
{  
    num=1.00;
    Serial.write(id);
    Serial.write(0x03);
    Serial.write((byte)msbAddress);
    Serial.write((byte)lsbAddress);
    Serial.write((byte)0x00);
    Serial.write(0x02);
    Serial.write(msbCrc);
    Serial.write(lsbCrc);
    delay(1000); 
 
 for(i=0;i<9;i++)
  {  
   if(!Serial.available())
    {
     for (int x=0;x < 9;x++)
      {
       reply[x]=0x00;
      }
     while(Serial.available()){}
     break;
    }
   reply[i]=Serial.read();
  }  
    while(Serial.available()){}  
    if((reply[3] &  0x80)!=0)
  num=num*-1;
    reply[3]=reply[3]<<1;
    if((reply[4] & 0x80)!=0x00)
  reply[3]=reply[3] | 0x01;
  num=num*pow(2,reply[3]-0x7F);
    i=0; 
   delay(1000); 
   return num*calculatemantisa(reply[4],reply[5],reply[6]);
}
float calculatemantisa(byte a,byte b,byte c)
{
  float x=1.0000;
  if((a & 0x40)!=0x00)
      x=x+pow(2,-1);
  if((a & 0x20)!=0x00)
      x=x+pow(2,-2);
  if((a & 0x10)!=0x00)
      x=x+pow(2,-3);
  if((a & 0x8)!=0x00)
      x=x+pow(2,-4);
  if((a & 0x4)!=0x00)
      x=x+pow(2,-5);
  if((a & 0x2)!=0x00)
      x=x+pow(2,-6);
  if((a & 0x1)!=0x00)
      x=x+pow(2,-7);
      
  if((b & 0x80)!=0x00)
      x=x+pow(2,-8);
  if((b & 0x40)!=0x00)
      x=x+pow(2,-9);
  if((b & 0x20)!=0x00)
      x=x+pow(2,-10);
  if((b & 0x10)!=0x00)
      x=x+pow(2,-11);
  if((b & 0x8)!=0x00)
      x=x+pow(2,-12);
  if((b & 0x4)!=0x00)
      x=x+pow(2,-13);
  if((b & 0x2)!=0x00)
      x=x+pow(2,-14);
  if((b & 0x1)!=0x00)
      x=x+pow(2,-15);   
      
  if((c & 0x80)!=0x00)
      x=x+pow(2,-16);
  if((c & 0x40)!=0x00)
      x=x+pow(2,-17);
  if((c & 0x20)!=0x00)
      x=x+pow(2,-18);
  if((c & 0x10)!=0x00)
      x=x+pow(2,-19);
  if((c & 0x8)!=0x00)
      x=x+pow(2,-20);
  if((c & 0x4)!=0x00)
      x=x+pow(2,-21);
  if((c & 0x2)!=0x00)
      x=x+pow(2,-22);
  if((c & 0x1)!=0x00)
      x=x+pow(2,-23);      
      
  return x;
}