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 <carles.cufi@nordicsemi.no>
This commit is contained in:
parent
7f6524949a
commit
d0ebeee0aa
1 changed files with 4 additions and 35 deletions
|
@ -26,6 +26,7 @@ LOG_MODULE_REGISTER(modbus_serial, CONFIG_MODBUS_LOG_LEVEL);
|
|||
#include <kernel.h>
|
||||
#include <string.h>
|
||||
#include <sys/byteorder.h>
|
||||
#include <sys/crc.h>
|
||||
#include <modbus_internal.h>
|
||||
|
||||
static void modbus_serial_tx_on(struct modbus_context *ctx)
|
||||
|
@ -238,37 +239,6 @@ static void modbus_ascii_tx_adu(struct modbus_context *ctx)
|
|||
}
|
||||
#endif
|
||||
|
||||
static uint16_t modbus_rtu_crc16(uint8_t *src, size_t length)
|
||||
{
|
||||
uint16_t crc = 0xFFFF;
|
||||
uint8_t shiftctr;
|
||||
bool flag;
|
||||
uint8_t *pblock = src;
|
||||
|
||||
while (length > 0) {
|
||||
length--;
|
||||
crc ^= (uint16_t)*pblock++;
|
||||
shiftctr = 8;
|
||||
do {
|
||||
/* Determine if the shift out of rightmost bit is 1 */
|
||||
flag = (crc & 0x0001) ? true : false;
|
||||
/* Shift CRC to the right one bit. */
|
||||
crc >>= 1;
|
||||
/*
|
||||
* If bit shifted out of rightmost bit was a 1
|
||||
* exclusive OR the CRC with the generating polynomial.
|
||||
*/
|
||||
if (flag == true) {
|
||||
crc ^= MODBUS_CRC16_POLY;
|
||||
}
|
||||
|
||||
shiftctr--;
|
||||
} while (shiftctr > 0);
|
||||
}
|
||||
|
||||
return crc;
|
||||
}
|
||||
|
||||
/* Copy Modbus RTU frame and check if the CRC is valid. */
|
||||
static int modbus_rtu_rx_adu(struct modbus_context *ctx)
|
||||
{
|
||||
|
@ -296,8 +266,8 @@ static int modbus_rtu_rx_adu(struct modbus_context *ctx)
|
|||
|
||||
ctx->rx_adu.crc = sys_get_le16(&cfg->uart_buf[crc_idx]);
|
||||
/* Calculate CRC over address, function code, and payload */
|
||||
calc_crc = modbus_rtu_crc16(&cfg->uart_buf[0],
|
||||
cfg->uart_buf_ctr - sizeof(ctx->rx_adu.crc));
|
||||
calc_crc = crc16_ansi(&cfg->uart_buf[0],
|
||||
cfg->uart_buf_ctr - sizeof(ctx->rx_adu.crc));
|
||||
|
||||
if (ctx->rx_adu.crc != calc_crc) {
|
||||
LOG_WRN("Calculated CRC does not match received CRC");
|
||||
|
@ -320,8 +290,7 @@ static void rtu_tx_adu(struct modbus_context *ctx)
|
|||
|
||||
memcpy(data_ptr, ctx->tx_adu.data, ctx->tx_adu.length);
|
||||
|
||||
ctx->tx_adu.crc = modbus_rtu_crc16(&cfg->uart_buf[0],
|
||||
ctx->tx_adu.length + 2);
|
||||
ctx->tx_adu.crc = crc16_ansi(&cfg->uart_buf[0], ctx->tx_adu.length + 2);
|
||||
sys_put_le16(ctx->tx_adu.crc,
|
||||
&cfg->uart_buf[ctx->tx_adu.length + 2]);
|
||||
tx_bytes += 2;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue