README.rst
1.. zephyr:code-sample:: modbus-tcp-server
2 :name: Modbus TCP server
3 :relevant-api: modbus bsd_sockets
4
5 Implement a Modbus TCP server exposing Modbus commands to control LEDs.
6
7Overview
8********
9
10This is a simple application demonstrating a Modbus TCP server implementation
11in Zephyr RTOS.
12
13Requirements
14************
15
16This sample has been tested with FRDM-K64F board,
17but it should work with any board or shield that has a network interface.
18Additionally the board should have three LEDs.
19
20TCP server example is running on an evaluation board. Client is running
21on a PC or laptop.
22
23The description of this sample uses `PyModbus`_ (Pymodbus REPL).
24The user can of course try out other client implementations with this sample.
25
26Building and Running
27********************
28
29The following commands build and flash TCP server sample.
30
31.. zephyr-app-commands::
32 :zephyr-app: samples/subsys/modbus/tcp_server
33 :board: frdm_k64f
34 :goals: build flash
35 :compact:
36
37On the client side, PC or laptop, the following command connects PyModbus
38to the TCP server.
39
40.. code-block:: console
41
42 # pymodbus.console tcp --host 192.0.2.1 --port 502
43
44The LEDs on the board are controlled by Modbus commands FC01, FC05, FC15.
45For example, to set LED0 on use FC01 command (write_coil).
46
47.. code-block:: console
48
49 > client.connect
50 > client.write_coil address=0 value=1 slave=1
51
52Client should confirm successful communication and LED0 should light.
53
54.. code-block:: console
55
56 {
57 "address": 0,
58 "value": true
59 }
60
61To set LED0 off but LED1 and LED2 on use FC15 command (write_coils).
62
63.. code-block:: console
64
65 > client.write_coils address=0 values=0,1,1 slave=1
66
67To read LED0, LED1, LED2 state FC05 command (read_coils) can be used.
68
69.. code-block:: console
70
71 > client.read_coils address=0 count=3 slave=1
72 {
73 "bits": [
74 false,
75 true,
76 true,
77 false,
78 false,
79 false,
80 false,
81 false
82 ]
83 }
84
85It is also possible to write and read the holding registers.
86This however does not involve any special interaction
87with the peripherals on the board yet.
88
89To write single holding registers use FC06 command (write_register),
90
91.. code-block:: console
92
93 > client.write_register address=0 value=42 slave=1
94
95or FC16 command (write_registers).
96
97.. code-block:: console
98
99 > client.write_registers address=0 values=42,42,42 slave=1
100
101To read holding registers use FC03 command (read_holding_registers).
102
103.. code-block:: console
104
105 > client.read_holding_registers address=0 count=3 slave=1
106 {
107 "registers": [
108 42,
109 42,
110 42
111 ]
112 }
113
114.. _`PyModbus`: https://github.com/pymodbus-dev/pymodbus
115