Specifications

M1 Control RS-232 ASCII String Protocol Page 67 of 68 Rev. 1.79 July 16, 2009
9. Calculate Checksum
Calculate checksum on received and transmitted ASCII string
Example C code program
//INT8U is an 8 bit unsigned integer.
INT8U itAscRecBuf[82]; //ASCII receive
character buffer
INT8U AscHexToBin(INT8U, INT8U *); //ASCII hex to binary
conversion
INT8U AsciiToHex( INT8U); //Ascii to Hex conversion
//Calculate checksum on a received ASCII string, return checksum
value. //It should equal 0 if good.
INT8U CalcCheckSum(void)
{
INT8U i,length, cc;
length = AscHexToBin(2, &itAscRecBuf[0]);
//get length value,
//first two characters
cc = AscHexToBin(2, &itAscRecBuf[length]); //get
checksum value
//at end of string.
for (i=0;i<length ;i++ )
{
cc += itAscRecBuf[i]; //get string value and
add it to
//checksum
}
return(cc); //good checksum should equal 0
}
//ascii hex to binary, width 1 or 2
INT8U AscHexToBin(INT8U Width, INT8U * DataPtr) //
{
INT8U aVal; // accumulated value
aVal = AsciiToHex(*DataPtr);
DataPtr++;
if (Width ==
2)//tw
o digits wide, else 1 digit wide
{
aVal = aVal << 4;
aVal += AsciiToHex(*DataPtr);
}
return(aVal);
}
//Ascii to Hex conversion
INT8U AsciiToHex( INT8U Value )
{
switch ( Value )
{
case 'A':
return( 10 );
case 'B':
return( 11 );
case 'C':
return( 12 );
case 'D':
return( 13 );
case 'E':
return( 14 );
case 'F':
return( 15 );
default:
return( Value - 0x30 );
}
}
/*
*******************************************************
*******
To generate the checksum for an ASCII string to be transmitted,
clear the checksum value (CC = 0;)
Add each byte of the string to be transmitted to the checksum value
(CC += ASCII byte).
Do a two’s compliment of the checksum (CC = (CC ^
0xff) + 1;)
.
Convert the checksum’s upper and lower nibble’s to ASCII hex.
Send a carriage return (0x0D) and line feed (0x0A).
The following is an example C code for sending the checksum after
building the initial checksum value.
*/
//send checksum + carriage return, line feed
//Comm2_Put_Ch() sends the byte out the serial data port.
INT8U NibToAsc(INT8U);
void SendChecksum(INT8U CC) //enter with checksum value
added up
{
CC = (CC ^ 0xFF) + 1; //calculate two's compliment
Comm2_Put_Ch(NibToAsc(CC >> 4));
Comm2_Put_Ch(NibToAsc(CC & 0x0F));
Comm2_Put_Ch(0x0D);
Comm2_Put_Ch(0x0A);
}
INT8U NibToAsc(INT8U Nib)
{
if (Nib < 0x0A)
return( (INT8U)(Nib + 0x30));
else if (Nib <= 0x0F)
return(Nib + 0x37); //converts to 0x0A ->
0x0F hex value
return(0x20); //error
}