Appending CRC (Checksum) to data stream serial port communication C++ -
i appending crc data stream. using serial port libary rs-232 linux , windows.
i want same value 1 displayed on comport tool picture:
i using const char[4086]="123456789";
buffer.
crc returned bb3d convert unsigned short
char *
.
#define serialport_bufsize 4088 char *im_buf = (char *)malloc(serialport_bufsize + 8); char *tx_buf = (char *)malloc(serialport_rcv_bufsize + 8); const char buf[serialport_bufsize]="123456789"; strcpy(im_buf, buf); writetoserialport(); // call function void serialportcom::writetoserialport(void) { if(!port_open) return; int i,n, tmp, tmp2; if(newline == 1) { strcat(im_buf, "0a"); } else if(newline == 2) { strcat(im_buf, "0d"); } else if(newline == 3) { strcat(im_buf, "0d0a"); } n = strlen(im_buf) / 2; if(n < 1) return; for(i=0; i< n; i++) { tmp = im_buf[i*2]; if((tmp >= '0') && (tmp <= '9')) { tmp -= '0'; } else if((tmp >= 'a') && (tmp <= 'f')) { tmp -= ('a' - 10); } else if((tmp >= 'a') && (tmp <= 'f')) { tmp -= ('a' - 10); } tmp *= 16; tmp2 = im_buf[(i*2)+1]; if((tmp2 >= '0') && (tmp2 <= '9')) { tmp2 -= '0'; } else if((tmp2 >= 'a') && (tmp2 <= 'f')) { tmp2 -= ('a' - 10); } else if((tmp2 >= 'a') && (tmp2 <= 'f')) { tmp2 -= ('a' - 10); } tmp += tmp2; tx_buf[i] = tmp; } //generate crc unsigned short crc = getcrc16(im_buf, strlen(im_buf)); //append crc memcpy( tx_buf + n, &crc, 2 ); //send serial port rs232_sendbuf(comport_nr, (unsigned char *)tx_buf, n+2); }
what get: (12 34 56 78 70 11 4a 3d
)
want:(12 34 56 78 7b 34 fd fd fd fd
)
how achieve expected result?
unsigned short serialportcom::getcrc16(const char* instr,unsigned int len) { //crc16 unsigned short crc16table[256]; unsigned int i,j; unsigned short crc; unsigned char crchigh = 0xff, crclow = 0xff; (i = 0; < 256; i++) { crc = i; (j = 0; j < 8; j++) { if(crc & 0x1) crc = (crc >> 1) ^ 0xa001; else crc >>= 1; } crc16table[i] = crc; } //crc16 crc=0x0000; for(i=0; i<len; i++) { crc = (crc >> 8) ^ crc16table[(crc & 0xff) ^(uint8_t) instr[i]]; } //crc ^= 0x0000; return crc; }
first, notes :
- your inputs ascii hex. each character half-byte, input string has odd number of characters : discard last character.
- what expect
12 34 56 78 7b 34
:0x347b
crc0x12 0x34 0x56 0x78
. additionalfd
s looks irrelevant end of buffer (or bug ?).
the problems program :
you need data buffer send rs232_sendbuf
. convert ascii data , put in tx_buf
, take crc. that's fine, use strcat
append crc buffer ; can't that, strcat
text. strcat
expect 2 null terminated strings, have 2 data buffers.
you crc function has problem : have superfluous mask & 0x7f
removes last bit of each crc byte. 0xff
mask sufficient (and not needed actually).
you allocate buffer new char[2]
, never delete
it. work it's ugly.
note crc 2 bytes ; return crc
directly unsigned short
.
after that, append crc buffer memcpy
.
in case, memcpy( tx_buf + n, &my_crc_short, 2 );
Comments
Post a Comment