Hello everyone,
I have a function that creates a custom protocol for transmission of data to a serial port.
The function is below:
Code:
void calc()
{
/*cmd array and num integer are global*/
unsigned char checksum = 0;
cmd[0] = 0xAA; //starting byte
cmd[1] = 0x10;
cmd[2] = 4;
cmd[3] = 'G';
cmd[4] = 'P';
cmd[5] = ' ';
cmd[6] = num & 0xFF; //lsb
cmd[7] = (num >> 8) & 0xFF; //msb
//printf("lsb: %d",cmd[6]);
//printf("\nmsb: %d",cmd[7]);
checksum = 0;
checksum ^= cmd[1];
checksum ^= cmd[2];
checksum ^= cmd[3];
checksum ^= cmd[4];
checksum ^= cmd[5];
checksum ^= cmd[6];
checksum ^= cmd[7];
cmd[8] = checksum;
//printf("\nchecksum:%d",cmd[8]);
cmd[9] = 0xCC; //closing byte
cmd[10] = 0;
cmd[11] = 0;
//cmd[12] = 0;
}
Now in my main.c i am sending the cmd array:
Code:
calc(num);
if(!WriteFile(hSerial,cmd,strlen(cmd),&dwBytesRead, NULL))
{
//if any error occurs in writing to serial port.
printf("\n\nError occured while writting file. \n");
exit(1);
}
else
{
printf("\nData sent.");
}
Just to confirm that all the data was indeed sent to the serial port ,i looped the port back to my computer to re-read the data.
Code:
if(!ReadFile(hSerial, rzBuff, 10, &dwBytesRead, NULL))
{
system("cls");
printf("Error occured while reading string data.\n");
system("pause");
exit(1);
}
else
{
printf("\n\nRead data: \n");
printf("0:%x\n1:%x\n2:%d\n3:%c\n4:%c\n5:%c\n6:%d\n7:%d\n8:%d\n9:%x\n10:%d",rzBuff[0],rzBuff[1],rzBuff[2],rzBuff[3],rzBuff[4],rzBuff[5],rzBuff[6],rzBuff[7],rzBuff[8],rzBuff[9],rzBuff[10]);
}
memset(rzBuff,0,strlen(rzBuff));
memset(cmd,0,strlen(cmd));
All is working fine except for one strange thing.
if num is less than 256 and greater than 799 the closing bit i.e cmd[9] always shows 0!!!
I am not able to understand what i am doing wrong,no matter what , cmd[9] should always be 0xcc.
I know this is more of a windows programming related discussion,but i am having trouble in the basic functionality and asignment of variables in a function.
Please help.