一、简介
Modbus是一种串行通信协议,是Modicon公司(现在的施耐德电气 Schneider Electric)于1979年为使用可编程逻辑控制器(PLC)通信而发表。Modbus已经成为工业领域通信协议的业界标准(De facto),并且现在是工业电子设备之间常用的连接方式。
RK3568 芯片拥有 10 个 UART 控制器,支持以下功能:
- 均包含两个 64 字节的 FIFO 用于数据接收和传输;- 支持 115.2Kbps、460.8Kbps、921.6Kbps、1.5Mbps、3Mbps、4Mbps;
- 支持可编程波特率,支持非整数时钟分频器;
- 支持基于中断或基于 DMA 的模式;
- 支持 5-8 位宽度传输。
HZ-EVM-RK3568配备四个UART:
root@arm64-ubuntu:~# ls /dev/ttyS*
/dev/ttyS3 /dev/ttyS4 /dev/ttyS5 /dev/ttyS8
此外还配备了UART2 M0,默认是 RK3568 的 Debug UART。

UART3默认波特率是9600,强迫症改成115200方便后续测试。
stty -F /dev/ttyS3 ispeed 115200 ospeed 115200
二、源码编译
在github(Releases · stephane/libmodbus)下载libmodbus源码,最新的是3.1.11。

