Skip to content

Commit d0ebeee

Browse files
carlescufinashif
authored andcommitted
modbus: Get rid of custom CRC16 function
In previous commits the crc16_ansi() function has been made compliant with the CRC-16-ANSI aka CRC-16-MODBUS standard. Use that standard function instead of a custom one. Signed-off-by: Carles Cufi <[email protected]>
1 parent 7f65249 commit d0ebeee

File tree

1 file changed

+4
-35
lines changed

1 file changed

+4
-35
lines changed

subsys/modbus/modbus_serial.c

Lines changed: 4 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ LOG_MODULE_REGISTER(modbus_serial, CONFIG_MODBUS_LOG_LEVEL);
2626
#include <kernel.h>
2727
#include <string.h>
2828
#include <sys/byteorder.h>
29+
#include <sys/crc.h>
2930
#include <modbus_internal.h>
3031

3132
static void modbus_serial_tx_on(struct modbus_context *ctx)
@@ -238,37 +239,6 @@ static void modbus_ascii_tx_adu(struct modbus_context *ctx)
238239
}
239240
#endif
240241

241-
static uint16_t modbus_rtu_crc16(uint8_t *src, size_t length)
242-
{
243-
uint16_t crc = 0xFFFF;
244-
uint8_t shiftctr;
245-
bool flag;
246-
uint8_t *pblock = src;
247-
248-
while (length > 0) {
249-
length--;
250-
crc ^= (uint16_t)*pblock++;
251-
shiftctr = 8;
252-
do {
253-
/* Determine if the shift out of rightmost bit is 1 */
254-
flag = (crc & 0x0001) ? true : false;
255-
/* Shift CRC to the right one bit. */
256-
crc >>= 1;
257-
/*
258-
* If bit shifted out of rightmost bit was a 1
259-
* exclusive OR the CRC with the generating polynomial.
260-
*/
261-
if (flag == true) {
262-
crc ^= MODBUS_CRC16_POLY;
263-
}
264-
265-
shiftctr--;
266-
} while (shiftctr > 0);
267-
}
268-
269-
return crc;
270-
}
271-
272242
/* Copy Modbus RTU frame and check if the CRC is valid. */
273243
static int modbus_rtu_rx_adu(struct modbus_context *ctx)
274244
{
@@ -296,8 +266,8 @@ static int modbus_rtu_rx_adu(struct modbus_context *ctx)
296266

297267
ctx->rx_adu.crc = sys_get_le16(&cfg->uart_buf[crc_idx]);
298268
/* Calculate CRC over address, function code, and payload */
299-
calc_crc = modbus_rtu_crc16(&cfg->uart_buf[0],
300-
cfg->uart_buf_ctr - sizeof(ctx->rx_adu.crc));
269+
calc_crc = crc16_ansi(&cfg->uart_buf[0],
270+
cfg->uart_buf_ctr - sizeof(ctx->rx_adu.crc));
301271

302272
if (ctx->rx_adu.crc != calc_crc) {
303273
LOG_WRN("Calculated CRC does not match received CRC");
@@ -320,8 +290,7 @@ static void rtu_tx_adu(struct modbus_context *ctx)
320290

321291
memcpy(data_ptr, ctx->tx_adu.data, ctx->tx_adu.length);
322292

323-
ctx->tx_adu.crc = modbus_rtu_crc16(&cfg->uart_buf[0],
324-
ctx->tx_adu.length + 2);
293+
ctx->tx_adu.crc = crc16_ansi(&cfg->uart_buf[0], ctx->tx_adu.length + 2);
325294
sys_put_le16(ctx->tx_adu.crc,
326295
&cfg->uart_buf[ctx->tx_adu.length + 2]);
327296
tx_bytes += 2;

0 commit comments

Comments
 (0)