Commit 27b90deddba7c4d7c5d7d8494f1aec9ef6d69cea

Authored by Stéphane Raimbault
Committed by Stéphane Raimbault
1 parent a2e0e454

Swap CRC bytes in request data but not at CRC computing (#397)

Showing 1 changed file with 8 additions and 5 deletions
src/modbus-rtu.c
@@ -137,9 +137,9 @@ static uint16_t crc16(uint8_t *buffer, uint16_t buffer_length) @@ -137,9 +137,9 @@ static uint16_t crc16(uint8_t *buffer, uint16_t buffer_length)
137 137
138 /* pass through message buffer */ 138 /* pass through message buffer */
139 while (buffer_length--) { 139 while (buffer_length--) {
140 - i = crc_hi ^ *buffer++; /* calculate the CRC */  
141 - crc_hi = crc_lo ^ table_crc_hi[i];  
142 - crc_lo = table_crc_lo[i]; 140 + i = crc_lo ^ *buffer++; /* calculate the CRC */
  141 + crc_lo = crc_hi ^ table_crc_hi[i];
  142 + crc_hi = table_crc_lo[i];
143 } 143 }
144 144
145 return (crc_hi << 8 | crc_lo); 145 return (crc_hi << 8 | crc_lo);
@@ -155,8 +155,11 @@ static int _modbus_rtu_prepare_response_tid(const uint8_t *req, int *req_length) @@ -155,8 +155,11 @@ static int _modbus_rtu_prepare_response_tid(const uint8_t *req, int *req_length)
155 static int _modbus_rtu_send_msg_pre(uint8_t *req, int req_length) 155 static int _modbus_rtu_send_msg_pre(uint8_t *req, int req_length)
156 { 156 {
157 uint16_t crc = crc16(req, req_length); 157 uint16_t crc = crc16(req, req_length);
158 - req[req_length++] = crc >> 8; 158 +
  159 + /* According to the MODBUS specs (p. 14), the low order byte of the CRC comes
  160 + * first in the RTU message */
159 req[req_length++] = crc & 0x00FF; 161 req[req_length++] = crc & 0x00FF;
  162 + req[req_length++] = crc >> 8;
160 163
161 return req_length; 164 return req_length;
162 } 165 }
@@ -374,7 +377,7 @@ static int _modbus_rtu_check_integrity(modbus_t *ctx, uint8_t *msg, @@ -374,7 +377,7 @@ static int _modbus_rtu_check_integrity(modbus_t *ctx, uint8_t *msg,
374 } 377 }
375 378
376 crc_calculated = crc16(msg, msg_length - 2); 379 crc_calculated = crc16(msg, msg_length - 2);
377 - crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1]; 380 + crc_received = (msg[msg_length - 1] << 8) | msg[msg_length - 2];
378 381
379 /* Check CRC of msg */ 382 /* Check CRC of msg */
380 if (crc_calculated == crc_received) { 383 if (crc_calculated == crc_received) {