I have come once again to ask for your assistance. I have been working on a coding problem for the past couple of days and I just cannot seem to find the problem. I am attempting to communicate with a device over a USB/serial port. The object sending information to my code requires an initial command ("!SCVER?") which I send from the raspberry pi with the following code (hex equivalent):
Code: Select all
char version[8] = {0x21,0x53,0x43,0x56,0x45,0x52,0x3F,'\r'};I then immediately receive a response from the device. The structure of the incoming data packet is as follows:
"1.0(hex byte)(hex byte)(hex byte)(hex byte)(checksum1byte)(checksum2byte)"
The check sum is calculated by adding all of the previous hex values. '1' +'.'+'0'+'(hex byte 1..4)
However my problem occurs when calculating the checksum. I have checked the devices output NUMEROUS times on a PC serial terminal and it is outputting correct checksum values whenever I query it (in the 7th and 8th packet adress). However when I try extracting these values in my C code I get completely different results that do not equate to the checksum.... I am running the code at 38400 baud 8bit no parity. I am starting to wonder if the baud rate has anything to do with it or maybe I am allocating the wrong amount of memory to the buffer1 variable??
My C code is shown below. Any help would be very much appreciated.
Code: Select all
short sum1 = 0;
unsigned char buffer1[15];
char version[8] = {0x21,0x53,0x43,0x56,0x45,0x52,0x3F,'\r'};
write(tty_fd1,version,8);
if(read(tty_fd1,buffer1,15)>0)
{
if(buffer1[0] == '1' && buffer1[1] == '.' && buffer1[2] == '0')
{
printf("Start of packet\n\r");
printf("\n\r");
for(u=0;u<7;u++) //sum current buffer
{
printf("%x\n\r",buffer1[u]);
sum1+=buffer1[u]; //sum turns out to be 16 bit (hence short)
}
printf("Check1: %02x Check2: %02x\n\r",buffer1[7],buffer1[8]); //INCORRECT
checksum1 = ((buffer1[8]<<8)+buffer1[7]); //INCORRECT
printf("check: %04x\n\r",checksum1);
printf("sum: %04x\n\r",sum1);
//if lowbyte of sum is equal to checksum
if(sum1 == checksum1){
currenttime = (buffer1[0]+(buffer1[1]<<8)+(buffer1[2]<<16)+(buffer1[3]<<24));
}
sum1 = 0;
printf("\n\r");
}
}