//CRC 16 for modbus checksum
unsigned int CRC16(unsigned int dataLength,char check)
{
// trame 01 03 00 0A 00 01 A4 08 envoi avec check=0
// trame 01 03 02 02 03 F9 25 reception avec check=1
unsigned int CheckSum;
unsigned int i,j;
CheckSum = 0xffff;
for (j=0; j<dataLength; j++)
{
CheckSum = CheckSum^(unsigned int)buffer[j];
for(i=8;i>0;i--)
{
if(CheckSum & 1)
CheckSum = (CheckSum>>1)^0xa001;
else
CheckSum>>= 1;
}
}
// attention rangement Checksum inversé
CRC16_Value=CheckSum ; // for checking purpose
CRC16_H = CheckSum>>8;
CRC16_L = CheckSum & 0x00FF;
if (check==1)
{
if ( (buffer[dataLength] == CRC16_L) && (buffer[dataLength+1] ==CRC16_H ))
return CheckSum;
else
return 0;
}
else
{
buffer[dataLength] = CRC16_L;
buffer[dataLength+1] = CRC16_H;
return CheckSum;
}
}