因为RK3568的核心为cortex-A55,所以需要支持AARCH64的交叉编译器。这里用的是gcc-linaro-x86_64_aarch64-linux-gnu。
源码解压后先配置环境。进入libmodbus-3.1.11文件夹执行 makedir -p install创建install目录。
然后执行./configure ac_cv_func_malloc_0_nonnull=yes --host=aarch64-linux-gnu --enable-static --prefix=$(pwd)/install/ 进行配置。
root@DeepThink:/home/libmodbus-3.1.11# ./configure ac_cv_func_malloc_0_nonnull=yes --host=aarch64-linux-gnu --enable-static --prefix=$(pwd)/install/
checking for a BSD-compatible install... /usr/bin/install -c
checking whether sleep supports fractional seconds... yes
checking filesystem timestamp resolution... 0.01
checking whether build environment is sane... yes
checking for aarch64-linux-gnu-strip... aarch64-linux-gnu-strip
checking for a race-free mkdir -p... /usr/bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking xargs -n works... yes
checking how to create a pax tar archive... gnutar
checking for aarch64-linux-gnu-gcc... /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... yes
checking for suffix of object files... o
checking whether the compiler supports GNU C... yes
checking whether /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc accepts -g... yes
checking for /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc option to enable C11 features... none needed
checking whether /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc understands -c and -o together... yes
checking whether make supports the include directive... yes (GNU style)
checking dependency style of /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc... gcc3
checking for stdio.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for strings.h... yes
checking for sys/stat.h... yes
checking for sys/types.h... yes
checking for unistd.h... yes
checking for wchar.h... yes
checking for minix/config.h... no
checking whether it is safe to define __EXTENSIONS__... yes
checking whether _XOPEN_SOURCE should be defined... no
checking for /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc option to enable large file support... none needed
checking build system type... x86_64-pc-linux-gnu
checking host system type... aarch64-unknown-linux-gnu
checking how to print strings... printf
checking for a sed that does not truncate output... /usr/bin/sed
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for fgrep... /usr/bin/grep -F
checking for ld used by /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc... /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/bin/ld
checking if the linker (/home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/bin/ld) is GNU ld... yes
checking for BSD- or MS-compatible name lister (nm)... /usr/bin/aarch64-linux-gnu-nm -B
checking the name lister (/usr/bin/aarch64-linux-gnu-nm -B) interface... BSD nm
checking whether ln -s works... yes
checking the maximum length of command line arguments... 1572864
checking how to convert x86_64-pc-linux-gnu file names to aarch64-unknown-linux-gnu format... func_convert_file_noop
checking how to convert x86_64-pc-linux-gnu file names to toolchain format... func_convert_file_noop
checking for /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/bin/ld option to reload object files... -r
checking for file... file
checking for aarch64-linux-gnu-objdump... aarch64-linux-gnu-objdump
checking how to recognize dependent libraries... pass_all
checking for aarch64-linux-gnu-dlltool... no
checking for dlltool... no
checking how to associate runtime and link libraries... printf %s\n
checking for aarch64-linux-gnu-ranlib... aarch64-linux-gnu-ranlib
checking for aarch64-linux-gnu-ar... aarch64-linux-gnu-ar
checking for archiver @FILE support... @
checking for aarch64-linux-gnu-strip... (cached) aarch64-linux-gnu-strip
checking command to parse /usr/bin/aarch64-linux-gnu-nm -B output from /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc object... ok
checking for sysroot... no
checking for a working dd... /usr/bin/dd
checking how to truncate binary pipes... /usr/bin/dd bs=4096 count=1
checking for aarch64-linux-gnu-mt... no
checking for mt... mt
configure: WARNING: using cross tools not prefixed with host triplet
checking if mt is a manifest tool... no
checking for dlfcn.h... yes
checking for objdir... .libs
checking if /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc supports -fno-rtti -fno-exceptions... no
checking for /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc option to produce PIC... -fPIC -DPIC
checking if /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc PIC flag -fPIC -DPIC works... yes
checking if /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc static flag -static works... yes
checking if /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc supports -c -o file.o... yes
checking if /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc supports -c -o file.o... (cached) yes
checking whether the /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc linker (/home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/bin/ld) supports shared libraries... yes
checking whether -lc should be explicitly linked in... no
checking dynamic linker characteristics... GNU/Linux ld.so
checking how to hardcode library paths into programs... immediate
checking whether stripping libraries is possible... yes
checking if libtool supports shared libraries... yes
checking whether to build shared libraries... yes
checking whether to build static libraries... yes
checking for arpa/inet.h... yes
checking for byteswap.h... yes
checking for errno.h... yes
checking for fcntl.h... yes
checking for limits.h... yes
checking for linux/serial.h... yes
checking for netdb.h... yes
checking for netinet/in.h... yes
checking for netinet/ip.h... yes
checking for netinet/tcp.h... yes
checking for sys/ioctl.h... yes
checking for sys/params.h... no
checking for sys/socket.h... yes
checking for sys/time.h... yes
checking for sys/types.h... (cached) yes
checking for termios.h... yes
checking for time.h... yes
checking for unistd.h... (cached) yes
checking for /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc options needed to detect all undeclared functions... none needed
checking whether __CYGWIN__ is declared... no
checking for library containing accept... none required
checking for accept4... yes
checking for gai_strerror... yes
checking for getaddrinfo... yes
checking for gettimeofday... yes
checking for inet_pton... yes
checking for inet_ntop... yes
checking for select... yes
checking for socket... yes
checking for strerror... yes
checking for strlcpy... no
checking for inline... inline
checking for aarch64-linux-gnu-g++... aarch64-linux-gnu-g++
checking whether the compiler supports GNU C++... yes
checking whether aarch64-linux-gnu-g++ accepts -g... yes
checking for aarch64-linux-gnu-g++ option to enable C++11 features... none needed
checking dependency style of aarch64-linux-gnu-g++... gcc3
checking how to run the C++ preprocessor... aarch64-linux-gnu-g++ -E
checking for ld used by aarch64-linux-gnu-g++... /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/bin/ld
checking if the linker (/home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/bin/ld) is GNU ld... yes
checking whether the aarch64-linux-gnu-g++ linker (/home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/bin/ld) supports shared libraries... yes
checking for aarch64-linux-gnu-g++ option to produce PIC... -fPIC -DPIC
checking if aarch64-linux-gnu-g++ PIC flag -fPIC -DPIC works... yes
checking if aarch64-linux-gnu-g++ static flag -static works... yes
checking if aarch64-linux-gnu-g++ supports -c -o file.o... yes
checking if aarch64-linux-gnu-g++ supports -c -o file.o... (cached) yes
checking whether the aarch64-linux-gnu-g++ linker (/home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/bin/ld) supports shared libraries... yes
checking dynamic linker characteristics... (cached) GNU/Linux ld.so
checking how to hardcode library paths into programs... immediate
checking for int64_t... yes
checking for size_t... yes
checking for ssize_t... yes
checking for uint16_t... yes
checking for uint32_t... yes
checking for uint8_t... yes
checking whether TIOCSRS485 is declared... yes
checking whether TIOCM_RTS is declared... yes
checking that generated files are newer than configure... done
configure: creating ./config.status
config.status: creating Makefile
config.status: creating src/Makefile
config.status: creating src/modbus-version.h
config.status: creating src/win32/modbus.dll.manifest
config.status: creating tests/Makefile
config.status: creating libmodbus.pc
config.status: creating config.h
config.status: creating tests/unit-test.h
config.status: tests/unit-test.h is unchanged
config.status: executing depfiles commands
config.status: executing libtool commands
libmodbus 3.1.11
===============
prefix: /home/libmodbus-3.1.11/install
sysconfdir: ${prefix}/etc
libdir: ${exec_prefix}/lib
includedir: ${prefix}/include
compiler: /home/gcc/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc
cflags: -O2 -Wall -Wmissing-declarations -Wmissing-prototypes -Wnested-externs -Wpointer-arith -Wsign-compare -Wchar-subscripts -Wstrict-prototypes -Wshadow -Wformat-security
ldflags: -L/home/libs/system/glibc_arm64
tests: yes

之后make & make install即可。
root@DeepThink:~/libmodbus-3.1.11$ file install/lib/
libmodbus.a libmodbus.la libmodbus.so libmodbus.so.5 libmodbus.so.5.1.1 pkgconfig/
三、测试
在HZ-RK3568开发板上实现个MODBUS server,具体源码如下:
#include <errno.h>
#include <modbus.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifdef _WIN32
# include <winsock2.h>
#else
# include <sys/socket.h>
#endif
#ifndef MSG_NOSIGNAL
# define MSG_NOSIGNAL 0
#endif
#include "unit-test.h"
enum {
TCP,
TCP_PI,
RTU
};
int main(int argc, char *argv[])
{
int s = -1;
modbus_t *ctx;
modbus_mapping_t *mb_mapping;
int rc;
int i;
int use_backend;
uint8_t *query;
int header_length;
char *ip_or_device;
if (argc > 1) {
if (strcmp(argv[1], "tcp") == 0) {
use_backend = TCP;
} elseif (strcmp(argv[1], "tcppi") == 0) {
use_backend = TCP_PI;
} elseif (strcmp(argv[1], "rtu") == 0) {
use_backend = RTU;
} else {
printf("Modbus server for unit testing.\n");
printf("Usage:\n %s [tcp|tcppi|rtu] [<ip or device>]\n", argv[0]);
printf("Eg. tcp 127.0.0.1 or rtu /dev/ttyUSB0\n\n");
return-1;
}
} else {
use_backend = TCP;
}
if (argc > 2) {
ip_or_device = argv[2];
} else {
switch (use_backend) {
case TCP:
ip_or_device = "127.0.0.1";
break;
case TCP_PI:
ip_or_device = "::1";
break;
case RTU:
ip_or_device = "/dev/ttyUSB0";
break;
default:
break;
}
}
if (use_backend == TCP) {
ctx = modbus_new_tcp(ip_or_device, 1502);
query = malloc(MODBUS_TCP_MAX_ADU_LENGTH);
} elseif (use_backend == TCP_PI) {
ctx = modbus_new_tcp_pi(ip_or_device, "1502");
query = malloc(MODBUS_TCP_MAX_ADU_LENGTH);
} else {
ctx = modbus_new_rtu(ip_or_device, 115200, 'N', 8, 1);
modbus_set_slave(ctx, SERVER_ID);
query = malloc(MODBUS_RTU_MAX_ADU_LENGTH);
}
header_length = modbus_get_header_length(ctx);
modbus_set_debug(ctx, TRUE);
mb_mapping = modbus_mapping_new_start_address(UT_BITS_ADDRESS,
UT_BITS_NB,
UT_INPUT_BITS_ADDRESS,
UT_INPUT_BITS_NB,
UT_REGISTERS_ADDRESS,
UT_REGISTERS_NB_MAX,
UT_INPUT_REGISTERS_ADDRESS,
UT_INPUT_REGISTERS_NB);
if (mb_mapping == NULL) {
fprintf(stderr, "Failed to allocate the mapping: %s\n", modbus_strerror(errno));
modbus_free(ctx);
return-1;
}
modbus_set_bits_from_bytes(
mb_mapping->tab_input_bits, 0, UT_INPUT_BITS_NB, UT_INPUT_BITS_TAB);
for (i = 0; i < UT_INPUT_REGISTERS_NB; i++) {
mb_mapping->tab_input_registers[i] = UT_INPUT_REGISTERS_TAB[i];
}
if (use_backend == TCP) {
s = modbus_tcp_listen(ctx, 1);
modbus_tcp_accept(ctx, &s);
} elseif (use_backend == TCP_PI) {
s = modbus_tcp_pi_listen(ctx, 1);
modbus_tcp_pi_accept(ctx, &s);
} else {
rc = modbus_connect(ctx);
if (rc == -1) {
fprintf(stderr, "Unable to connect %s\n", modbus_strerror(errno));
modbus_free(ctx);
return-1;
}
}
for (;;) {
do {
rc = modbus_receive(ctx, query);
} while (rc == 0);
if (rc == -1 && errno != EMBBADCRC) {
break;
}
if (query[header_length] == 0x03) {
if (MODBUS_GET_INT16_FROM_INT8(query, header_length + 3) ==
UT_REGISTERS_NB_SPECIAL) {
printf("Set an incorrect number of values\n");
MODBUS_SET_INT16_TO_INT8(
query, header_length + 3, UT_REGISTERS_NB_SPECIAL - 1);
} elseif (MODBUS_GET_INT16_FROM_INT8(query, header_length + 1) ==
UT_REGISTERS_ADDRESS_SPECIAL) {
printf("Reply to this special register address by an exception\n");
modbus_reply_exception(ctx, query, MODBUS_EXCEPTION_SLAVE_OR_SERVER_BUSY);
continue;
} elseif (MODBUS_GET_INT16_FROM_INT8(query, header_length + 1) ==
UT_REGISTERS_ADDRESS_INVALID_TID_OR_SLAVE) {
constint RAW_REQ_LENGTH = 5;
uint8_t raw_req[] = {(use_backend == RTU) ? INVALID_SERVER_ID : 0xFF,
0x03,
0x02,
0x00,
0x00};
printf("Reply with an invalid TID or slave\n");
modbus_send_raw_request(ctx, raw_req, RAW_REQ_LENGTH * sizeof(uint8_t));
continue;
} elseif (MODBUS_GET_INT16_FROM_INT8(query, header_length + 1) ==
UT_REGISTERS_ADDRESS_SLEEP_500_MS) {
printf("Sleep 0.5 s before replying\n");
usleep(500000);
} elseif (MODBUS_GET_INT16_FROM_INT8(query, header_length + 1) ==
UT_REGISTERS_ADDRESS_BYTE_SLEEP_5_MS) {
uint8_t req[] = "\x00\x1C\x00\x00\x00\x05\xFF\x03\x02\x00\x00";
int req_length = 11;
int w_s = modbus_get_socket(ctx);
if (w_s == -1) {
fprintf(stderr, "Unable to get a valid socket in special test\n");
continue;
}
req[1] = query[1];
for (i = 0; i < req_length; i++) {
printf("(%.2X)", req[i]);
usleep(5000);
rc = send(w_s, (constchar *) (req + i), 1, MSG_NOSIGNAL);
if (rc == -1) {
break;
}
}
continue;
}
}
rc = modbus_reply(ctx, query, rc, mb_mapping);
if (rc == -1) {
break;
}
}
printf("Quit the loop: %s\n", modbus_strerror(errno));
if (use_backend == TCP) {
if (s != -1) {
close(s);
}
}
modbus_mapping_free(mb_mapping);
free(query);
modbus_close(ctx);
modbus_free(ctx);
return0;
}
依旧在PC上编译好,然后在测试PC运行modbus-poll。
在HZ-RK3568开发板上打开测试程序。
root@arm64-ubuntu:~# ./mod-server rtu /dev/ttyS3
Opening /dev/ttyS3 at 115200 bauds (N, 8, 1)
Waiting for an indication...
modbus-poll读寄存器设置如下,设备id是测试程序里面写死的。

HZ-RK3568开发板侧的log显示已经收到modbus信息,对比modbus-poll的信息:

到此为止,可以接入MODBUS设备了。