REKLAMA

MODBUS_materiały.rar

Jak działa protokół MODBUS RTU na mikrokontrolerze AVR z RS485?

Witam Robiłem kiedyś sterownik zbierający dane z maszyny i przesyłający je do kompa za pomocą MODBUSA (moja praca inż na ATH :-) ). W załączniku przesyłam różne dane z których korzystałem mam nadzieję ze się przydadzą Pozdrawiam Aha zapomniałbym. Proponuje zajrzeć na stronę www.modbus.pl Jest tam fajny programik "MODBUS Tester" Jest bardzo pomocny przy testowaniu poprawności transmisji.


Pobierz plik - link do postu
  • MODBUS_materiały.rar
    • Instrukcja%20-%20Modbus.pdf
    • Elektronika Wirtualna.htm
    • Modbus_over_serial_line_V1 implementacja.pdf
    • Sterowniki_komunikacja.pdf
    • MOD.PDF
    • radio kontrola z modbusem.pdf
    • Elektronika Wirtualna_pliki
      • KSIEGA.GIF
      • HTML.GIF
      • KONTAKT.GIF
      • ftr_separator.gif
      • LOGO.JPG
      • UKLADY.GIF
      • DOWNLOAD.GIF
      • ARTYKULY.GIF
      • RADIO.GIF
      • Thumbs.db
      • TOP.GIF
      • LEFT2.GIF
      • TV.GIF
      • TEORIA.GIF
      • STYL.CSS
      • JAVA.GIF
      • RIGHT2.GIF
      • ICONS.JPG
      • FORUM.GIF
      • DOWN.GIF
      • LEFT.GIF
      • LINKI.GIF
      • WARSZTAT.GIF
      • blank_header.jpg
      • dluga_linia.jpg
      • ROZNE.GIF
      • NEWS.GIF
      • CHAT.GIF
      • BANER.GIF
      • CPP.GIF
      • komputery.gif
      • CYFRA.GIF
      • CB.GIF
      • RIGHT.GIF
      • aplikacje.gif
      • INDEX.GIF
      • IRC.GIF
      • AUDIO.GIF
      • KABLE.GIF
      • MAIL.GIF
      • TOPLEFT.JPG
    • Łącze RS-232, protokoły transmisji.txt
    • Modbus Application Protocol v1.pdf
    • Sieci przemysłowe.htm
    • PI_MBUS_300.pdf
    • MODBUS_ES-1510.pdf
    • Array
    • Modbus Application Protocol v1 opis funkcji.pdf
    • MODBUS
      • modbus, kontrola ramki danych crc; pomocy!!!_pliki
        • icon_offline.gif
        • DLEVEL3.GIF
        • DLEVEL2.GIF
        • Thumbs.db
        • POST.GIF
        • SPACER.GIF
        • quick_reply.gif
        • PRINTER.GIF
        • smartBlue.css
        • icon_profile.gif
        • REPLY.GIF
        • ICON_AIM.GIF
        • icon_quote.gif
        • icon_smile.gif
        • ICON_PM.GIF
        • icon_minipost.gif
        • icon_email.gif
        • 404.HTM
        • icon_bcard.gif
      • BASCOM
        • Array
        • CRC_tablica.bas
        • CRC_TABLICA_2.RPT
        • CRC_tablica_2.bas
        • CRC_TABLICA_2.SIM
        • CRC_TABLICA.OBJ
        • CRC_TABLICA_2.DBG
        • CRC_TABLICA.SMX
        • CRC_TABLICA_2.SMX
        • CRC_TABLICA.RPT
        • CRC_TABLICA_2.BIN
        • CRC_TABLICA.SIM
        • CRC_TABLICA.BIN
        • CRC_TABLICA.HEX
        • CRC_TABLICA.DBG
        • CRC_TABLICA_2.OBJ
        • CRC_TABLICA_2.HEX
      • modbus, kontrola ramki danych crc; pomocy!!!.htm
    • C_CRC16.TXT


MODBUS_materiały.rar > Modbus_over_serial_line_V1 implementacja.pdf

MODBUS over serial line specification and implementation guide V1.0

MODBUS.ORG

MODBUS over Serial Line
Specification & Implementation guide
V1.0

Modbus.org
12/02/02

http://www.modbus.org/

1/44

MODBUS over serial line specification and implementation guide V1.0

Contents

1

Introduction ..............................................................................4
1.1
1.2
1.3
1.4
1.5

2

6

Installation................................................................................ 33
User Guide............................................................................... 33

Implementation Classes ........................................................34
Appendix ................................................................................35
6.1
6.2
6.3

Modbus.org
12/02/02

Preamble.................................................................................. 20
Data Signaling Rates ............................................................... 20
Electrical Interfaces.................................................................. 21
Multipoint System requirements............................................... 27
Mechanical Interfaces .............................................................. 29
Cables...................................................................................... 32
Visual Diagnosis ...................................................................... 32

Installation and Documentation .............................................33
4.1
4.2

5

MODBUS Master / Slaves protocol principle.............................. 7
MODBUS Addressing rules........................................................ 8
MODBUS frame description....................................................... 8
Master / Slaves State Diagrams................................................. 9
The two serial Transmission Modes......................................... 12
Error Checking Methods .......................................................... 19

Physical Layer........................................................................20
3.1
3.2
3.3
3.4
3.5
3.6
3.7

4

Scope of this document ............................................................. 4
Protocol overview....................................................................... 5
Conventions ............................................................................... 5
Compliance ................................................................................ 6
Glossary..................................................................................... 6

MODBUS Data Link Layer .......................................................7
2.1
2.2
2.3
2.4
2.5
2.6

3

MODBUS.ORG

Appendix A - Management of Serial Line Diagnostic Counters 35
Appendix B - LRC/CRC Generation ......................................... 38
Appendix E - References ......................................................... 44

http://www.modbus.org/

2/44

MODBUS over serial line specification and implementation guide V1.0

1.0

MODBUS.ORG

Document modifications
Month-Year Modifications
Nov 02
Creation.
This document comprises a description of Master / slave protocol and of the two
different transmission modes ( RTU, ASCII).
The main features of the physical layer ( RS485, RS232) and some recommendations
are provided.
Implementation classes are proposed to guide the implementation.

Modbus.org
12/02/02

http://www.modbus.org/

3/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

1
1.1

Introduction
Scope of this document

The MODBUS standard defines an application layer messaging protocol, positioned at level 7 of the OSI model that provides
" client/server " communications between devices connected on different types of buses or networks. It standardizes also a specific
protocol on serial line to exchange MODBUS request between a master and one or several slaves.
The objective of this document is to present the MODBUS protocol over serial line, in order to be used by all system designers when
they want to implement MODBUS protocol on their serial line products. Thus, this document will facilitate interoperability between
devices using the MODBUS protocol.
This document comes in complement to the document called " MODBUS Application Protocol Specification " .
In chapter 5 different implementation classes are defined for " MODBUS Serial Line " .
requirements that a device must respect in order to belong to that class.

Specification of a class is the sum of

The MODBUS
application protocol

MODBUS
Application
Protocol
Specification

This
document

MODBUS over
Serial Line
Specification &
Implementation
Guide

Figure 1:

Modbus.org
12/02/02

( OSI Level 7)

Serial Line specification
(OSI Levels 1 & 2)

General overview of MODBUS documents

http://www.modbus.org/

4/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

1.2

Protocol overview

This document describes the MODBUS over Serial Line protocol. MODBUS Serial Line protocol is a Master-Slave protocol. This
protocol takes place at level 2 of the OSI model.
A master-slave type system has one node (the master node) that issues explicit commands to one of the " slave " nodes and processes
responses. Slave nodes will not typically transmit data without a request from the master node, and do not communicate with other
slaves.
At the physical level, MODBUS over Serial Line systems may use different physical interfaces (RS485, RS232). TIA/EIA-485 (RS485)
Two-Wire interface is the most common. As an add-on option, RS485 Four-Wire interface may also be implemented. A TIA/EIA-232E (RS232) serial interface may also be used as an interface, when only short point to point communication is required. (see chapter
" Physical Layer " )
The following figure gives a general representation of MODBUS serial communication stack compared to the 7 layers of the OSI
model.
Layer

ISO/OSI Model

7

Application

MODBUS Application Protocol

6

Presentation

Empty

5

Session

Empty

4

Transport

Empty

3

Network

Empty

2

Data Link

MODBUS Serial Line Protocol

1

Physical

EIA/TIA-485 (or EIA/TIA-232)

MODBUS Application
Layer
Client / server

MODBUS Master / Slave
EIA/TIA-485
(or EIA/TIA-232)

Figure 2:

MODBUS Protocols and ISO/OSI Model

MODBUS application layer messaging protocol, positioned at level 7 of the OSI model, provides client/server communication between
devices connected on buses or networks. On MODBUS serial line the client role is provided by the Master of the serial bus and the
Slaves nodes act as servers.

1.3

Conventions

In this document, the following words are used to define the significance of each particular requirement.
" MUST " / " REQUIRED "
All requirements containing the word " MUST " are mandatory. The word MUST, or the adjective " REQUIRED " , means that the item is
an absolute requirement of the implementation. These words are underlined.
" SHOULD " / " RECOMMENDED "
All recommendations containing the word " SHOULD " , or the adjective “RECOMMENDED”, are considered desired behavior. These
recommendations should be used as a guideline when choosing between different options to implement functionality. There may be
valid reasons in particular circumstances to ignore this item, but the full implications should be understood and the case carefully
weighed before choosing a different course. These words are underlined.
" MAY " / " OPTIONAL "
The word “MAY”, or the adjective " OPTIONAL " , means that this item is truly optional. One designer may choose to include the item
because a particular marketplace requires it or because it enhances the product, for example; another designer may omit the same
item.

Modbus.org
12/02/02

http://www.modbus.org/

5/44

MODBUS over serial line specification and implementation guide V1.0

1.4

MODBUS.ORG

Compliance

An implementation is not in conformity if it fails to satisfy one or more of the MUST requirements from its implementation class.
An implementation that satisfies all the MUST requirements and all the SHOULD recommendations is said to be " unconditionally
compliant " .
One that satisfies all the MUST requirements but not all the SHOULD recommendations is said to be " conditionally compliant " .

1.5

Glossary

Definition of particular words, symbols, and abbreviations used in this document.

2W

The Two-Wire configuration defined in the “Electrical Interface” chapter, or one of its interfaces.

4W

The Four-Wire configuration defined in the “Electrical Interface” chapter, or one of its interfaces.

AUI

Attachment Unit Interface

Common

The Signal Common in EIA/TIA Standards. In a 2W-or 4W-RS485 MODBUS Network, Signal and optional
Power Supply Common

DCE

a MODBUS Device, for example a programmable controller adapter, which implements an RS232 Data
Circuit-terminating Equipment, also named Data Communication Equipment.

Device

or “MODBUS device” : see this definition.

Driver

Generator, or Transmitter.

DTE

a MODBUS Device, for example a programming panel or a PC, which implements an RS232 Data
Terminal Equipment.

ITr

Physical bus Interface on Trunk side.

IDv

Physical bus Interface on Derivation (or tap or device drop) side.

LT

Line Termination.

MODBUS Device

a Device that implements MODBUS over Serial Line and respects this Technical Note.

RS232

EIA/ TIA -232 Standard.

RS485

EIA/ TIA -485 Standard.

RS485-MODBUS

A 2W-or 4W-Network in accordance with this Technical Note.

Transceiver

a Transmitter and a Receiver (or Driver and Receiver).

Modbus.org
12/02/02

http://www.modbus.org/

6/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

2

MODBUS Data Link Layer

2.1

MODBUS Master / Slaves protocol principle

The MODBUS Serial Line protocol is a Master-Slaves protocol. Only one master (at the same time) is connected to the bus, and one
or several (247 maximum number) slaves nodes are also connected to the same serial bus. A MODBUS communication is always
initiated by the master. The slave nodes will never transmit data without receiving a request from the master node. The slave nodes
will never communicate with each other. The master node initiates only one MODBUS transaction at the same time.
The master node issues a MODBUS request to the slave nodes in two modes :
In unicast mode, the master addresses an individual slave. After receiving and processing the request, the slave returns a
message (a 'reply') to the master .
In that mode, a MODBUS transaction consists of 2 messages : a request from the master, and a reply from the slave.
Each slave must have an unique address (from 1 to 247) so that it can be addressed independently from other nodes.
In broadcast mode, the master can send a request to all slaves.
No response is returned to broadcast requests sent by the master. The broadcast requests are necessarily writing commands. All
devices must accept the broadcast for writing function. The address 0 is reserved to identify a broadcast exchange.

master

request

reply

slave

slave

slave

Figure 3:

Unicast mode

master

request

slave

slave

Figure 4:

Modbus.org
12/02/02

slave

Broadcast mode

http://www.modbus.org/

7/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

2.2

MODBUS Addressing rules

The MODBUS addressing space comprises 256 different addresses.
0

From 1 to 247

From 248 to 255

Broadcast
address

Slave individual addresses

Reserved

The Address 0 is reserved as the broadcast address. All slave nodes must recognise the broadcast address.
The MODBUS Master node has no specific address, only the slave nodes must have an address. This address must be unique on a
MODBUS serial bus.

2.3

MODBUS frame description

The MODBUS application protocol [1] defines a simple Protocol Data Unit (PDU) independent of the underlying communication layers:

Data

Function code
MODBUS PDU
Figure 5:

MODBUS Protocol Data Unit

The mapping of MODBUS protocol on a specific bus or network introduces some additional fields on the Protocol Data Unit. The
client that initiates a MODBUS transaction builds the MODBUS PDU, and then adds fields in order to build the appropriate
communication PDU.

MODBUS SERIAL LINE PDU
Address field

Function code

Data

CRC (or LRC)

MODBUS PDU
Figure 6:

MODBUS frame over Serial Line

On MODBUS Serial Line, the Address field only contains the slave address.
As described in the previous section the valid slave nodes addresses are in the range of 0 – 247 decimal. The individual slave
devices are assigned addresses in the range of 1 – 247. A master addresses a slave by placing the slave address in the address field
of the message. When the slave returns its response, it places its own address in the response address field to let the master know
which slave is responding.
The function code indicates to the server what kind of action to perform. The function code can be followed by a data field that
contains request and response parameters.
Error checking field is the result of a " Redundancy Checking " calculation that is performed on the message contents. Two kinds
of calculation methods are used depending on the transmission mode that is being used (RTU or ASCII). (see 2.5 section, " The
two serial Transmission Modes " )

Modbus.org
12/02/02

http://www.modbus.org/

8/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

2.4

Master / Slaves State Diagrams

The MODBUS data link layer comprises two separate sub layers :


The Master / slave protocol



The transmission mode ( RTU vs ASCII modes)

The following sections describes the state diagrams of a master and a slave that are independent of transmission modes used.
The RTU and ASCII transmission modes are specified in next chapters using two state diagrams. The reception and the sending of a
frame are described.
Syntax of state diagram :
The following state diagrams are drawn in compliance with UML standard notations. The notation is briefly recalled below :
trigger [ guard condition ]
/ action

State_A

State_B

When a " trigger " event occurs in a system being in " State_A " , system is going into " State_B " , only if " guard condition " is true. An action " action " is then
performed.

2.4.1

Master State diagram

The following drawing explains the Master behavior :

Request sent in
broadcast mode
/ turnaround delay
is started
Waiting
turnaround
delay
turnaround delay
expiration

Reply reception
[Unexpected slave]

Idle

request sent to a
slave
/ response timeout is started

Waiting
for reply

Figure 7:

End of error processing
End of reply processing

Processing
reply

Frame error

Reply reception [Expected slave]
/ response time-out is stopped
response time-out expiration

Processing
error

Master state diagram

Some explanations about the state diagram above :
State " Idle " = no pending request. This is the initial state after power-up. A request can only be sent in " Idle " state. After sending
a request, the Master leaves the " Idle " state, and cannot send a second request at the same time
When a unicast request is sent to a slave, the master goes into " Waiting for reply " state, and a “Response Time-out” is started. It
prevents the Master from staying indefinitely in " Waiting for reply " state. Value of the Response time-out is application
dependant.
When a reply is received, the Master checks the reply before starting the data processing. The checking may result in an error,
for example a reply from an unexpected slave, or an error in the received frame. In case of a reply received from an unexpected
slave, the Response time-out is kept running. In case of an error detected on the frame, a retry may be performed.
If no reply is received, the Response time-out expires, and an error is generated. Then the Master goes into " Idle " state, enabling
a retry of the request. The maximum number of retries depends on the master set-up.

Modbus.org
12/02/02

http://www.modbus.org/

9/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

When a broadcast request is sent on the serial bus, no response is returned from the slaves. Nevertheless a delay is respected
by the Master in order to allow any slave to process the current request before sending a new one. This delay is called
" Turnaround delay " . Therefore the master goes into " Waiting Turnaround delay " state before going back in " idle " state and before
being able to send another request.
In unicast the Response time out must be set long enough for any slave to process the request and return the response, in
broadcast the Turnaround delay must be long enough for any slave to process only the request and be able to receive a new one.
Therefore the Turnaround delay should be shorter than the Response time-out. Typically the Response time-out is from 1s to
several second at 9600 bps; and the Turnaround delay is from 100 ms to 200ms.
Frame error consists of : 1) Parity checking applied to each character; 2) Redundancy checking applied to the entire frame. See
§2.6 " Error Checking Methods " for more explanations.
The state diagram is intentionally very simple. It does not take into account access to the line, message framing, or retry following
transmission error, etc … For more details about frame transmission, please refer to 2.5 paragraph, " The two serial Transmission
Modes " .

2.4.2

Slave State Diagram

The following drawing explains the Slave behavior :

Idle

error reply sent
normal reply sent

Formatting
normal reply
reception of a
request

end of processing [unicast mode]

(from the master)

Checking
request

check OK

Processing
required action

error while processing

error in request data

Figure 8:

end of processing
[broadcast mode]

Formatting
error reply

error in frame
checking, or
frame not
addressed to
this slave

Slave state diagram

Some explanations about the above state diagram :
State " Idle " = no pending request. This is the initial state after power-up.
When a request is received, the slave checks the packet before performing the action requested in the packet. Different errors
may occur : format error in the request, invalid action, … In case of error, a reply must be sent to the master.
Once the required action has been completed, a unicast message requires that a reply must be formatted and sent to the master.
If the slave detects an error in the received frame, no respond is returned to the master.
MODBUS diagnostics counters are defined and should be managed by any slave in order to provide diagnostic information.
These counters can be get using the Diagnostic MODBUS function (see Appendix A, and the MODBUS application protocol
specification [1]).

Modbus.org
12/02/02

http://www.modbus.org/

10/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

2.4.3

Master / Slave communication time diagram

This following figure shows the time diagram of 3 typical scenarios of Master / Slave communications.

Reply analysis and
preparation of the
following exchange

Turnaround delay

Wait

Master

Response time out

Wait

REQUEST

BROADCAST

to slave 1

Wait
REQUEST
to slave N
error

Slave 1

REPLY
Request
treatment

Error detection

Slave N

NO
REPLY
Simultaneous execution of
the order by the slaves

Physical
line

Time
Exchange i-1

Figure 9:

Exchange i

Exchange i+1

Master / Slave scenario time diagram

Remarks :
the duration of the REQUEST, REPLY, BROACAST phases depends on the communication features (frame length and
throughput).
the duration of the WAIT and TREATMENT phases depends on the request processing time needed for the slave application.

Modbus.org
12/02/02

http://www.modbus.org/

11/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

2.5

The two serial Transmission Modes

Two different serial transmission modes are defined : The RTU mode and the ASCII mode.
It defines the bit contents of message fields transmitted serially on the line. It determines how information is packed into the message
fields and decoded.
The transmission mode (and serial port parameters) must be the same for all devices on a MODBUS Serial Line.
Although the ASCII mode is required in some specific applications, interoperability between MODBUS devices can be reached only if
each device has the same transmission mode : All devices must implement the RTU Mode. The ASCII transmission mode is an
option.
Devices should be set up by the users to the desired transmission mode, RTU or ASCII. Default setup must be the RTU mode.

2.5.1

RTU Transmission Mode

When devices communicate on a MODBUS serial line using the RTU (Remote Terminal Unit) mode, each 8–bit byte in a message
contains two 4–bit hexadecimal characters. The main advantage of this mode is that its greater character density allows better data
throughput than ASCII mode for the same baud rate. Each message must be transmitted in a continuous stream of characters.
The format for each byte ( 11 bits ) in RTU mode is :
Coding System:
Bits per Byte:

8–bit binary
1 start bit
8 data bits, least significant bit sent first
1 bit for parity completion
1 stop bit

Even parity is required, other modes ( odd parity, no parity ) may also be used. In order to ensure a maximum compatibility with
other products, it is recommended to support also No parity mode. The default parity mode must be even parity.
Remark : the use of no parity requires 2 stop bits.
How Characters are Transmitted Serially :
Each character or byte is sent in this order (left to right):
Least Significant Bit (LSB) . . . Most Significant Bit (MSB)
With Parity Checking
Start

1

2

3

4

Figure 10:

5

6

7

8

Par Stop

Bit Sequence in RTU mode

Devices may accept by configuration either Even, Odd, or No Parity checking. If No Parity is implemented, an additional stop bit is
transmitted to fill out the character frame to a full 11-bit asynchronous character :

Without Parity Checking
Start

Figure 11:

1

2

3

4

5

6

7

8

Stop Stop

Bit Sequence in RTU mode (specific case of No Parity)

Frame Checking Field : Cyclical Redundancy Checking (CRC)

Modbus.org
12/02/02

http://www.modbus.org/

12/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

Frame description :

Slave Function
Address Code
1 byte

Data

1 byte

CRC

0 up to 252 byte(s)

2 bytes
CRC Low CRC Hi

Figure 12:

RTU Message Frame

The maximum size of a MODBUS RTU frame is 256 bytes.

2.5.1.1

MODBUS Message RTU Framing

A MODBUS message is placed by the transmitting device into a frame that has a known beginning and ending point. This allows
devices that receive a new frame to begin at the start of the message, and to know when the message is completed. Partial
messages must be detected and errors must be set as a result.
In RTU mode, message frames are separated by a silent interval of at least 3.5 character times. In the following sections, this time
interval is called t3,5.

Frame 1

Frame 2

Frame 3

t0
3.5 char
at least 3.5 char

at least 3.5 char
4.5 char

MODBUS message

Start
≥ 3.5 char

Address Function
8 bits
8 bits
Figure 13:

Data
N x 8 bits

CRC Check
16 bits

End
≥ 3.5 char

RTU Message Frame

The entire message frame must be transmitted as a continuous stream of characters.
If a silent interval of more than 1.5 character times occurs between two characters, the message frame is declared incomplete and
should be discarded by the receiver.

Frame 1 OK

Frame 2 NOK

t0

≤ 1.5 char

& gt; 1.5 char

Remark :
The implementation of RTU reception driver may imply the management of a lot of interruptions due to the t1.5 and t3.5 timers. With
high communication baud rates, this leads to a heavy CPU load. Consequently these two timers must be strictly respected when the
baud rate is equal or lower than 19200 Bps. For baud rates greater than 19200 Bps, fixed values for the 2 timers should be used: it is
recommended to use a value of 750µs for the inter-character time-out (t1.5) and a value of 1.750ms for inter-frame delay (t3.5).

Modbus.org
12/02/02

http://www.modbus.org/

13/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

The following drawing provides a description of the RTU transmission mode state diagram. Both " master " and " slave " points of view
are expressed in the same drawing :
Character received
/ flag = frame NOK
/start t3.5

Comment
If frame OK
processing frame
If frame NOK
delete entire frame

Initial State
Character received
/ init. and start t3.5

Comment
control frame (CRC, Parity, Slave addr)
flag = frame OK or NOK

Control and
Waiting

t3.5 expired
t1.5 expired

t3.5 expired
First character received
/ init. and start t1.5, t3.5

Idle

Reception

(ready to receive or to emit)

Demand of emission

Character received
/ init. and start t1.5, t3.5

t3.5 expired
Legend

Emitted character
[if last emitted character]
/ init. and start t3.5

Emission

Figure 14:

t1.5, t3.5 : timers
t3.5 : 3.5 character times
t1.5 : 1.5 character times

RTU transmission mode state diagram

Some explanations about the above state diagram:
Transition from " Initial State " to " Idle " state needs t3.5 time-out expiration : that insures inter-frame delay
" Idle " state is the normal state when neither emission nor reception is active.
In RTU mode, the communication link is declared in " idle " state when there is no transmission activity after a time interval equal to
at least 3,5 characters.
When the link is in idle state, each transmitted character detected on the link is identified as the start of a frame. The link goes to
the " active " state. Then, the end of frame is identified when no more character is transmitted on the link after the time interval
t3,5.
After detection of the end of frame, the CRC calculation and checking is completed. Afterwards the address field is analysed to
determine if the frame is for the device. If not the frame is discarded. In order to reduce the reception processing time the
address field can be analysed as soon as it is received without waiting the end of frame. In this case the CRC will be calculated
and checked only if the frame is addressed to the slave (broadcast frame included).

2.5.1.2

CRC Checking

The RTU mode includes an error–checking field that is based on a Cyclical Redundancy Checking (CRC) method performed on the
message contents.
The CRC field checks the contents of the entire message. It is applied regardless of any parity checking method used for the
individual characters of the message.
The CRC field contains a 16–bit value implemented as two 8–bit bytes.
The CRC field is appended to the message as the last field in the message. When this is done, the low–order byte of the field is
appended first, followed by the high–order byte. The CRC high–order byte is the last byte to be sent in the message.
The CRC value is calculated by the sending device, which appends the CRC to the message. The receiving device recalculates a
CRC during receipt of the message, and compares the calculated value to the actual value it received in the CRC field. If the two
values are not equal, an error results.
The CRC calculation is started by first pre-loading a 16–bit register to all 1’s. Then a process begins of applying successive 8–bit
bytes of the message to the current contents of the register. Only the eight bits of data in each character are used for generating the
CRC. Start and stop bits and the parity bit, do not apply to the CRC.

Modbus.org
12/02/02

http://www.modbus.org/

14/44

MODBUS over serial line specification and implementation guide V1.0

MODBUS.ORG

During generation of the CRC, each 8–bit character is exclusive ORed with the register contents. Then the result is shifted in the
direction of the least significant bit (LSB), with a zero filled into the most significant bit (MSB) position. The LSB is extracted and
examined. If the LSB was a 1, the register is then exclusive ORed with a preset, fixed value. If the LSB was a 0, no exclusive OR takes
place.
This process is repeated until eight shifts have been performed. After the last (eight) shift, the next 8–bit byte is exclusive ORed with
the register’s current value, and the process repeats for eight more shifts as described above. The final content of the register, after all
the bytes of the message have been applied, is the CRC value.
When the CRC is appended to the message, the low-order byte is appended first, followed by the high-order byte. A detailed example
of CRC generation is contained in Appendix B.

Modbus.org
12/02/02

http://www.modbus.org/

15/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

2.5.2

The ASCII Transmission Mode

When devices are setup to communicate on a MODBUS serial line using ASCII (American Standard Code for Information
Interchange) mode, each 8–bit byte in a message is sent as two ASCII characters. This mode is used when the physical
communication link or the capabilities of the device does not allow the conformance with RTU mode requirements regarding timers
management.
Remark : this mode is less efficient than RTU since each byte needs two characters.
Example : The byte 0X5B is encoded as two characters : 0x35 and 0x42 ( 0x35 = " 5 " , and 0x42 = " B " in ASCII ).
The format for each byte ( 10 bits) in ASCII mode is :
Coding System:
Bits per Byte:

Hexadecimal, ASCII characters 0–9, A–F
One hexadecimal character contains 4-bits of data within each ASCII character of the message
1 start bit
7 data bits, least significant bit sent first
1 bit for parity completion;
1 stop bit

Even parity is required, other modes ( odd parity, no parity ) may also be used. In order to ensure a maximum compatibility with
other products, it is recommended to support also No parity mode. The default parity mode must be Even parity.
Remark : the use of no parity requires 2 stop bits.

How Characters are Transmitted Serially :
Each character or byte is sent in this order (left to right):
Least Significant Bit (LSB) . . . Most Significant Bit (MSB)
With Parity Checking
Start

1

2

3

Figure 15:

4

5

6

7

Par Stop

Bit Sequence in ASCII mode

Devices may accept by configuration either Even, Odd, or No Parity checking. If No Parity is implemented, an additional stop bit is
transmitted to fill out the character frame :

Without Parity Checking
Start

Figure 16:
Frame Checking Field:

Modbus.org
12/02/02

1

2

3

4

5

6

7

Stop Stop

Bit Sequence in ASCII mode (specific case of No Parity)

Longitudinal Redundancy Checking (LRC)

http://www.modbus.org/

16/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

2.5.2.1

MODBUS Message ASCII Framing

A MODBUS message is placed by the transmitting device into a frame that has a known beginning and ending point. This allows
devices that receive a new frame to begin at the start of the message, and to know when the message is completed. Partial
messages must be detected and errors must be set as a result.
The address field of a message frame contains two characters.
In ASCII mode, a message is delimited by specific characters as Start-of-frames and End-of-frames. A message must start with a
‘colon’ ( : ) character (ASCII 3A hex), and end with a ‘carriage return – line feed’ (CRLF) pair (ASCII 0D and 0A hex).
Remark : The LF character can be changed using a specific MODBUS application command ( see MODBUS application protocol
specification).
The allowable characters transmitted for all other fields are hexadecimal 0–9, A–F (ASCII coded). The devices monitor the bus
continuously for the ‘colon’ character. When this character is received, each device decodes the next character until it detects the
End-Of-Frame.
Intervals of up to one second may elapse between characters within the message. Unless the user has configured a longer timeout,
an interval greater than 1 second means an error has occurred. Some Wide-Area-Network application may require a timeout in the 4
to 5 second range.
A typical message frame is shown below.

Start
1 char
:

Address
2 chars

Function
2 chars

Data

LRC
2 chars

0 up to 2x252 char(s)

Figure 17:

End
2 chars
CR,LF

ASCII Message Frame

Remark : Each data byte needs two characters for encoding. Thus, to ensure compatibility at MODBUS application level between
ASCII mode and RTU mode, the maximum data size for ASCII data field (2x252) is the double the maximum data size for RTU data
field (252). Consequently, the maximum size of a MODBUS ASCII frame is 513 characters.
The ASCII framing requirements are synthesized in the following state diagram. Both " master " and " slave " points of view are
expressed in the same drawing :
Reception of " : "
character / Empty
reception buffer

Reception of " : "
character

Idle

Sending of “LF”

Reception

(ready to receive or to emit)

Reception of character
/ Concatenation of
character into
reception buffer

Emission Demand

Emission
start

Reception of " LF " character
/ control frame (LRC, Parity,
Slave addr.)

Comment
If frame OK
processing frame
If frame NOK
delete entire frame

Sending of “:”

Emission

Reception of " CR "
character

Waiting " End
of Frame "

Reception of " : "
character / Empty
reception buffer

Sending of
all characters
Sending of “CR”

Emission End

Figure 18:

Modbus.org
12/02/02

ASCII Transmission mode State diagram

http://www.modbus.org/

17/44

MODBUS over serial line specification and implementation guide V1.0

MODBUS.ORG

Some explanations about the above state diagram :
" Idle " state is the normal state when neither emission nor reception is active.
Each reception of a " : " character means a beginning of a new message. If a message was in process of reception while receiving
such a character, the current message is declared incomplete and it is discarded. A new reception buffer is then allocated.
After detection of the end of frame, the LRC calculation and checking is completed. Afterwards the address field is analyzed to
determine if the frame is for the device. If not the frame is discarded. In order to reduce the reception processing time the
address field can be analyzed as soon as it is reserved without waiting the end of frame.

2.5.2.2

LRC Checking

In ASCII mode, messages include an error–checking field that is based on a Longitudinal Redundancy Checking (LRC) calculation
that is performed on the message contents, exclusive of the beginning ‘colon’ and terminating CRLF pair characters. It is applied
regardless of any parity checking method used for the individual characters of the message.
The LRC field is one byte, containing an 8–bit binary value. The LRC value is calculated by the device that emits, which appends the
LRC to the message. The device that receives calculates an LRC during receipt of the message, and compares the calculated value
to the actual value it received in the LRC field. If the two values are not equal, an error results.
The LRC is calculated by adding together successive 8–bit bytes of the message, discarding any carries, and then two’s
complementing the result. It is performed on the ASCII message field contents excluding the ‘colon’ character that begins the
message, and excluding the CRLF pair at the end of the message. In ASCII mode, the resulting LRC is ASCII encoded into two bytes
and placed at the end of ASCII mode frame prior to the CRLF.
A detailed example of LRC generation is contained in Appendix B.

Modbus.org
12/02/02

http://www.modbus.org/

18/44

MODBUS over serial line specification and implementation guide V1.0

2.6

MODBUS.ORG

Error Checking Methods

The security of standard MODBUS Serial Line is based on two kinds of error checking :
Parity checking (even or odd) should be applied to each character.
Frame checking (LRC or CRC) must be applied to the entire message.
Both the character checking and message frame checking are generated in the device (master or slave) that emits and applied to the
message contents before transmission. The device (slave or master) checks each character and the entire message frame during
receipt.
The master is configured by the user to wait for a predetermined timeout interval ( Response time-out) before aborting the transaction.
This interval is set to be long enough for any slave to respond normally ( unicast request). If the slave detects a transmission error, the
message will not be acted upon. The slave will not construct a response to the master. Thus the timeout will expire and allow the
master’s program to handle the error. Note that a message addressed to a nonexistent slave device will also cause a timeout.

2.6.1

Parity Checking

Users may configure devices for Even ( required) or Odd Parity checking, or for No Parity checking ( recommended). This will
determine how the parity bit will be set in each character.
If either Even or Odd Parity is specified, the quantity of 1 bits will be counted in the data portion of each character (seven data bits for
ASCII mode, or eight for RTU). The parity bit will then be set to a 0 or 1 to result in an Even or Odd total of 1 bits.
For example, these eight data bits are contained in an RTU character frame:
1100 0101
The total quantity of 1 bits in the frame is four. If Even Parity is used, the frame’s parity bit will be a 0, making the total quantity of 1 bits
still an even number (four). If Odd Parity is used, the parity bit will be a 1, making an odd quantity (five).
When the message is transmitted, the parity bit is calculated and applied to the frame of each character. The device that receives
counts the quantity of 1 bits and sets an error if they are not the same as configured for that device (all devices on the MODBUS Serial
Line must be configured to use the same parity checking method).
Note that parity checking can only detect an error if an odd number of bits are picked up or dropped in a character frame during
transmission. For example, if Odd Parity checking is employed, and two 1 bits are dropped from a character containing three 1 bits,
the result is still an odd count of 1 bits.
If No Parity checking is specified, no parity bit is transmitted and no parity checking can be made. An additional stop bit is transmitted
to fill out the character frame.

2.6.2

Frame Checking

Two kinds of frame checking is used depending on the transmission mode, RTU or ASCII.
In RTU mode, messages include an error–checking field that is based on a Cyclical Redundancy Checking (CRC) method. The
CRC field checks the contents of the entire message. It is applied regardless of any parity checking method used for the individual
characters of the message.
In ASCII mode, messages include an error–checking field that is based on a Longitudinal Redundancy Checking (LRC) method.
The LRC field checks the contents of the message, exclusive of the beginning ‘colon’ and ending CRLF pair. It is applied
regardless of any parity checking method used for the individual characters of the message.
The detailed information about error checking methods is contained in the previous sections.

Modbus.org
12/02/02

http://www.modbus.org/

19/44

MODBUS over serial line specification and implementation guide V1.0

3
3.1

MODBUS.ORG

Physical Layer
Preamble

A new MODBUS solution over serial line should implement an electrical interface in accordance with EIA/TIA-485 standard ( also
known as RS485 standard). This standard allows point to point and multipoint systems, in a “two-wire configuration”. In addition, some
devices may implement a “Four-Wire” RS485-Interface.
A device may also implement an RS232-Interface.

In such a MODBUS system, a Master Device and one or several Slave Devices communicate on a passive serial line.
On standard MODBUS system, all the devices are connected (in parallel) on a trunk cable constituted by 3 conductors. Two of those
conductors ( the “Two-Wire” configuration ) form a balanced twisted pair, on which bi-directional data are transmitted, typically at the
bit rate of 9600 bits per second.
Each device may be connected ( see figure 19):
-

either directly on the trunk cable, forming a daisy-chain,

-

either on a passive Tap with a derivation cable,

-

either on an active Tap with a specific cable.

Screw Terminals, RJ45, or D-shell 9 connectors may be used on devices to connect cables (see the chapter “Mechanical Interfaces”).

3.2

Data Signaling Rates

9600 bps and 19.2 Kbps are required and 19.2 is the required default
Other baud rates may optionally be implemented : 1200, 2400, 4800, … 38400 bps, 56 Kbps, 115 Kbps, …
Every implemented baud rate must be respected better than 1% in transmission situation, and must accept an error of 2% in reception
situation.

Modbus.org
12/02/02

http://www.modbus.org/

20/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

3.3
3.3.1

Electrical Interfaces
Multipoint Serial Bus Infrastructure

Figure 19 gives a general overview of the serial bus infrastructure in a MODBUS multipoint Serial Line system.

Master

D
R

IDv
Passive TAP

ActiveTap

ITr
ITr

ITr

LT

D

Passive TAP

R

LT

IDv
AUI

R
D

R
D

Slave n
Slave 1

Slave 2

Figure 19 : Serial bus infrastructure

A multipoint MODBUS Serial Line bus is made of a principal cable (the Trunk), and possibly some derivation cables.
Line terminations are necessary at each extremity of the trunk cable for impedance adaptation (see § " Two-Wire MODBUS Definition "
& " Optional Four-Wire MODBUS Definition " for details).
As shown in figure 19, different implementations may operate in the same MODBUS Serial Line system :
the device integrates the communication transceiver and is connected to the trunk using a Passive Tap and a derivation cable
( case of Slave 1 and Master ) ;
the device doesn't integrate the communication transceiver and is connected to the trunk using an Active Tap and a derivation
cable (the active TAP integrates the transceiver)
( case of Slave 2 ) ;
the device is connected directly to the trunk cable, in a Daisy-Chain ( case of Slave n )
The following conventions are adopted :
The interface with the trunk is named ITr (Trunk Interface)
The interface between the device and the Passive Tap is named IDv (Derivation Interface)
The interface between the device and the Active Tap is named AUI (Attachment Unit Interface)
Remarks :
1. In some cases, the Tap may be connected directly to the IDv-socket or the AUI-socket of the device, without using a derivation
cable.
2. A Tap may have several IDv sockets to connect several devices. Such a Tap is named Distributor when it is a passive one.
3. When using an active Tap, power supply of the Tap may be provided either via its AUI or ITr interface.
ITr and IDv interfaces are described in the following chapters (see § " Two-Wire MODBUS DEFINITION " & " Four-Wire MODBUS
DEFINITION " ).

Modbus.org
12/02/02

http://www.modbus.org/

21/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

3.3.2

Two-Wire MODBUS Definition

A MODBUS solution over serial line should implement a “Two-Wire” electrical interface in accordance with EIA/TIA-485 standard.
On such a 2W-bus, at any time one driver only has the right for transmitting.
In fact a third conductor must also interconnect all the devices of the bus : the common.

Master
5V
D

R

Pull Up

D1
Balanced Pair

LT

LT

D0
Pull Down

Common

R

R
D

D

Slave n

Slave 1

Figure 20:

General 2-Wire Topology

2W-MODBUS Circuits Definition
Required Circuits
on ITr

on IDv

For
device

Required
on device

EIA/TIA-485
name

D1

D1

I/O

X

B/B’

D0

D0

I/O

X

A/A’

Common

Common

--

X

C/C’

Description
Transceiver terminal 1, V1 Voltage
( V1 & gt; V0 for binary 1 [OFF] state )
Transceiver terminal 0, V0 Voltage
( V0 & gt; V1 for binary 0 [ON] state )
Signal and optional Power Supply Common

Notes :


For Line Termination (LT), Pull Up and Pull Down resistors, please refer to section “Multipoint System requirements " .



D0, D1, and Common circuit names must be used in the documentation related to the device and the Tap ( User Guide, Cabling
Guide, … ) to facilitate interoperability.



Optional electrical interfaces may be added, for example :
Power Supply :

5..24 V D.C.

Port mode control : PMC circuit ( TTL compatible ). When needed, port mode may be controlled either by this external
circuit and/or by another way (a switch on the device for example). In the first case while an open circuit PMC will ask for the
2W-MODBUS mode, a Low level on PMC will switch the port into 4W-MODBUS or RS232-MODBUS Mode, depending on the
implementation.

Modbus.org
12/02/02

http://www.modbus.org/

22/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

3.3.3

Optional Four-Wire MODBUS Definition

Optionally, such MODBUS devices also permit to implement a 2-pair bus (4 wires) of mono directional data. The data on the master
pair ( RXD1-RXD0 ) are only received by the slaves ; the data on the slave pair ( TXD1-TXD0 ) are only received by the only master.
In fact a fifth conductor must also interconnect all the devices of the 4W-bus : the common.
In the same way as on a 2W-MODBUS, at any time one driver only has the right for emitting.
Such a device must implement, for each balanced pair, a driver and a transceiver in accordance with EIA/ TIA-485.
( Sometimes this solution has been named “RS422”, which is not correct : the RS422 standard does not support several drivers on
one balanced pair.)
M a s te r
D

5 V

R

P u ll U p

TXD1
LT

LT

S la v e P a ir
TXD0

5 V
P u ll D o w n
P u ll U p

R XD1
LT

LT

M a s te r P a ir
R XD0
P u ll D o w n

Com m on

R

R

D

D

S la v e 1

S la v e n

Figure 21:

General 4-wire topology

Optional 4W-MODBUS Circuits Definition
Required Circuits
on ITr

on IDv

For
device

TXD1

TXD1

Out

Out

Required
on device

EIA/TIA-485
name

X

B

X

A

(1)

B’

Generator terminal 1, Vb Voltage
( Vb & gt; Va for binary 1 [OFF] state )

TXD0

TXD0

RXD1

RXD1

RXD0

RXD0

In

(1)

A’

Common

Common

--

X

C/C’

In

Description for IDv

Generator terminal 0, Va Voltage
( Va & gt; Vb for binary 0 [ON] state )
Receiver terminal 1, Vb’ Voltage
( Vb’ & gt; Va’ for binary 1 [OFF] state )
Receiver terminal 0, Va’ Voltage
( Va’ & gt; Vb’ for binary 0 [ON] state )
Signal and optional Power Supply Common

Notes :


For Line Termination (LT), Pull Up and Pull Down resistors, please refer to section “Multipoint System requirements " .



Those circuits (1) are required only if an 4W-MODBUS option is implemented.



The name of the 5 required circuits must be used in the documentation related to the device and the Tap ( User Guide, Cabling
Guide, … ) to facilitate interoperability.



Optional electrical interfaces may be added, for example :
Power Supply :

5..24 V D.C.

PMC circuit : See above ( In 2W-MODBUS Circuits Definition ) the note about this optional circuit.

Modbus.org
12/02/02

http://www.modbus.org/

23/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

3.3.3.1

4W-Cabling System Important Topic

In such a 4W-MODBUS, Master Device and Slave Devices have IDv interfaces with the same 5 required circuits.
As the master has to :
-

receive from the slave the data on the slave pair ( TXD1-TXD0 ),

-

and transmit on the master pair ( RXD1-RXD0 , received by the slaves) ,

the 4W-cabling system must cross the two pairs of the bus between ITr and the IDv of the master :

Signal on Master IDv

EIA/TIA-485

Circuit on ITr

Name

Type

Name

RXD1

In

B’

TXD1

RXD0

In

A’

TXD0

TXD1

Out

B

RXD1

TXD0

Out

A

RXD0

Common

--

C/C’

Common

Slave Pair

Master Pair

This crossing may be implemented by crossed cables, but the connection of such crossed cables in a 2-wire system may cause
damages. To connect a 4W master device ( which have a MODBUS connector) a better solution is to use a Tap which includes the
crossing function.

3.3.3.2

Compatibility between 4-Wire and 2-Wire cabling

In order to connect devices implementing a 2-Wire physical interface to an already existing 4-Wire system, the 4-Wire cabling system
can be modified as described below :
TxD0 signal shall be wired with the RxD0 signal, turning them to the D0 signal
TxD1 signal shall be wired with the RxD1 signal, turning them to the D1 signal.
Pull-up, Pull-down and line terminations resistors shall be re-arranged to correctly adapt the D0, D1 signals.

Modbus.org
12/02/02

http://www.modbus.org/

24/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

The figure hereafter gives an example where slaves 2 and 3 which use a 2-Wire interface can operate with the Master and the slave 1
which use a 4-Wire interface.

M a s te r
D

5 V

R

P u ll U p

TXD1
LT

TXD0
P u ll D o w n

R XD1
LT

R XD0
Com m on

R

R

D

R

D

S la v e 1

D

S la v e 2

S la v e 3

Figure 22 : Changing a 4-Wire cabling system into a 2-Wire cabling system

In order to connect devices implementing a 4-Wire physical interface to an already existing 2-Wire system, the 4-Wire interface of the
new coming devices can be arranged as describe below :
On each 4-Wire device interface :
TxD0 signal shall be wired with the RxD0 signal and then connected to the D0 signal of the trunk ;
TxD1 signal shall be wired with the RxD1 signal and then connected to the D1 signal of the trunk.
The figure hereafter gives an example where slaves 2 and 3 which use a 4-Wire interface can operate with the Master and the slave 1
which use a 2-Wire interface.

Master
5V
D

R

Pull Up

D1
Balanced Pair

LT

LT

D0
Pull Down

Common

R
D

Slave 1

R

R
D

Slave 2

D

Slave 3

Figure 23 : Connecting devices with 4-Wire interface to a 2-Wire cabling system

Modbus.org
12/02/02

http://www.modbus.org/

25/44

MODBUS over serial line specification and implementation guide V1.0

3.3.4

MODBUS.ORG

RS232-MODBUS Definition

Some devices may implement an RS232-Interface between a DCE and a DTE.
Optional RS232-MODBUS Circuits Definition
For DCE

Required
on DCE (1)

Required
on DTE (1)

Common

--

X

X

CTS

In

Clear to Send

DCD

--

Data Carrier Detected ( from DCE to DTE )

DSR

In

Data Set Ready

DTR

Out

Data Terminal Ready

RTS

Out

Request to Send

Signal

Description
Signal Common

RXD

In

X

X

Received Data

TXD

Out

X

X

Transmitted Data

Notes :


“X” marked signals are required only if an RS232-MODBUS option is implemented.



Signals are in accordance with EIA/ TIA-232.



Each TXD must be wired with RXD of the other device ;



RTS may be wired with CTS of the other device,



DTR may be wired with DSR of the other device.



Optional electrical interfaces may be added, for example :
Power Supply :
PMC circuit :

3.3.5

5..24 V D.C.
See above ( In 2W-MODBUS Circuits Definition ) the note about this optional circuit.

RS232-MODBUS requirements

This optional MODBUS on Serial Line system should only be used for short length ( typically less than 20m ) point to point interconnection.
Then, the EIA/TIA-232 standard must be respected :


circuits definition,



maximum wire capacitance to ground ( 2500 pF, then 25 m for a 100 pF/m cable ).

Please refer to chapter “Cables” for the shield, and for the possibility to use Category 5 Cables.
Documentation of the device must indicate :


if the device must be considered as a DCE either as a DTE,



how optional circuits must work if such is the case.

Modbus.org
12/02/02

http://www.modbus.org/

26/44

MODBUS over serial line specification and implementation guide V1.0

3.4

MODBUS.ORG

Multipoint System requirements

For any EIA/ TIA-485 multipoint system, in either 2-wire or 4-wire configuration, the following requirements all apply.

3.4.1

Maximum number of devices without repeater

A figure of 32 devices is always authorized on any RS485-MODBUS system without repeater.
Depending of :
- all the possible addresses,
- the figure of RS485 Unit Load used by the devices,
- and the line polarization in need be,
A RS485 system may implement a larger number of devices. Some devices allow the implementation of a RS485-MODBUS serial line
with more than 32 devices, without repeater.
In this case these MODBUS devices must be documented to say how many of such devices are authorized without repeater.
The use of a repeater between two heavy loaded RS485-MODBUS is also possible.

3.4.2

Topology

An RS485-MODBUS configuration without repeater has one trunk cable, along which devices are connected, directly (daisy chaining)
or by short derivation cables.
The trunk cable, also named “Bus”, can be long (see hereafter). Its two ends must be connected on Line Terminations.
The use of repeaters between several RS485-MODBUS is also possible.

3.4.3

Length

The end to end length of the trunk cable must be limited. The maximum length depends on the baud rate, the cable (Gauge,
Capacitance or Characteristic Impedance), the number of loads on the daisy chain, and the network configuration (2-wire or 4-wire).
For a maximum 9600 Baud Rate and AWG26 (or wider) gauge, the maximum length is 1000m. In the specific case shown in the figure
22 ( 4 Wire cabling used as a 2 Wire cabling system) the maximum length must be divided by two.
The derivations must be short, never more than 20m. If a multi-port tap is used with n derivations, each one must respect a maximum
length of 40m divided by n.

3.4.4

Grounding Arrangements

The « Common » circuit ( Signal and optional Power Supply Common ) must be connected directly to protective ground, preferably at
one point only for the entire bus. Generally this point is to choose on the master device or on its Tap.

3.4.5

Line Termination

A reflection in a transmission line is the result of an impedance discontinuity that a travelling wave sees as it propagates down the line.
To minimize the reflections from the end of the RS485-cable it is required to place a Line Termination near each of the 2 Ends of the
Bus.
It is important that the line be terminated at both ends since the propagation is bi-directional, but it is not allowed to place more than 2
LT on one passive D0-D1 balanced pair . Never place any LT on a derivation cable.

Modbus.org
12/02/02

http://www.modbus.org/

27/44

MODBUS over serial line specification and implementation guide V1.0

MODBUS.ORG

Each line termination must be connected between the two conductors of the balanced line : D0 and D1.
Line termination may be a 150 ohms value ( 0.5 W ) resistor.
A serial capacitor ( 1 nF, 10 V minimum ) with a 120 Ohms ( 0.25 W ) resistor is a better choice when a polarization of the pair must
be implemented (see here after).
In a 4W-system, each pair must be terminated at each end of the bus.
In an RS232 interconnections, no termination should be wired.

3.4.6

Line Polarization

When there is no data activity on an RS-485 balanced pair, the lines are not driven and, thus susceptible to external noise or
interference. To insure that its receiver stays in a constant state, when no data signal is present, some devices need to bias the
network.
Each MODBUS device must be documented to say :
-

if the device needs a line polarization,

-

if the device implements, or can implement, such a line polarization.

If one or several devices need polarization, one pair of resistors must be connected on the RS-485 balanced pair :
-

a Pull-Up Resistor to a 5V Voltage on D1 circuit,

-

a Pull-Down Resistor to the common circuit on D0 circuit.

The value of those resistors must be between 450 Ohms and 650 Ohms. 650 Ohms resistors value may allow a higher number of
devices on the serial line bus.
In this case, a polarization of the pair must be implemented at one location for the whole Serial Bus. Generally this point is to
choose on the master device or on its Tap. Other devices must not implement any polarization.
The maximum number of devices authorized on such a MODBUS Serial Line is reduced by 4 from a MODBUS without polarization.

Modbus.org
12/02/02

http://www.modbus.org/

28/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

3.5

Mechanical Interfaces

Screw Terminals may be used for both IDv and ITr connections. All information must be provided to the users about the exact
location of each signal, with names in accordance with the previous chapter “Electrical Interface”.
If a RJ45 ( or a mini-DIN or a D-Shell) connector is used on an equipment for a MODBUS mechanical interface, a shielded female
connector must be chosen. Then the cable-end must have a shielded male connector.

3.5.1

Connectors pin-out for 2W-MODBUS
Device side - female connector

Common
D0
D1

Figure 24:

2W- MODBUS on RJ45 connector ( required pin-out )

Female (Front view)
5

4
9

3
8

2
7

Male (Front view)
1

1

6

Figure 25:

2
6

3
7

4
8

5
9

D-shell 9-pin connector

Screw type connectors can also be used.
If an RJ45 or a 9-pin D-shell connector is used for a standard MODBUS device, the pinouts hereafter must be respected for every
implemented circuit.
2W-MODBUS RJ45 and 9-pin D-shell Pinouts
Pin on Pin on
RJ45 D9-shell

Level of
requirement

IDv

ITr

Circuit

Circuit

EIA/TIA485 name

Description for IDv

3

3

optional

PMC

--

--

4

5

required

D1

D1

B/B’

Transceiver terminal 1, V1 Voltage
( V1 & gt; V0 for binary 1 [OFF] state )

5

9

required

D0

D0

A/A’

Transceiver terminal 0, V0 Voltage
( V0 & gt; V1 for binary 0 [ON] state )

7

2

recommended

VP

--

--

Positive 5...24 V D.C. Power Supply

8

1

required

Common

Common

C/C’

Signal and Power Supply Common

Modbus.org
12/02/02

Port Mode Control

http://www.modbus.org/

29/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

3.5.2

Connectors pin-out for optional 4W-MODBUS
Device side - female connector

Common
TXD0
TXD1
RXD1
RXD0

Figure 26:

4W- MODBUS on RJ45 connector ( required pin-out )

Female (Front view)
5

4
9

3
8

2
7

Male (Front view)
1

1

6

Figure 27:

2
6

3
7

4
8

5
9

D-shell 9-pin connector

Screw type connectors can also be used.
If an RJ45 or a 9-pin D-shell connector is used for a 4W-MODBUS device, the pinouts hereafter must be respected for every
implemented circuit.
Optional 4W-MODBUS RJ45 and 9-pin D-shell Pinouts
Pin on Pin on
RJ45 D9-shell

Level of
requirement

IDv

ITr

Signal

Signal

EIA/TIA485 name

1

required

RXD0

RXD0

A’

2

4

required

RXD1

RXD1

B’

3

3

optional

PMC

--

--

4

5

required

TXD1

TXD1

B

5

9

required

TXD0

TXD0

A

7

2

recommended

VP

--

--

8

Note :

8

1

required

Common

Common

C/C’

Description for IDv
Receiver terminal 0, Va’ Voltage
( Va’ & gt; Vb’ for binary 0 [ON] state )
Receiver terminal 1, Vb’ Voltage
( Vb’ & gt; Va’ for binary 1 [OFF] state )
Port Mode Control
Generator terminal 1, Vb Voltage
( Vb & gt; Va for binary 1 [OFF] state )
Generator terminal 0, Va Voltage
( Va & gt; Vb for binary 0 [ON] state )
Positive 5...24 V DC Power Supply
Signal and Power Supply Common

When both 2 and 4-Wire configurations are implemented on the same port, the 4W notations must be used.

Modbus.org
12/02/02

http://www.modbus.org/

30/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

3.5.3

RJ45 and 9-pin D-shell Pinouts for optional RS232-MODBUS

If an RJ45 or a 9-pin D-shell connector is used for a RS232-MODBUS device, the pinouts hereafter must be respected for every
implemented circuit.

DCE
Underlined pins can be output
Pin on Pin on
RJ45 D9-shell

DTE

Circuit

Level of
requirement

Name

Description

Underlined pins can be output
RS232
Source
DTE

Level of
requirement

Pin on
RJ45

Pin on D9shell

required

2

3

1

2

required

TXD

Transmitted Data

2

3

required

RXD

Received Data

DCE

required

1

2

3

7

optional

CTS

Clear to Send

DCE

optional

6

8

6

8

optional

RTS

Request to Send

optional

3

7

8

5

required

Common

Signal Common

required

8

5

DTE
--

Important Note : Some DCE Pinouts are crossed with DTE Pinouts with the same name :
A directly pin to pin wired cable ( without any crossing ) must be used between one DTE
( a PC for example ) and a DCE (a PLC for example).

Modbus.org
12/02/02

http://www.modbus.org/

31/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

3.6

Cables

A MODBUS over Serial Line Cable must be shielded. At one end of each cable its shield must be connected to protective ground. If
a connector is used at this end, the shell of the connector is connected to the shield of the cable.
An RS485-MODBUS must use a balanced pair (for D0-D1) and a third wire (for the Common). In addition to that a second balanced
pair must be used in a 4W-MODBUS system (for RXD0-RXD1).
If a connectorized 4 pairs Category 5 Cable is used, please remember to the user in the User Guides :
“Connection of a crossed cable in a 2-wire MODBUS system may cause damages”.

To minimize errors in cabling, a Color Code is recommended for the wires in the RS485-MODBUS Cables :
Signal Names

Recommended Color

D1-TXD1

yellow

D0-TXD0

brown

Common

grey

4W ( Optional )

RXD0

white

4W ( Optional )

RXD1

blue

Figure 28:
Note :

Color code for RS485-MODBUS wires

Category 5 Cables use other colors.

For RS485-MODBUS, Wire Gauge must be chosen sufficiently wide to permit the maximum length ( 1000 m ). AWG 24 is always
sufficient for the MODBUS Data.
Category 5 cables may operate for RS485-MODBUS, to a maximum length of 600m.
For the balanced pairs used in an RS485-system, a Characteristic Impedance with a value higher than 100 Ohms may be preferred,
especially for 19200 and higher baud rates.

3.7

Visual Diagnosis

For a visual diagnosis, communication status and device status must be indicated by LEDs :
LED

Level of requirement

State

Recommended colour

Communication

required

Switched ON during frame reception or sending.

Yellow

( 2 LEDs for frame reception and frame sending, or 1 LED
for both purposes.)
Error

recommended

Switched ON : internal fault

Red

Flashing : Other faults (Communication fault or
configuration error)
Device status

Modbus.org
12/02/02

optional

Switched ON : device powered

http://www.modbus.org/

Green

32/44

MODBUS over serial line specification and implementation guide V1.0

4

MODBUS.ORG

Installation and Documentation

4.1

Installation

Product vendor should pay attention to give to the user of a MODBUS System or MODBUS Devices all useful information to
prevent them from any error in cabling or bad utilization of cabling accessories :
-

Some other Fieldbuses, CANopen for example, use the same connector types ( D-shell, RJ45…) .

-

Studies are conducted on Ethernet, with power supply on the same Balanced Pairs Cable.

-

Some Products use for I/O circuits the same connector types ( D-shell, RJ45…).

On these connectors, for the most part, no foolproofing is available (polarizing notch or other implementation) .

4.2

User Guide

The User Guide of any MODBUS Device or Cabling System Component must include in a non exhaustive manner one or two types of
information:

4.2.1

For any MODBUS Product :

The following information should be documented :
All the implemented requests.
The operating modes.
The visual diagnostics.
The reachable registers and supported function codes.
Installation rules.
The required information in the following sections should also be documented :


" Two-Wire MODBUS Definition " (to mention the Required Circuits) ;



" Optional Four-Wire MODBUS Definition " (to mention the Required Circuits) ;



" Line Polarization " (to mention a possible Need or an Implementation) ;



" Cables " (special care of crossed cables).
A specific indication relating to the devices addresses, is to be written in the form of an important warning :

" It is of great importance to ensure at the time of the procedure of devices addressing, that there is not two devices with the same
address. In such a case, an abnormal behavior of the whole serial bus can occur, the Master being then in the impossibility to
communicate with all present slaves on the bus. "
A " Getting Started " chapter is highly recommended, with the documented description of a typical application example, for an
easy start.

4.2.2

For a MODBUS Product with implemented Options :

The different optional parameters must be clearly detailed :







Optional serial Transmission mode ;
Optional Parity Checking ;
Optional Baud Rates ;
Optional Circuit(s) : Power Supply, Port Configuration ;
Optional Interface(s) ;
Maximum number of devices (without repeater) if greater than 32.

Modbus.org
12/02/02

http://www.modbus.org/

33/44

MODBUS over serial line specification and implementation guide V1.0

5

MODBUS.ORG

Implementation Classes

Each device on a MODBUS Serial Line must respect all the mandatory requirements of a same implementation class.
The following parameters are used to classify the MODBUS Serial Line devices :


Addressing



Broadcasting



Transmission mode



Baud rate



Character format



Electrical interface parameter

Two implementation classes are proposed, the Basic and the Regular classes.
The regular class must provide configuration capabilities.
BASIC
Addressing

Slave :

REGULAR
Master :

Default value

Same as Basic

-

-

configurable address to be able to address
from 1 to 247
a slave from address
1 to 247
Broadcast

Yes

Yes

Baud Rate

9600 ( 19200 is also recommended)

9600, 19200 + additional configurable
baud rates

19200
(if implemented,
else 9600)

Parity

EVEN

EVEN + possibility to configure NO and
ODD parity

EVEN

Mode

RTU

RTU + ASCII

RTU

Electrical Interface RS485 2W-cabling
or RS232

RS485 2W-cabling (and 4W-cabling as an RS485 2W-cabling
additional option)
or RS232

Connector Type

Modbus.org
12/02/02

RJ 45 ( recommended )

-

http://www.modbus.org/

34/44

MODBUS over serial line specification and implementation guide V1.0

6

MODBUS.ORG

Appendix

6.1

Appendix A - Management of Serial Line Diagnostic Counters

6.1.1

General description

MODBUS Serial Line defines a list of diagnostic counters to allow performance and error management.
These counters are accessible using the MODBUS application protocol and its Diagnostic function (function code 08).
Each counter can be get by a sub-function code bound to the counter number. All counters can be cleared using the sub-function
code 0x0A.
The format of the Diagnostic function is described in the MODBUS application protocol specification.
Herein is the list of diagnostics and associated sub-function codes supported by a serial line device.
Subfunction
code
Hex

Counter

Counters Name

number

Comments
(for diagram below)

Dec

0x0B

1

Return Bus Message Count

Quantity of messages that the remote device has detected on the
communications system since its last restart, clear counters operation,
or power–up. Messages with bad CRC are not taken into account.

0x0C

2

Return Bus Communication Error
Count

Quantity of CRC errors encountered by the remote device since its last
restart, clear counters operation, or power–up. In case of an error
detected on the character level, (overrun, parity error), or in case of a
message length & lt; 3 bytes, the receiving device is not able to calculate
the CRC. In such cases, this counter is also incremented.

0x0D

3

Return Slave Exception Error Count

Quantity of MODBUS exception error detected by the remote device
since its last restart, clear counters operation, or power–up. It
comprises also the error detected in broadcast messages even if an
exception message is not returned in this case.
Exception errors are described and listed in " MODBUS Application
Protocol Specification " document.

0xOE

4

Return Slave Message Count

Quantity of messages addressed to the remote device, including
broadcast messages, that the remote device has processed since its
last restart, clear counters operation, or power–up.

0x0F

5

Return Slave No Response Count

Quantity of messages received by the remote device for which it
returned no response (neither a normal response nor an exception
response), since its last restart, clear counters operation, or power–up.
Then, this counter counts the number of broadcast messages it has
received.

0x10

6

Return Slave NAK Count

Quantity of messages addressed to the remote device for which it
returned a Negative Acknowledge (NAK) exception response, since its
last restart, clear counters operation, or power–up. Exception
responses are described and listed in " MODBUS Application Protocol
Specification " document.

0x11

7

Return Slave Busy Count

Quantity of messages addressed to the remote device for which it
returned a Slave Device Busy exception response, since its last restart,
clear counters operation, or power–up. Exception responses are
described and listed in " MODBUS Application Protocol Specification "
document

0x12

8

Return Bus Character Overrun Count

Quantity of messages addressed to the remote device that it could not
handle due to a character overrun condition, since its last restart, clear
counters operation, or power–up. A character overrun is caused by data
characters arriving at the port faster than they can be stored, or by the
loss of a character due to a hardware malfunction.

Modbus.org
12/02/02

http://www.modbus.org/

35/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

6.1.2

Counters Management Diagram

The following diagrams describe when each previous counters must be incremented.
3

Rest
IDLE
reception

reception
reception max
255 characters
number
max
characters

CPT8 = CPT8 + 1

character overrun
error

end of frame detected
3 characters silence

YES

NO

error on at least
1 frame character
YES

length
& lt; 3 bytes

CRC incorrect

YES

NO

NO

CPT2 = CPT2 + 1

CPT1 = CPT1 +
CPT1 = CPT1 + 1 1
YES

YES
YES
CPT5 = CPT5 + 1

CPT5 = CPT5 + 1

slave
number 0

NO

CPT4 = CPT4 + 1
slave number
=0
YES

1

NO

slave number = 0
or
slave number = my slave
number

slave number
=
workstation slave
number

NO

NO

CPT4 = CPT4 + 1

YES

function code
not known

exception
n° 1

YES

CPT3 = CPT3 + 1

NO

length
incorrect

exception
n° 3

NO

YES

CPT3 = CPT3 + 1

addressing
incorrect

NO

YES

exception
n° 2

data
incorrect

NO

CPT3 = CPT3 + 1

exception
n° 3

2

CPT3 = CPT3 + 1

Modbus.org
12/02/02

http://www.modbus.org/

36/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

1
3
YES

function code
not known

YES

NO

function code
prohibited in
broadcasts

YES

NO

length
incorrect

YES

NO

addressing
incorrect

YES

NO

data
incorrect

NO

CPT3 = CPT3 + 1

2

2
3

application
processing

NO

YES
processing
error

CPT3 = CPT3 + 1

NO

YES
broadcast

broadcast

exception response

Modbus.org
12/02/02

NO

YES

http://www.modbus.org/

response

37/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

6.2

6.2.1

Appendix B - LRC/CRC Generation

LRC Generation

The Longitudinal Redundancy Checking (LRC) field is one byte, containing an 8–bit binary value. The LRC value is calculated by the
transmitting device, which appends the LRC to the message. The device that receives recalculates an LRC during receipt of the
message, and compares the calculated value to the actual value it received in the LRC field. If the two values are not equal, an error
results.
The LRC is calculated by adding together successive 8–bit bytes in the message, discarding any carries, and then two’s
complementing the result. The LRC is an 8–bit field, therefore each new addition of a character that would result in a value higher than
255 decimal simply ‘rolls over’ the field’s value through zero. Because there is no ninth bit, the carry is discarded automatically.
A procedure for generating an LRC is:
1.

Add all bytes in the message, excluding the starting ‘colon’ and ending CRLF. Add them into an 8–bit field, so that
carries will be discarded.

2.

Subtract the final field value from FF hex (all 1’s), to produce the ones–complement.

3.

Add 1 to produce the twos–complement.

Placing the LRC into the Message

When the 8–bit LRC (2 ASCII characters) is transmitted in the message, the high–order character will be transmitted first, followed by
the low–order character. For example, if the LRC value is 61 hex (0110 0001):

Colon

Addr

Func

Data
Count

Data

Data

Data

Data

LRC
Hi
" 6 "
0x36

Figure 29:

LRC
Lo

CR

LF

" 1 "
0x31

LRC Character Sequence

Example: an example of a C language function performing LRC generation is shown below.
The function takes two arguments:
unsigned char *auchMsg;

A pointer to the message buffer containing binary data to be used for generating the LRC,

unsigned short usDataLen; The quantity of bytes in the message buffer.
LRC Generation Function

static unsigned char LRC(auchMsg, usDataLen)

/* the function returns the LRC as a type unsigned char */

unsigned char *auchMsg ;

/* message to calculate LRC upon */

unsigned short usDataLen ;

/* quantity of bytes in message */

{
unsigned char uchLRC = 0 ;

/* LRC char initialized */

while (usDataLen––)

/* pass through message buffer */

uchLRC += *auchMsg++ ;

/* add buffer byte without carry */

return ((unsigned char)(–((char)uchLRC))) ;

/* return twos complement */

}

Modbus.org
12/02/02

http://www.modbus.org/

38/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

6.2.2

CRC Generation

The Cyclical Redundancy Checking (CRC) field is two bytes, containing a 16–bit binary value. The CRC value is calculated by the
transmitting device, which appends the CRC to the message. The device that receives recalculates a CRC during receipt of the
message, and compares the calculated value to the actual value it received in the CRC field. If the two values are not equal, an error
results.
The CRC is started by first preloading a 16–bit register to all 1’s. Then a process begins of applying successive 8–bit bytes of the
message to the current contents of the register. Only the eight bits of data in each character are used for generating the CRC. Start
and stop bits and the parity bit, do not apply to the CRC.
During generation of the CRC, each 8–bit character is exclusive ORed with the register contents. Then the result is shifted in the
direction of the least significant bit (LSB), with a zero filled into the most significant bit (MSB) position. The LSB is extracted and
examined. If the LSB was a 1, the register is then exclusive ORed with a preset, fixed value. If the LSB was a 0, no exclusive OR takes
place.
This process is repeated until eight shifts have been performed. After the last (eighth) shift, the next 8–bit character is exclusive ORed
with the register’s current value, and the process repeats for eight more shifts as described above. The final content of the register,
after all the characters of the message have been applied, is the CRC value.
A procedure for generating a CRC is:
1. Load a 16–bit register with FFFF hex (all 1’s). Call this the CRC register.
2. Exclusive OR the first 8–bit byte of the message with the low–order byte of the 16–bit CRC register, putting the result in the
CRC register.
3. Shift the CRC register one bit to the right (toward the LSB), zero–filling the MSB. Extract and examine the LSB.
4. (If the LSB was 0): Repeat Step 3 (another shift).
(If the LSB was 1): Exclusive OR the CRC register with the polynomial value 0xA001 (1010 0000 0000 0001).
5. Repeat Steps 3 and 4 until 8 shifts have been performed. When this is done, a complete 8–bit byte will have been
processed.
6. Repeat Steps 2 through 5 for the next 8–bit byte of the message. Continue doing this until all bytes have been processed.
7. The final content of the CRC register is the CRC value.
8. When the CRC is placed into the message, its upper and lower bytes must be swapped as described below.
Placing the CRC into the Message

When the 16–bit CRC (two 8–bit bytes) is transmitted in the message, the low-order byte will be transmitted first, followed by the highorder byte.
For example, if the CRC value is 1241 hex (0001 0010 0100 0001):

Func

Data
Count

Data

Figure 30:

Modbus.org
12/02/02

Data

Data

Data

CRC
Lo

CRC
Hi

0x41

Addr

0x12

CRC Byte Sequence

http://www.modbus.org/

39/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0
Calculation algorithm of the CRC 16
OxFFFF → CRC16

CRC16 XOR BYTE → CRC16

N=0

Move to the right CRC16

No

Yes
Carry over

CRC16 XOR POLY → CRC 16

N=N+1

No

Yes
N & gt; 7

No

Yes
End of message

Following BYTE

END

XOR = exclusive or
N = number of information bits
POLY = calculation polynomial of the CRC 16 = 1010 0000 0000 0001
(Generating polynomial = 1 + x2 + x 15 + x 16)
In the CRC 16, the 1st byte transmitted is the least significant one.

Modbus.org
12/02/02

http://www.modbus.org/

40/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0

Example of CRC calculation (frame 02 07)

CRC register initialization

1111

1111

1111

1111

XOR 1st character

0000

0000

0000

0000

1111

Flag to 1,

Flag to 1, XOR polynomial

1101

1111

1110|1

0000

0000

0001

1111

1111

1111

0110

1111

1111

1111|1

1010

Move 2

1111

1111

1101

XOR polynomial

1111

0111
1010

Move 1

0000

0000

0001

1100

1111

1111

1110

Move 3

0110

0111

1111

11100

Move 4

0011

0011

1111

11111

1010

0000

0000

0001

1001

0011

1111

1110

Move 5

0100

1001

1111

11110

Move 6

0010

0100

1111

11111

1010

0000

0000

0001

1000

0100

1111

1110

Move 7

0100

0010

0111

11110

Move 8

0010

0001

0011

11110

1010

0000

0000

0001

1000

0001

0011

1110

0000

0000

0000

0111

1000

0001

0011

1001

0100

0000

1001

11001

1010

0000

0000

0001
1101

XOR 2nd character
Move 1

1110

0000

1001

0111

0000

0100

11101

1010

0000

0000

0001

1101

0000

0100

1111

0110

1000

0010

01111

1010

0000

0000

0001

1100

1000

0010

0110

Move 4

0110

0100

0001

00110

Move 5

0011

0010

0000

10011

1010

0000

0000

0001

Move 2

Move 3

1001

0010

0000

1000

Move 6

0100

1001

0000

01000

Move 7

0010

0100

1000

00100

Move 8

0001

0010

0100

00010

Most significant

least significant

The CRC 16 of the frame is then: 4112

Modbus.org
12/02/02

http://www.modbus.org/

41/44

MODBUS over serial line specification and implementation guide V1.0

MODBUS.ORG

Example
An example of a C language function performing CRC generation is shown on the following pages. All of the possible CRC values are
preloaded into two arrays, which are simply indexed as the function increments through the message buffer. One array contains all of
the 256 possible CRC values for the high byte of the 16–bit CRC field, and the other array contains all of the values for the low byte.
Indexing the CRC in this way provides faster execution than would be achieved by calculating a new CRC value with each new
character from the message buffer.
Note: This function performs the swapping of the high/low CRC bytes internally. The bytes are already swapped in the CRC value that
is returned from the function.
Therefore the CRC value returned from the function can be directly placed into the message for transmission.
The function takes two arguments:
unsigned char *puchMsg;

A pointer to the message buffer containing binary data to be used for generating the CRC

unsigned short usDataLen;

The quantity of bytes in the message buffer.

CRC Generation Function

unsigned short CRC16 ( puchMsg, usDataLen )

/* The function returns the CRC as a unsigned short type */

unsigned char *puchMsg ;

/* message to calculate CRC upon

*/

unsigned short usDataLen ;

/* quantity of bytes in message

*/

/* high byte of CRC initialized

*/

unsigned char uchCRCLo = 0xFF ;

/* low byte of CRC initialized

*/

unsigned uIndex ;

/* will index into CRC lookup table

*/

while (usDataLen--)
{

/* pass through message buffer

*/

/* calculate the CRC

*/

{
unsigned char uchCRCHi = 0xFF ;

uIndex = uchCRCLo ^ *puchMsgg++ ;
uchCRCLo = uchCRCHi ^ auchCRCHi[uIndex} ;
uchCRCHi = auchCRCLo[uIndex] ;
}
return (uchCRCHi & lt; & lt; 8 | uchCRCLo) ;
}

Modbus.org
12/02/02

http://www.modbus.org/

42/44

MODBUS.ORG

MODBUS over serial line specification and implementation guide V1.0
High-Order Byte Table

/* Table of CRC values for high–order byte */
static unsigned char auchCRCHi[] = {
0x00, 0xC1, 0x81, 0x40, 0x01,
0x40, 0x01, 0xC0, 0x80, 0x41,
0x80, 0x41, 0x01, 0xC0, 0x80,
0xC0, 0x80, 0x41, 0x00, 0xC1,
0x00, 0xC1, 0x81, 0x40, 0x01,
0x40, 0x01, 0xC0, 0x80, 0x41,
0x80, 0x41, 0x00, 0xC1, 0x81,
0xC0, 0x80, 0x41, 0x00, 0xC1,
0x00, 0xC1, 0x81, 0x40, 0x01,
0x40, 0x00, 0xC1, 0x81, 0x40,
0x80, 0x41, 0x01, 0xC0, 0x80,
0xC0, 0x80, 0x41, 0x01, 0xC0,
0x00, 0xC1, 0x81, 0x40, 0x00,
0x40, 0x01, 0xC0, 0x80, 0x41,
0x80, 0x41, 0x00, 0xC1, 0x81,
0xC0, 0x80, 0x41, 0x00, 0xC1,
0x00, 0xC1, 0x81, 0x40, 0x01,
0x40

0xC0,
0x00,
0x41,
0x81,
0xC0,
0x00,
0x40,
0x81,
0xC0,
0x01,
0x41,
0x80,
0xC1,
0x01,
0x40,
0x81,
0xC0,

0x80,
0xC1,
0x00,
0x40,
0x80,
0xC1,
0x00,
0x40,
0x80,
0xC0,
0x00,
0x41,
0x81,
0xC0,
0x00,
0x40,
0x80,

0x41,
0x81,
0xC1,
0x01,
0x41,
0x81,
0xC1,
0x01,
0x41,
0x80,
0xC1,
0x00,
0x40,
0x80,
0xC1,
0x00,
0x41,

0x01,
0x40,
0x81,
0xC0,
0x00,
0x40,
0x81,
0xC0,
0x01,
0x41,
0x81,
0xC1,
0x01,
0x41,
0x81,
0xC1,
0x01,

0xC0,
0x00,
0x40,
0x80,
0xC1,
0x01,
0x40,
0x80,
0xC0,
0x00,
0x40,
0x81,
0xC0,
0x00,
0x40,
0x81,
0xC0,

0x80,
0xC1,
0x00,
0x41,
0x81,
0xC0,
0x01,
0x41,
0x80,
0xC1,
0x00,
0x40,
0x80,
0xC1,
0x01,
0x40,
0x80,

0x41,
0x81,
0xC1,
0x01,
0x40,
0x80,
0xC0,
0x00,
0x41,
0x81,
0xC1,
0x01,
0x41,
0x81,
0xC0,
0x01,
0x41,

0x00,
0x40,
0x81,
0xC0,
0x00,
0x41,
0x80,
0xC1,
0x00,
0x40,
0x81,
0xC0,
0x00,
0x40,
0x80,
0xC0,
0x00,

0xC1,
0x01,
0x40,
0x80,
0xC1,
0x01,
0x41,
0x81,
0xC1,
0x01,
0x40,
0x80,
0xC1,
0x01,
0x41,
0x80,
0xC1,

0x81,
0xC0,
0x01,
0x41,
0x81,
0xC0,
0x01,
0x40,
0x81,
0xC0,
0x01,
0x41,
0x81,
0xC0,
0x01,
0x41,
0x81,

0x03,
0x0F,
0xD9,
0xD5,
0x30,
0x3C,
0x38,
0xEC,
0x21,
0xA5,
0xAB,
0x7F,
0xB2,
0x96,
0x5E,
0x8A,
0x47,

0x02,
0xCF,
0x1B,
0x15,
0x31,
0xFC,
0x28,
0x2C,
0x20,
0x65,
0x69,
0xBF,
0xB3,
0x56,
0x5A,
0x4A,
0x46,

0xC2,
0xCE,
0xDB,
0xD7,
0xF1,
0xFD,
0xE8,
0xE4,
0xE0,
0x64,
0xA9,
0x7D,
0x73,
0x57,
0x9A,
0x4E,
0x86,

0xC6,
0x0E,
0xDA,
0x17,
0x33,
0x3D,
0xE9,
0x24,
0xA0,
0xA4,
0xA8,
0xBD,
0xB1,
0x97,
0x9B,
0x8E,
0x82,

0x06,
0x0A,
0x1A,
0x16,
0xF3,
0xFF,
0x29,
0x25,
0x60,
0x6C,
0x68,
0xBC,
0x71,
0x55,
0x5B,
0x8F,
0x42,

0x07,
0xCA,
0x1E,
0xD6,
0xF2,
0x3F,
0xEB,
0xE5,
0x61,
0xAC,
0x78,
0x7C,
0x70,
0x95,
0x99,
0x4F,
0x43,

0xC7,
0xCB,
0xDE,
0xD2,
0x32,
0x3E,
0x2B,
0x27,
0xA1,
0xAD,
0xB8,
0xB4,
0xB0,
0x94,
0x59,
0x8D,
0x83,

0x05,
0x0B,
0xDF,
0x12,
0x36,
0xFE,
0x2A,
0xE7,
0x63,
0x6D,
0xB9,
0x74,
0x50,
0x54,
0x58,
0x4D,
0x41,

0xC5,
0xC9,
0x1F,
0x13,
0xF6,
0xFA,
0xEA,
0xE6,
0xA3,
0xAF,
0x79,
0x75,
0x90,
0x9C,
0x98,
0x4C,
0x81,

0xC4,
0x09,
0xDD,
0xD3,
0xF7,
0x3A,
0xEE,
0x26,
0xA2,
0x6F,
0xBB,
0xB5,
0x91,
0x5C,
0x88,
0x8C,
0x80,

};
Low-Order Byte Table

/* Table of CRC values for low–order byte */
static char auchCRCLo[] = {
0x00, 0xC0, 0xC1, 0x01,
0x04, 0xCC, 0x0C, 0x0D,
0x08, 0xC8, 0xD8, 0x18,
0x1D, 0x1C, 0xDC, 0x14,
0x11, 0xD1, 0xD0, 0x10,
0x37, 0xF5, 0x35, 0x34,
0x3B, 0xFB, 0x39, 0xF9,
0x2E, 0x2F, 0xEF, 0x2D,
0x22, 0xE2, 0xE3, 0x23,
0x62, 0x66, 0xA6, 0xA7,
0x6E, 0xAE, 0xAA, 0x6A,
0x7B, 0x7A, 0xBA, 0xBE,
0x77, 0xB7, 0xB6, 0x76,
0x51, 0x93, 0x53, 0x52,
0x5D, 0x9D, 0x5F, 0x9F,
0x48, 0x49, 0x89, 0x4B,
0x44, 0x84, 0x85, 0x45,
0x40

0xC3,
0xCD,
0x19,
0xD4,
0xF0,
0xF4,
0xF8,
0xED,
0xE1,
0x67,
0x6B,
0x7E,
0x72,
0x92,
0x9E,
0x8B,
0x87,

};

Modbus.org
12/02/02

http://www.modbus.org/

43/44

MODBUS over serial line specification and implementation guide V1.0

6.3

MODBUS.ORG

Appendix E - References

ANSI/ TIA/ EIA-232-F-1997

Interface Between Data Terminal Equipment and Data Circuit-Terminating Equipment
Employing Serial Binary Data Interchange.

ANSI/ TIA/ EIA-485-A-1998

Electrical Characteristics of Generators and Receivers for Use in Balanced Digital Multipoint
Systems.

MODBUS.org

Modbus.org
12/02/02

MODBUS application protocol specification

http://www.modbus.org/

44/44


MODBUS_materiały.rar > radio kontrola z modbusem.pdf

Na prawach rekopisu
 

INSTYTUT CYBERNETYKI TECHNICZNEJ
POLITECHNIKI WROCŁAWSKIEJ
Raport serii SPR nr 19/2002

Komunikacja radiowa
z dwukołowym robotem mobilnym
Marek Wnuk

Słowa kluczowe: komunikacja radiowa, Modbus, robot mobilny, sterownik, oprogramowanie

Wrocław 2002

Spis tre´ ci
s
1 Układ do komunikacji radiowej z robotem
1.1 Moduł nadawczo–odbiorczy (transceiver) BiM2 . . . . . . . . . . . . . . . . . . . .
1.2 Konstrukcja modułu transmisji dla robota mobilnego . . . . . . . . . . . . . . . . .
1.3 Połaczenie układu ze sterownikiem robota . . . . . . . . . . . . . . . . . . . . . . .
 

2 Protok´ ł komunikacyjny MODBUS (Modicon)
o
2.1 Komunikacja w protokole MODBUS . . . . . . . . . . . .
2.2 Ramki protokołu MODBUS . . . . . . . . . . . . . . . .
2.3 Pola ramki MODBUS . . . . . . . . . . . . . . . . . . .
2.4 Przykłady ramek MODBUS . . . . . . . . . . . . . . . .
2.5 Kontrola poprawno´ci transmisji . . . . . . . . . . . . . .
s
2.6 Przystosowanie protokołu do potrzeb komunikacji radiowej

4
4
5
7

.
.
.
.
.
.

7
8
8
9
9
10
10

3 Oprogramowanie
3.1 Strona sterownika (slave) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.2 Strona komputera nadrzednego (master) . . . . . . . . . . . . . . . . . . . . . . . .

11
12
12

´
4 Uwagi koncowe

12

5 Dodatek A: Oprogramowanie sterownika

14

6 Dodatek B: Oprogramowanie PC

28

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

 

Spis rysunk´ w
o
1
2
3
4

Schemat blokowy modułu radiowego BiM2 firmy Radiometrix
Schemat ideowy układu transmisyjnego . . . . . . . . . . . .
Układ zmontowany na płytce uniwersalnej . . . . . . . . . . .
Transakcja w protokole MODBUS . . . . . . . . . . . . . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

5
6
6
8

Spis tablic
Sygnały złacza komunikacyjnego sterownika robota . . . . . . . . . . . . . . . . . .
Tablica kodowa do transmisji radiowej w protokole MODBUS . . . . . . . . . . . .
 

1
2

7
11

1 Układ do komunikacji radiowej z robotem
W laboratorium robotyki Instytutu Cybernetyki Technicznej skonstruowano stanowisko do badania
algorytm´ w sterowania obiektem nieholonomicznym. Obiektem tym jest dwukołowy robot mobilny
o
z napedem odniesionym do korpusu stanowiacego wahadło zawieszone na osi k´ ł [1], [2], [3].
o
W celu umo˙ liwienia w pełni autonomicznej pracy robota zaprojektowano i wykonano dwa moduły
z
z
zawierajace radiowe układy nadawczo-odbiorcze i układy logiczne umo˙ liwiajace połaczenie ich z
komputerem nadrzednym i sterownikiem robota. Zaproponowano r´ wnie˙ protok´ ł komunikacyjny
o
z
o
(MODBUS) i dokonano jego modyfikacji, niezbednych przy wykorzystywaniu transmisji radiowej.
Do budowy układu wybrano tranceiver BiM2-433-64S firmy Radiometrix [4], a prototypy zmontowano na płytkach uniwersalnych.
 

 

 

 

 

 

 

1.1 Moduł nadawczo–odbiorczy (transceiver) BiM2
BiM2 jest p´ łdupleksowym modułem nadawczo–odbiorczym przeznaczonym do szybkiej dwukieo
runkowej transmisji danych na niewielkie odległo´ci.
s
Podstawowe własno´ci:
s
certyfikat CE,
¡

zgodno´c ze standardem radiowym: ETSI EN 300-220-3,

¡

zgodno´c ze standardem EMC: ETSI EN 301-489-3,

¡

u˙ yteczny zasieg: do 200m (w budynkach do 50m),
z
¡

 

predko´c transmisji danych: do 64kb/s,

¡

 

nadajnik FM o mocy 10mW,
¡

odbiornik superheterodynowy FM z podw´ jnym przetwarzaniem,
o
¡

filtracja sygnału wej´ciowego i pełne ekranowanie,
s
¡

zasilanie: 5V/20mA,
¡

wymiary: 23x33x4mm.
¡

Schemat blokowy BiM2 przedstawiono na rys. 1.
Linia T X select włacza nadajnik (pełna moc 10mW jest osiagana po 100µs). Sygnał modulujacy
s
jest doprowadzany do wej´cia T X D (mo˙ na stosowa´ modulacje cyfrowa lub analogowa). Wyj´cie
s
z
c
stopnia mocy nadajnika jest podłaczane do wyprowadzenia antenowego przez szybki przełacznik i
filtr zapewniajacy zgodno´c z norma EN 300-220-3.

Cze´c odbiorcza BiM2 pracuje jako superheterodyna FM z podw´ jnym przetwarzaniem (16MHz i

o
150kHz). Odbiornik jest aktywowany linia RX select z op´ znieniem mniejszym od 1ms. Adaptao´
cyjny dyskryminator danych zapewnia dyskretyzacje sygnału odbieranego na poziomie jego sredniej
´
warto´ci (ze stała czasowa 1,2ms, a w wersji BiM2-433-64S – 150µs). Wyj´cie sygnału binarnego
s
s
(Data out) jest odtwarzane poprawnie tylko w przypadku przebieg´ w o wypełnieniu zbli˙ onym do
o
z
50% (np. kodowanie typu Manchester lub bi-fazowe). Dostepne jest r´ wnie˙ bezpo´rednie wyj´cie
o
z
s
s
sygnału analogowego (AF). Obecno´c fali no´nej jest sygnalizowana na wyj´ciu CD.

s
s
Producent zaleca stosowanie cwier´ falowej anteny pretowej (o długo´ci 155mm dla 433MHz).
´
c
s
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

4

 

Rysunek 1: Schemat blokowy modułu radiowego BiM2 firmy Radiometrix

1.2 Konstrukcja modułu transmisji dla robota mobilnego
W zaprojektowanym, wykonanym i przetestowanym układzie wykorzystano opisany wcze´niej moduł
s
BiM2-433-64S. Ze wzgledu na to, ze zachodzi potrzeba u˙ ycia pary moduł´ w radiowych, z kt´ rych
˙
z
o
o
jeden wsp´ łpracuje z komputerem klasy PC, a drugi – ze sterownikiem robota [2], układ opracoo
wano tak, by był uniwersalny. Złacze transmisji szeregowej PC (np. port COM2) pracuje z sygnałami w standardzie RS232C, co wymaga zastosowania po stronie modułu radiowego odpowiedniego konwertera poziom´ w elektrycznych. Wsp´ łpraca se sterownikiem robota odbywa sie na poo
o
ziomie standardowej logiki TTL, co pozwala na bezpo´rednie połaczenie. Układ konwersji TTL–
s
RS232C (MAX232) został zamontowany na podstawce, kt´ ra r´ wnocze´nie mo˙ e pełni´ role gniazda
o o
s
z
c
połaczeniowego dla portu szeregowego sterownika.
W przypadku PC do wysterowania sygnał´ w T X select i RX select wykorzystano sygnał RT S portu
o
s
o
szeregowego, a sygnał CD doprowadzono na wej´cie DCD. Zapewnia to naturalna obsługe sygnał´ w
portu szeregowego w PC, zgodna z wiekszo´cia protokoł´ w.
s
o
W przypadku sterownika robota do wysterowania sygnał´ w T X select i RX select wykorzystano wyj´cie
o
s
PE.5, a sygnał CD doprowadzono na wej´cie PF.1 mikrokontrolera MC68332.
s
Układ logiczny, zbudowany z bramek serii 74HCT, zapewnia wła´ciwe działanie modułu przy wykos
rzystaniu dw´ ch, opisanych wy˙ ej, sygnał´ w:
o
z
o
 

 

 

 

 

 

 

 

 

 

naprzemienne właczanie nadajnika i odbiornika,
¡

 

blokowanie sygnału CD przy właczonym nadajniku,
¡

 

blokowanie danych odbieranych przy braku fali no´nej z odbiornika.
s
¡

Dodatkowo, właczenie nadajnika (T X select) jest sygnalizowane dioda czerwona, a pojawienie sie
fali no´nej z odbiornika – dioda zielona.
s
Schemat ideowy układu przedstawiono na rys. 2. Ukaldy zmontowano na płytce uniwersalnej (rys. 3).
 

 

 

 

 

 

5

 

Vcc

Vcc

Yellow

Green

14
16

9

RXselect

1
6

8

8

10

7

11

14

12

Antenna

9

13

14

2
5
14

TXD

15

TXselect
2
11

CD
2

1

14
12

12

3

1

132

4

MAX232

13

14

5

6

132

11

RXD
14

10

BiM2-433-64S

Rysunek 2: Schemat ideowy układu transmisyjnego

Rysunek 3: Układ zmontowany na płytce uniwersalnej

6

DB9F

W celu zapewnienia autonomicznej pracy układu wsp´ łpracujacego z PC, wyposa˙ ono go w zasio
z
lacz stabilizowany zasilany z zewnetrznego transformatora zamontowanego we wtyku (tzw. walltransformer).
 

 

1.3 Połaczenie układu ze sterownikiem robota
 

W sterowniku dwukołowego robota mobilnego [2]do komunikacji z otoczeniem przeznaczono układ
szeregowej transmisji asynchronicznej (SCI - Serial Communicztion Interface [6]), dostepny w 68332.
Pozwala on przesyła´ dane i komendy pomiedzy sterownikiem autonomicznego robota a komputerem
c
nadrzednym.
 

 

 

Tablica 1: Sygnały złacza komunikacyjnego sterownika robota
¢

sygnał
5V

MAX232

przeznaczenie
zasilanie interfejsu i joystick-a

£

U joyX
GND
GND
U joyY

joystick, o´ x
s
masa
masa
joystick, o´ y
s

15

5V

16

zasilanie interfejsu i joystick-a

T xD
PE 5
PF 1
RxD

9
12
11
10

dane nadawane SCI
wyj´ cie do właczania nadawania (RT S)
s
wej´ cie do detekcji fali no´ nej (CD)
s
s
dane odbierane SCI
¢

¤

¤

£

DB15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Sygnały danych nadawanych (T xD) i odbieranych (RxD) oraz weej´cie (PF 1) i wyj´cie (PE 5) wys
s
prowadzono na złacze komunikacyjne Z2 typu DB15F (tablica 1) bez buforowania. Zasilanie odpowiednich interfejs´ w jest dostarczane przez złacze Z2. Sygnały logiczne i zasilajace sa doprowadzone
o
ze złacza sterownika robota przez wtyk właczony w jeden rzad postawki układu MAX232.
¥

¥

 

 

 

 

 

 

 

2 Protok´ ł komunikacyjny MODBUS (Modicon)
o
Protok´ ł MODBUS [5] jest rozpowszechnionym standardem komunikacji szeregowej w systemach
o
ontrolno–pomiarowych. Ze wzgledu na liczne zalety:
 

dostep do no´nika typu master – slave
s
¡

 

wykrywanie i sygnalizacja błed´ w
o
¡

 

potwierdzanie wykonania komend
¡

zabezpieczenie przed blokada
¡

 

mo˙ liwo´c transmisji znakowej RS232C, RS485 itp.
z

¡

został on r´ wnie˙ zastosowany w sterowniku dwukołowego robota mobilnego [2].
o
z
7

2.1 Komunikacja w protokole MODBUS
Komunikacja w protokole MODBUS [5] odbywa sie w trybie master – slave. Transakcje inicjuje
master przez wysłanie ramki zadania zawierajacej adres, kod funkcji, dane i sume kontrolna (rys. 4).
˙
 

 

 

 

 

 

MASTER

SLAVE
¦

adres
kod funkcji
dane
suma kontrolna

adres
kod funkcji
dane
suma kontrolna
§

Rysunek 4: Transakcja w protokole MODBUS

Jednostka podporzadkowana (slave) odsyła ramke odpowiedzi (skonstruowana podobnie). Czas oczekiwania na odpowied´ jest kontrolowany i w przypadku przekroczenia dopuszczalnej warto´ci (zale˙ nej
z
s
z
z
o c
od trybu protokołu) nastepuje przeterminowanie transakcji. Master mo˙ e w tej sytuacji powt´ rzy´ pytanie lub zasygnalizowa´ bład (timeout).
c
 

 

 

 

 

2.2 Ramki protokołu MODBUS
Ramki maja budowe zale˙ na od trybu protokołu. W trybie znakowym (ASCII) przez łacze szeregowe
z
sa przesyłane znaki ASCII. Adres, kod funkcji, dane i suma kontrolna sa przesyłane w postaci szesnastkowej. Znacznikiem poczatku ramki jest znak dwukropka, a koniec jest sygnalizowany znakami
ko´ ca linii.
n
W trybie binarnym (RTU) przesyłane sa bajty o´miobitowe. Adres, kod funkcji, dane i cykliczna suma
s
kontrolna (CRC) sa przesyłane binarnie. znacznikiem poczatku i ko´ ca ramki jest odstep czasowy
n
(cisza na linii transmisyjnej o odpowiednim czasie trwania).
 

 

 

 

 

 

 

 

 

 

 

 

Ramka w trybie znakowym (ASCII)
:

adres

kod f.

dane
...

suma

CR

LF

bajty sa wysyłane szesnastkowo (po dwa znaki ASCII)
¡

 

odstepy pomiedzy kolejnymi znakami ramki

1s

 

¨

¡

 

Ramka w trybie binarnym (RTU)
adres

kod f.

dane

suma

...
bajty sa wysyłane binarnie jako znaki o´miobitowe
s
¡

 

¡

 

¥

 

¨

8

1 5T

©

odstepy pomiedzy kolejnymi znakami ramki

3 5T (gdzie T oznacza czas transmisji
¥

ka˙ da ramka jest poprzedzona odstepem (cisza na linii)
z
jednego znaku)
 

¡

2.3

Pola ramki MODBUS

adres
0

1 – 247 –

adres rozgłaszania (broadcast)
adres jednostki slave

kod funkcji
odczyt wyj´c bitowych

odczyt wej´c bitowych

odczyt n rejestr´ w
o
odczyt n rejestr´ w wej´ciowych
o
s
zapis 1 bitu
zapis 1 rejestru
odczyt statusu
test diagnostyczny
zapis n bit´ w
o
zapis n rejestr´ w
o
identyfikacja urzadzenia slave
zarezerwowane na odpowiedzi błedne
 

 

1
$01
2
$02
3
$03
4
$04
5
$05
6
$06
7
$07
8
$08
15
$0F
16
$10
17
$11
128 – 255 $80–$FF

rejestry i zmienne
Urzadzenie jest widziane jako 16-bitowe rejestry Wn . Typy zmiennych umieszczanych w rejestrach:
 

bitowe
– bity rejestr´ w W0 W4095
o
2-bajtowe – całe rejestry Wn
4-bajtowe – sasiednie rejestry Wn : Wn


1

 



zalecenie
W celu ułatwienia przesyłania danych przy pomocy ramek z funkcja ”odczyt (zapis) n rejestr´ w”
o
rejestry powinny zajmowa´ sp´ jny obszar adresowany od 0 do re jmax .
c o
 

2.4 Przykłady ramek MODBUS
˙
o
zadanie (master): odczyt 2 rejestr´ w od W30 do W31
 

adres
slave
12

kod
fun. RAH
03
00

dane
RAL RNH
1E
00

RNL
02

suma
LRC
CB

odpowied´ (slave): dane z rejestr´ w od W30 do W31
z
o
adres
slave
12

kod
fun. NB W30H
03 04
01

dane
W30L W31H
23
02

odpowied´ (slave): bład – niedozwolony adres danych
z
 

adres
slave
12

kod dane
fun. kod
83
02
9

suma
LRC
69

W31L
34

suma
LRC
8D

2.5 Kontrola poprawno´ci transmisji
s
o
s
s
Wykrywanie błed´ w transmisji nastepuje dzieki kontroli parzysto´ci poprzecznej (bit parzysto´ci
znaku) i wzdłu˙ nej (LRC, CRC).
z
Wykrywanie i diagnozowanie błed´ w komunikacji nastepuje przez:
o
 

 

 

 

 

odesłanie przez slave ramki z kodem błedu:
¡

 

niedozwolona funkcja
niedozwolony zakres danych
niedozwolona warto´c danej

uszkodzenie w przyłaczonym urzadzeniu
potwierdzenie pozytywne
brak gotowo´ci, komunikat usuniety
s
potwierdzenie negatywne
s
bład parzysto´ci pamieci
 

 

 

 










 

01
02
03
04
05
06
07
08

przekroczenie czasu oczekiwania na odpowied´ (timeout w jednostce master) – slave nie odsyła
z
˙
odpowiedzi przy błedach w ramce zadania
 

¡

 

2.6 Przystosowanie protokołu do potrzeb komunikacji radiowej
Jednostka nadrzedna (master) jest komputer PC, a podporzadkowana (slave) – sterownik robota.
Przyjeto komunikacje asynchroniczna w trybie znakowym (ASCII). Zar´ wno master jak i slave
o
obsługuja minimalny podzbi´ r funkcji protokołu:
o
 

 

 

 

 

 

 

 

 

3 - Read N Registers,
¡

16 - Write N Registers,
¡

17 - Identify Slave.
¡

Zaimplementowano wyłacznie rejestry 16-bitowe reprezentowane przez zmienne całkowite.
Komunikacja znakowa wykorzystuje niewielki podzbi´ r znak´ w kodu ASCII:
o
o
 

dwukropek - ”:” - znacznik poczatku ramki,
¡

 

cyfry szesnastkowe - ”0 .. 9, A .. F” - w polach numerycznych ramki,
i
¨

©

CR

LF

- znacznik ko´ ca ramki.
n
©

¨

znaki ko´ ca linii n

¡
¡

Ta własno´c protokołu MODBUS ASCII została wykorzystana w celu unikniecia stosowania wspos´
mnianego wcze´niej modulatora/demodulatora (np. Manchester) zapewniajacego wypełnienie sys
gnału modulujacego nadajnik bliskie 50%. Zaproponowano tablice konwersji znak´ w protokołu na
o
o´miobitowe kody binarne. Maja one te własno´c, ze w obszarze jednego znaku (uwzgledniajac bity
s
s´ ˙
startu i stopu) nie wystepuja ciagi jednakowych bit´ w o długo´ci przekraczajacej 2 (tab. 2). Pozwala
o
s
to zachowa´ warunki poprawnej pracy adaptacyjnego dyskryminatora danych po stronie odbiorczej
c
BiM2.
W celu zapewnienia synchronizacji odbiornika ze strumieniem bit´ w odbieranych, ka˙ da ramka
o
z
jest poprzedzana preambuła zawierajaca kody spoza protokołu (0x55) - ignorowane przez odbiornik ramek i zapewniajace synchronizacje bit´ wa), oraz znacznik synchronizacji bajt´ w (0xff) - poo
o
zwalajacy jednoznacznie ustali´ pło˙ enie bitu startu). Ze wzgledu na konieczno´c transmitowania
c
z

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

10

Tablica 2: Tablica kodowa do transmisji radiowej w protokole MODBUS
kod binarny
01101010
00110011
00110101
00110110
01010011
01010110
01011001
01011010
01100101
01100110
01101001
10010011
10010101
10010110
10011001
10011010
10100101
10101001
10100110
01010101

kod szesnastkowy
0x6a
0x33
0x35
0x36
0x53
0x56
0x59
0x5a
0x65
0x66
0x69
0x93
0x95
0x96
0x99
0x9a
0xa5
0xa9
0xa6
0x55

zastosowanie w protokole
znacznik poczatku ramki
cyfra ”0”
cyfra ”1”
cyfra ”2”
cyfra ”3”
cyfra ”4”
cyfra ”5”
cyfra ”6”
cyfra ”7”
cyfra ”8”
cyfra ”9”
cyfra ”A”
cyfra ”B”
cyfra ”C”
cyfra ”D”
cyfra ”E”
cyfra ”F”
1-szy znak ko´ ca ramki
n
1-szy znak ko´ ca ramki
n
ignorowany (synchronizacja bitowa)
¢

znak
:
0
1
2
3
4
5
6
7
8
9
A
B
C
D
E
F
CR
LF
U








kod´ w o´miobitowych odstapiono od kontrolowania parzysto´ci poprzecznej (tryb portu szeregoo
s
s
wego: 19200, 8N1).
Jednostka nadrzedna (PC) po wysłaniu ramki (poprzedzonej preambuła) wyłacza nadajnik przez deaktywacje sygnału RT S na złaczu portu szeregowego (co powoduje deaktywacje T X select i aktywacje
RX select w module radiowym) i rozpoczyna oczekiwanie na odpowied´ .
z
Jednostka podrzedna (sterownik robota) oczekuje na ramki od PC przy wlaczonym odbiorniku (PE.5
w stanie niskim: RX select - aktywny, T X select - nieaktyny). Po odebraniu poprawnej ramki adresowanej do siebie, slave ustawia stan wysoki na wyj´ciu PE.5, co powoduje wyłaczenie nadajnika i
s
właczenie odbiornika, a nastepnie wysyła ramke odpowiedzi (r´ wnie˙ poprzedzona preambuła).
o
z
Taki spos´ b komunikacji zmniejsza energie fali no´nej emitowanej przez nadajniki, ograniczajac do
o
s
o
z
niezbednego minimum czas ich właczenia. Jest to r´ wnie˙ nie bez znaczenia dla poboru mocy z
akumulator´ w robota mobilnego.
o
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

3 Oprogramowanie
W dodatkach załaczono oprogramowanie realizujace komunikacje z wykorzystaniem zmodyfikowanego protokołu MODBUS, kt´ re zostało wykorzystane do zbadania poprawno´ci pracy opracowanego
o
s
systemu komunikacjo bezprzewodowej z robotem mobilnym. Zostało ono zrealizowane w jezyku C
na dw´ ch platformach:
o
 

 

 

 

MC68332 - strona sterownika robota (slave),
Linux/PC - strona komputera nadrzednego (master).
 

11

¡

¡

3.1 Strona sterownika (slave)
Koncepcja swobodnie programowalnego sterownika, kt´ ra zapewnia u˙ ytkownikowi łatwe impleo
z
mentowanie własnych algorytm´ w sterowania w sterowniku autonomicznego robota mobilnego obejo
muje obsługe komunikacji z otoczeniem w standardzie MODBUS.
Wykorzystywanie funkcji jadra do komunikacji nie wymaga od u˙ ytkownika znajomo´ci techniczz
s
nych szczeg´ ł´ w budowy sterownika. U˙ ytkownik (eksperymentator), chcac zapewni´ komunikacje z
oo
z
c
własnym algorytmem sterowania musi ustali´ przyporzadkowanie własnych zmiennych i paramet´ow
c
r
odpowiednim rejestrom MODBUS.
Je˙ eli zachodzi potrzeba reagowania sterownika w spos´ b asynchroniczny (tzn. poza cyklem realiz
o
zacji algorytmu sterowania) na zmiane zawarto´ci rejestr´ w MODBUS, to do u˙ ytkownika nale˙ y
s
o
z
z
napisanie procedury obsługujacej takie zdarzenia. Procedura ta bedzie wywoływana ka˙ dorazowo po
z
wykonaniu obsługi funkcji Write N Registers (#16) z argumentami przekazujacymi adres pierwszego
z zapisywanych rejestr´ w i ilo´c zapisanych rejestr´ w. W ten spos´ b u˙ ytkownik mo˙ e zapewni´ np.
o

o
o z
z
c
obsługe komend wpisywanych jako umowne kody do ustalonego rejestru MODBUS.
Zamieszczone zr´ dła zawieraja:
´o
 

 

 

 

 

 

 

 

 

 

 

obsługe protokołu MODBUS właczona do jadra sterownika (pliki Modbus.h i Modbus.c),
 

 

 

¡

 

przykładowy program u˙ ytkownika (plik Radio s.c).
z
¡

3.2 Strona komputera nadrzednego (master)
 

Oprogramowanie po stronie komputera nadrzednego zostało zrealizowane w celu przetestowania
własno´ci opracowanych modem´ w radiowych.
s
o
Składa sie ono z dw´ ch cze´ci:
o
s
 

 

 

obsługa protokołu MODBUS (pliki modbus.h i modbus.c),
¡

program testowy (plik mod.c).
¡

Cze´c u˙ ytkowa zawiera jedynie wizualizacje wynik´ w testu, pozwala jednak zapozna´ sie ze sposos´ z
o
c
bem wywoływania procedur obsługi protokołu.
W pełni funkcjonalna jest natomiast cze´c dotyczaca obsługi protokołu MODBUS z zaimplementos´
wanym kodowaniem znak´ w według tab. 2.
o
 

 

 

 

 

´
4 Uwagi koncowe
Opisane układy transmisji radiowej wraz ze zmodyfikowanym protokołem MODBUS pozwalaja na
komunikowanie sie oprogramowania u˙ ytkowego zaimplementowanego na komputerze nadrzednym
z
(PC) ze sterownikiem robota mobilnego.
s
Pr´ by przeprowadzono z u˙ yciem cwier´ falowych anteny pretowej o długo´ci 155mm, w laboratoo
z
´
c
rium robotyki Instytutu Cybernetyki Technicznej. Uzyskane wyniki sa zadawalajace. Stopa błed´ w
o
(retransmisji) jest poni˙ ej 0.002 przy odległo´ci do 10m wewnatrz budynku. Dalszego zbadania wyz
s
maga zasieg transmisji przy zastosowaniu innych typ´ w anten oraz na zewnatrz budynku.
o
Bezprzewodowa łaczno´c na niewielkie odległo´ci pozwala przekazywa´ parametry i rozkazy zadas´
s
c
wania trajektorii ruchu i parametr´ w algorytmu sterowania oraz odbiera´ wyniki pomiar´ w dokoo
c
o
nanych podczas eksperyment´ w. Niezbyt wielka predko´c transmisji (19.2kB) nie pozwala wprawo

dzie na bezpo´rednie sterowanie robotem w ruchu przy pomocy algorytmu zaimplementowanego
s
 

 

 

 

 

 

 

 

 

 

 

 

12

na koputerze nadrzzednym, ale nie jest to potrzebne, gdy˙ koncepcja swobodnie programowalnego
z
sterownika [2] pozwala eksperymentatorowi implementowa´ algorytmy sterowania bezpo´redni w
c
s
sterowniku robota i przeprowadza´ badania zachowujac autonomiczny charakter obiektu.
c
 

 

Bibliografia
[1] Kabała M., Tcho´ K., Wnuk M., Robot mobilny napedzany w układzie wewnetrznym, VII KKR,
n
Ladek Zdr´ j, 2001, Prace Naukowe ICT PWr., Konferencje 46, t.1, ss. 149-158.
o
 

 

 

[2] Kabała M., Wnuk M., Dwukołowy robot mobilny napedzany w układzie wewnetrznym, Raport
SPR 21/2001, Inst. Cyb. Techn. PWr, 2001.
 

 

[3] Kabała M., Tcho´ K., Wnuk M., Dwukołowy nieholonomiczny robot mobilny, Materiały Konfen
rencji Automation 2002, Warszawa, marzec 2002, ss. 269-280.
[4] BiM-2 User’s Manual, Radiometrix Inc., 2000.
[5] Modicon Modbus Protocol Reference Guide, PI-MBUS-300 Rev. J, Modicon Inc., 1996.
[6] Queued Serial Module Reference Manual, QSMRM/AD, Motorola Inc., 1991.

13

5 Dodatek A: Oprogramowanie sterownika
/*
* Modbus.c
* Implementacja minimalnej wersji
* protokolu MODBUS dla 68332
*
* Tryb:
ASCII
* Serial:
19200 8 n 1
* Funkcje:
03, 16, 17
* Rejestry:
16-bit
*
* MW 2000
*
* Dla Radiometrix BiM2-433-64-S
* tablice konwersji mw2asc i asc2mw
* (c) MW 2002
*/
#include ´im.h "
s
#include " qsm.h "
#define _DEFINE_MW_
#include " modbus.h "
#undef _DEFINE_MW_
#define
#define
#define
#define
#define

Baud
SCI_VECT
SCI_LEVEL
CLOCK
MAX_BUF

19200
112
6
16777216
256

#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define
#define

BitSet(b,n)
BitClr(b,n)
BitTst(b,n)
DirIn
DirOut
TxEnable
TxDisable
TxIEnable
TxIDisable
RxIEnable
RxIDisable
TxCIEnable
TxCIDisable

(b)|=(1 & lt; & lt; (n))
(b) & =˜(1 & lt; & lt; (n))
(b) & (1 & lt; & lt; (n))
BitSet(PORTE,5)
BitClr(PORTE,5)
SCCR1 |= 0x0008
SCCR1 & = 0xfff7
SCCR1 |= 0x0080
SCCR1 & = 0xff7f
SCCR1 |= 0x0020
SCCR1 & = 0xffdf
SCCR1 |= 0x0040
SCCR1 & = 0xffbf

/* czestotliwosc zegara CPU */

/*
/*
/*
/*
/*
/*
/*
/*
/*
/*

14

wylaczenie bufora nadajnika */
wlaczenie bufora nadajnika */
uruchomienie nadajnika */
zatrzymanie nadajnika */
dblokowanie przerwan Tx */
zablokowanie przerwan Tx */
dblokowanie przerwan Rx */
zablokowanie przerwan Rx */
odblokowanie przerwan Tx */
zablokowanie przerwan Tx */

/* kody bledow MODBUS */
#define
#define
#define
#define
#define
#define
#define
#define

FuncErr
AddrErr
DataErr
ExtErr
AckErr
BusyErr
NackErr
ParErr

1
2
3
4
5
6
7
8

/*
/*
/*
/*
/*
/*
/*
/*

niedozwolona funkcja */
niedozwolony zakres danych */
niedozwolona wartosc danych */
uszkodzenie w przylaczonym urzadzeniu */
potwierdzenie pozytywne */
brak gotowosci - komunikat usuniety */
potwierdzenie negatywne */
blad parzystosci pamieci */

/* deklaracje stalych globalnych */
const char

hex[16]= " 0123456789ABCDEF " ;

const char

preamble[8]={0x55,0x55,0x55,0xc3,0x3c,0x55,0x00,0x55};

/* deklracje zmiennych globalnych */
int
BYTE
BYTE
BYTE
BYTE
BYTE
WORD
WORD
int
int
int
int
int
int
WORD
BYTE
BYTE

MsgRdy;
MbErr;
MbID;
addr;
fc;
LRC;
index;
number;
i;
cntP;
cnt;
cntB;
stat;
ch;
timeout;
*TxPtr;
TxBuf[MAX_BUF];

#define ScBr(x) (CLOCK/32 + ((x)/2))/(x)
/* deklaracje procedur obslugi */
void (*Action)();
void (*WriteSvc)();
void NoAction();

15

/* dzielnik predkosci SCI */

void
void
void
void
void
void
void
void
void
void
void
void
int

NoSvc();
Await();
Adata();
Afinal();
Apre();
Asend();
Asend1();
AsendLRCH();
AsendLRCL();
AsendCR();
AsendLF();
AsendEnd();
Getint();

/* deklaracje funkcji protokolu MODBUS */
void
void
void
void

Read03 (WORD, WORD);
Write16(WORD, WORD);
Ident17();
SendEnd(WORD, WORD);

void initmw2asc()
{
int i;
for(i=0;i & lt; 256;i++) mw2asc[i] = 0;
for(i=0;i & lt; 128;i++)
{
if(asc2mw[i]) mw2asc[asc2mw[i]] = i;
}
}
/* Obsluga SCI */
/* procedura obslugi przerwania */
/* #pragma TRAP_PROC powoduje zamiane RTS na RTE i zachowanie rejestrow */
#pragma TRAP_PROC
void SciSvc()
{
stat = SCSR;
if(0 == (ch = mw2asc[SCDR & 0xff])) {Action= & Await; return;}
if(ch != 0x55) (*Action)();
}

/* Inicjalizacja SCI */

16

void SciBaud(int baudrate)
{
SCCR0 = ScBr(baudrate);
}
void SciMode()
{
DirIn;
TxCIDisable;
RxIDisable;
MsgRdy=0;
timeout=0;
SCCR1 = 0x000c;
Action= & Await;
RxIEnable;
}

/* dzielnik zegara SCI */

/* 8N1, TxEn RxEn ASCII*/

void MbInit(BYTE slaveaddr, BYTE slaveid)
{
int pom;
/* Ustawienie wektora przerwania od SCI */
*((void (**) ())(4*SCI_VECT)) = SciSvc;
QMCR

= 0x0083;

/* SUPV, IARB=0x3 */

SCCR1
QILR
QIVR

= 0x000c;
= SCI_LEVEL;
= SCI_VECT;

/* poziom przerwania */
/* wektor przerwania */

DirIn;
pom
= SCSR;
pom
+= SCDR;
Action
= & NoAction;
WriteSvc
= & NoSvc;
ExtFail
= 0;
addr
= slaveaddr;
MbID
= slaveid;
RunStat
= 0xff;
MsgRdy
= 0;
SciBaud(Baud);
SciMode();

/* wylaczenie bufora nadajnika RS232 */

}

17

void NoAction() {}
void NoSvc(WORD ind, WORD nbr) {}
/* Obsluga trybu MODBUS ASCII

*/

void Await()
{
ch & = 0x007f;
if(stat & 0x0080) TxCIDisable;
if((stat & 0x004f)==0x0040)
{
if(ch == ’:’)
{
TxPtr=TxBuf;
cntB=0;
LRC=0;
Action= & Adata;
}
}
}

// zblokuj przerwanie od nadajnika
// odebrano znak
// poczatek ramki

void Adata()
{
ch & = 0x007f;
if(stat & 0x0080) TxCIDisable; /* zblokuj przerwanie od nadajnika */
if((stat & 0x004f)==0x0040)
/* odebrano znak */
{
if(ch == 0x0d)
/* znak konca ramki & lt; CR & gt; */
{
Action= & Afinal;
return;
}
if(ch & lt; ’0’ || ch & gt; ’9’)
if(ch & lt; ’A’ || ch & gt; ’F’) {Action= & Await; return;}
if(ch & lt; ’A’) ch-=’0’;
else ch-=55;
/* ’A’-10 */
if(cntB & 0x0001) {
*TxPtr|=ch;
LRC+=*TxPtr++;
}
else *TxPtr=ch & lt; & lt; 4;
cntB++;
if(cntB & gt; 2*MAX_BUF) Action= & Await;
}
}

18

void Afinal()
{
ch & = 0x007f;
if(stat & 0x0080) TxCIDisable; // zblokuj przerwanie od nadajnika
if((stat & 0x004f)==0x0040)
// odebrano znak
{
if(ch == 0x0a) {
// drugi znak konca ramki & lt; LF & gt;
if(LRC==0) {
if(addr == TxBuf[0] || TxBuf[0]==0) {
MsgRdy=1;
Action= & Apre;
cntP=8;
RxIDisable;
return;
}
}
}
Action= & Await;
}
}
void Apre()
{
if(MsgRdy) {TxCIDisable; return;}
if(stat & 0x0080)
/* nadajnik? */
{
if(TxBuf[0]==0) {
TxCIDisable;
RxIEnable;
Action = & Await;
}
else {
DirOut;
if(--cntP) SCDR = preamble[cntP];
/* wyslij */
else Action = & Asend;
}
}
}
void Asend()
{
if(stat & 0x0080)
{
TxPtr = TxBuf;
cntB*=2;

/* nadajnik? */

19

LRC = 0;
SCDR = asc2mw[’:’];
Action = & Asend1;

/* wyslij */

}
}
void Asend1()
{
if(stat & 0x0080)
/* nadajnik? */
{
ch = *TxPtr;
if(cntB & 0x0001) { LRC+=*TxPtr++; ch & =0x0f;}
else ch & gt; & gt; =4;
ch = hex[ch];
SCDR = asc2mw[ch];
/* wyslij */
cntB--;
if(!cntB) Action = & AsendLRCH;
}
}
void AsendLRCH()
{
if(stat & 0x0080)
{
LRC=˜LRC+1;
ch = hex[LRC & gt; & gt; 4];
SCDR = asc2mw[ch];
Action = & AsendLRCL;
}
}
void AsendLRCL()
{
if(stat & 0x0080)
{
ch = hex[LRC & 0x0f];
SCDR = asc2mw[ch];
Action = & AsendCR;
}
}
void AsendCR()
{
if(stat & 0x0080)
{
SCDR = asc2mw[0x0d];

/* nadajnik? */

/* wyslij */

/* nadajnik? */

/* wyslij */

/* nadajnik? */
/* wyslij CR */

20

Action = & AsendLF;
}
}
void AsendLF()
{
if(stat & 0x0080)
{
SCDR = asc2mw[0x0a];
Action = & AsendEnd;
}
}
void AsendEnd()
{
if(stat & 0x0080)
{
TxCIDisable;
RxIEnable;
DirIn;
Action = & Await;
}
}

/* nadajnik? */
/* wyslij LF */

/* nadajnik? */

/* Funkcje obslugi bufora transmisji */
char Getchar()
{
return TxBuf[cnt++];
}
int Getint()
{
int xx;
xx=TxBuf[cnt++]*256;
xx+=TxBuf[cnt++];
return xx;
}
void Setint(int w)
{
char* wsk;
wsk=(char*) & w;
TxBuf[cntB++]=*wsk++;
TxBuf[cntB++]=*wsk++;
}

21

void Setchar(char w)
{
TxBuf[cntB++]=w;
}
void MbService()
{
if(MsgRdy) {
fc = TxBuf[1];
cnt=2;
MbErr=0;
if(fc == 0x03 ) { // odczyt n-rejestrow
cntB=3;
index= Getint();
number= Getint();
Read03(index,number);
TxBuf[2]=cntB-3;
}
else if(fc == 0x10) { // zapis rejestrow
index= Getint();
number= Getint();
Write16(index,number);
cntB=6;
}
else if(fc == 0x11 ) { // identyfikacja
cntB=3;
Ident17();
TxBuf[2]=cntB-3;
}
else MbErr = FuncErr;
if(ExtFail) MbErr = ExtErr;
if(MbErr) {
fc |= 0x80;
TxBuf[1] = fc;
TxBuf[2] = MbErr;
cntB= 3;
}
MsgRdy=0;
TxCIEnable;
if( fc==16 & & MbErr==0 ) (* WriteSvc)(index, number);
}
}
void Read03(WORD ind, WORD num)

22

{
int
i,k;
int
wi;
double w;
if(num == 0 || num & gt; FC03_MAX) {MbErr=AddrErr; return;}
if(ind & gt; =INT_BASE & & (ind+num) & lt; =INT_MAX) {
ind-=INT_BASE;
for(i=ind; i & lt; ind+num;i++) {
Setint(MbRegs[i]);
}
}
else MbErr=AddrErr;
}
void Write16(WORD ind, WORD num)
{
int
k;
k=Getchar();
if(k != num*2) {MbErr=FuncErr; return;}
if(ind & gt; =INT_BASE & & (ind+num) & lt; =INT_MAX) {
ind-=INT_BASE;
for(i=ind;i & lt; ind+num;i++) {
MbRegs[i] = Getint();
}
}
else MbErr=AddrErr;
}
void Ident17()
{
Setchar(MbID);
Setchar(RunStat);
}
void MbStart()
{
Action = & Await;
}
void MbStop()
{
Action = & Await;
}
/* koniec pliku modbus.c */

23

/*
* Modbus.h
* definicje dla protokolu MODBUS
*
* MW 2000
*
* Dla Radiometrix BiM2-433-64-S
* tablice konwersji mw2asc i asc2mw
* (c) MW 2002
*/
#ifndef WORD
#define WORD unsigned int
#endif
#ifndef BYTE
#define BYTE unsigned char
#endif
#ifndef _modbus_MW_
#define _modbus_MW_
/* definicje rejestrow */
#define INT_NBR
#define INT_BASE
#define INT_MAX

20
/* liczba rejestrow 16-bitowych */
1000
/* adres bazowy rejestrow 16-bitowych */
INT_BASE+INT_NBR
/* maks. adres rejestru */

#define FC03_MAX
#define FC16_MAX

10
10

/* maks. liczba odczytywanych rejestrow */
/* maks. liczba zapisywanych rejestrow */

#ifdef _DEFINE_MW_
#define EXTERN
const unsigned char asc2mw[128] = {0,0,0,0,0,0,0,0,0,0,0xa6,0,0,0xa9,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0x33,0x35,0x36,0x53,0x56,0x59,0x5a,0x65,
0x66,0x69,0x6a,0,0,0,0,0,
0,0x93,0x95,0x96,0x99,0x9a,0xa5,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,0x55,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };

24

#else
#define EXTERN extern
extern const unsigned char asc2mw[];
#endif

EXTERN unsigned char mw2asc[256];
EXTERN
EXTERN
EXTERN
EXTERN

int
int
int
void

RunStat;
ExtFail;
MbRegs[INT_NBR];
(*WriteSvc)();

/*
/*
/*
/*

flaga uruchomienia urzadzenia */
flaga uszkodzenia urzadzenia */
rejestry MODBUS */
obsluga komend wpisywanych do rejestrow */

EXTERN
EXTERN
EXTERN
EXTERN

void
void
void
void

MbInit(BYTE,BYTE);
MbService();
MbStart();
MbStop();

/*
/*
/*
/*

inicjalizacja transmisji szeregowej */
obsluga protokolu w petli glownej */
uruchomienie MODBUS */
zatrzymanie MODBUS */

#endif /*_modbus_MW_*/
/* koniec pliku modbus.h */

25

/*
* radio_s.c
* Program testowy minimalnej wersji
* protokolu MODBUS dla 68332
*
* Tryb:
ASCII, slave #1
* Serial:
19200 8 n 1
* Funkcje:
03, 16, 17
* Rejestry:
16-bit
*
* komunikacja przez Radiometrix BiM2-433-64-S
*
* (c) MW 2002
*/
#include
#include
#include
#include
#include

" tpu.h "
" qsm.h "
´im.h "
s
" modbus.h "
" flash.h "

#ifndef byte
#define byte unsigned char
#endif
#define RBASE

0x800000

extern const byte tpumska;
extern const long EXCEPT;
void komendy(WORD ind, WORD cnt)
{
if(ind == 1002) MbRegs[0] += 1;
}
int main()
{
BYTE saddr, sid;
int i;
const byte * tmaptr;
byte * ramptr;
volatile long Tblco,ii;

26

/* Programowanie pamieci FlashROM */
FlashProgFlag = 0;
/* zakaz programowania */
ProgMode = FlashProg(FlashProgFlag);
Tblco=EXCEPT;
/* Emulacja maski A TPU w RAM */
*((word *)0xfffb04) = RBASE & gt; & gt; 8;
tmaptr = (const byte *)( & tpumska);
ramptr = (byte *)RBASE;
for(i=0;i & lt; 2048;i++) *ramptr++ = *tmaptr++;
ramptr = (byte *)( & tpumska);
initmw2asc();
saddr = 1;
sid = 0;

/* adres wezla */
/* slave ID */

MbInit(saddr, sid);
asm { ORI #0x0700,SR
ANDI #0xfdff,SR
}

/* ustawienie poziomu przerwan na 5 */

for(i=0;i & lt; 20;i++) MbRegs[i] = i+1;
WriteSvc = & komendy;
MbStart();
while(1)
{
MbService();
ExtFail = 0;
MbRegs[6] += 1;
}
}
/* koniec pliku radio_s.c */

27

6 Dodatek B: Oprogramowanie PC

/*
* modbus.c
*
* Procedury do obslugi MODBUS-Master
* Wersja minimalna:
*
* Tryb:
ASCII
* Serial:
19200 8 n 1
* Funkcje:
03, 16, 17
* Rejestry:
16-bit
*
* (c) MW 2000-2002
*-----------------------------------------------------------* 2000/05/23
pierwsza wersja
mw
* 2002/06/17
kodowanie MODBUS dla BiM2
mw
*-----------------------------------------------------------*/
#include
#include
#include
#include
#include
#include
#include

& lt; stdio.h & gt;
& lt; unistd.h & gt;
& lt; stdlib.h & gt;
& lt; signal.h & gt;
& lt; errno.h & gt;
& lt; string.h & gt;
& lt; asm/termios.h & gt;

#define VERBF
#define _DEFINE_MW_
#include " modbus.h "

0

/* 1 dla testow */

#define BUFSIZE 100
int verb = VERBF;
int rerr = 0;
int werr = 0;
int ierr = 0;
FILE *fpt, *fpr;
const int rts = TIOCM_RTS;

28

void initmw2asc()
{
int i;
for(i=0;i & lt; 256;i++) mw2asc[i] = 0;
for(i=0;i & lt; 128;i++)
{
if(asc2mw[i]) mw2asc[asc2mw[i]] = i;
}
}
/* Inicjalizacja portu szeregowego do komunikacji */
int SetCom(int fd)
{
struct termios tds;
int i;
for (i=0; i & lt; NCCS; i++) tds.c_cc[i] = 0;
tds.c_iflag = (IGNBRK);
tds.c_iflag & = ˜(INPCK | ISTRIP | INLCR | IGNCR | ICRNL | IUCLC |
IXON | IXANY | IXOFF | IMAXBEL);
tds.c_oflag =0;
tds.c_cflag = 0;
tds.c_cflag |= CREAD | CLOCAL | CS8;
tds.c_lflag = NOFLSH;
/*....... Ustawienie predkosci odbioru i nadawania. ........*/
if (cfsetispeed( & tds,B19200)) { printf( " *** Blad 2\n " ); exit(2);}
if (cfsetospeed( & tds,B19200)) { printf( " *** Blad 3\n " ); exit(3);}
/*.......... Ustawienie trybu pracy .........................*/
return tcsetattr(fd,TCSANOW, & tds);
}
/* nadawanie ramki MODBUS */
SendFrame(char *txb)
{
char tc, rc;
unsigned char rr;
char *ptr = txb;
int i, t0;
int ilosc, ilosc_nad;

29

ioctl(fd, TIOCMBIS, & rts);

// ustawienie linii RTS w porcie

while(*ptr){
*ptr=asc2mw[*ptr];
ptr++;
}
write(fd, " \125\125\125\125\125\125\125\125\125\125\125\125\125\125\
\125\125\125\125\125\125\125\125\377\125 " ,24);
ptr=txb;
t0 = time(NULL);
ilosc_nad=strlen(txb);
do {
if (time(NULL) - t0 & gt; 2) {
fprintf(stderr, " *** Przekroczony dozwolony czas na zapis.\n " );
exit(5);
}
/*... Przesylanie tekstu ................................*/
if ((ilosc = write(fd,ptr,ilosc_nad)) == 0) continue;
if (ilosc & lt; 0) { fprintf(stderr, " *** Blad nadawania\n " ); exit(4);}
ilosc_nad -= ilosc;
ptr += ilosc;
t0 = time(NULL); /*.. Jesli cos nadane to ponownie odczytany czas */
} while (ilosc_nad & gt; 0);
tcdrain (fd);
ioctl(fd, TIOCMBIC, & rts);

// wyzerowanie linii RTS w porcie

}
/* Funkcje do obslugi MODBUS */
/* Funkcja 03 - read n-registers */
int ReadRegs(unsigned char
unsigned short
unsigned short
unsigned short
{
char txbuf[30];
char rxbuf[256];
char tc, rc;
unsigned char rr;
char *ptr = txbuf;
char *eptr, ebuf[80];

slave,
index,
count,
* buffer)

30

unsigned char sum = 3;
unsigned int slrx, fcrx, nbrx, sumx;
int err = 0, flag =0, fin = 0, ecnt=0;
int i, hibuf, lobuf, stat;
int t0, ilosc, ilosc_nad;
sum
sum
sum
sum

+= slave;
+= (index-1)%256 + (index-1)/256;
+= count%256 + count/256;
= 256 - sum;

/* Zestawianie ramki dla funkcji 03 */
sprintf(txbuf, " :%02X03%04X%04X%02X\015\012 " , slave, index-1, count, sum);
if(verb) fprintf(stderr, " %s " , txbuf);
for(i=0;i & lt; 256;i++) rxbuf[i]=0;
SendFrame(txbuf);
/* Odbieranie odpowiedzi */
ptr = rxbuf;
t0 = time(NULL);
while(!err & & !fin)
{
if(1 == (stat = read(fd, & rr, 1)))
{
rc=mw2asc[rr];
if(verb) fputc(rc, stderr);
if(rc == ’:’) flag = 1;
if(flag)
{
*ptr++ = rc;
if(rc == 0xa) fin = 1;
*ptr = 0;
}
}
else
{
if(stat==0){
if(time(NULL)-t0 & lt; TOUT_SEC) continue;
else{
err ++; rerr++;
if(verb) fprintf(stderr, " \n!!! timeout: %d, %s \n " , err, rxbuf);

31

fprintf(stderr, " \nrerr #%d\n " ,rerr);
return ERR_TOUT;
}
}
else{
err ++;rerr++;
if(verb) fprintf(stderr, " \n!!! blad przy odpowiedzi na 03\n " );
fprintf(stderr, " \nrurr #%d\n " ,rerr);
return ERR_UNKN;
}
}
if(fin)
{
fprintf(stderr, " \nfin #r:%d w:%d i:%d\n " ,rerr,werr,ierr);
if(verb) fprintf(stderr, " %s " , rxbuf);
ptr = rxbuf;
if(3 != sscanf(ptr, " :%02X%02X%02X " , & slrx, & fcrx, & nbrx))
return ERR_FORM;
if(verb) fprintf(stderr, " \nslave: %d\nfunct: %d\nnumbr: %d\n " ,
slrx, fcrx, nbrx);
sum = slrx + fcrx + nbrx;
if(fcrx & 0x80)
{
if(1 != sscanf(rxbuf + 5, " %02X " , & sumx))
return ERR_FORM;
if(0 != sum + sumx)
return ERR_CSUM;
if(slrx != slave) return ERR_SLVN;
if(fcrx == 0x83)
{
ModErrno = nbrx;
if(verb) fprintf(stderr, " \nerror: %d\n " , nbrx);
return ERR_MBUS;
}
else
return ERR_FUNC;
}
if(slrx != slave) return ERR_SLVN;
if(fcrx != 3) return ERR_FUNC;

32

else
{
ptr = rxbuf + 7;
for(i=0; i & lt; nbrx/2; i++)
{
ptr = rxbuf + 7 + 4*i;
if(1 != sscanf(ptr, " %02x " , & hibuf)) return ERR_FORM;
sum += hibuf;
if(1 != sscanf(ptr+2, " %02x " , & lobuf)) return ERR_FORM;
sum += lobuf;
buffer[i] = 256*hibuf+lobuf;
}
ptr = rxbuf + 7 + 2*nbrx;
if(1 != sscanf(ptr, " %02x " , & sumx)) return ERR_FORM;
sum += sumx;
if(verb) fprintf(stderr, " \nsuma : %02X (%02X)\n " ,
sum%256, sumx);
if(sum) return ERR_CSUM;
if(verb)
{
for(i=0; i & lt; nbrx/2; i++)
{
fprintf(stderr, " (%d) = %04X\n " , index+i, buffer[i]);
}
}
return 0;
}
}
}
}
/* Funkcja 16 - write n-registers */
int WriteRegs(unsigned
unsigned
unsigned
unsigned
{
char txbuf[256];
char rxbuf[300];
char tc, rc;
unsigned char rr;
char *ptr = txbuf;

char
short
short
short

slave,
index,
count,
* buffer)

33

unsigned char sum = 16;
unsigned int slrx, fcrx, nbrx, sumx, firstx, numberx;
char *eptr, ebuf[80];
int err = 0, flag =0, fin = 0, ecnt=0;
int i, hibuf, lobuf, stat, t0;
sum
sum
sum
sum

+=
+=
+=
+=

slave;
(index-1)%256 + (index-1)/256;
count%256 + count/256;
2*count;

/* Zestawianie ramki dla funkcji 16 */
sprintf(txbuf, " :%02X10%04X%04X%02X " , slave, index-1, count, 2*count);
for(i=0; i & lt; count; i++)
{
ptr = txbuf + 15 + 4*i;
sprintf(ptr, " %04X " , buffer[i]);
sum += buffer[i]%256 + buffer[i]/256;
}
sprintf( txbuf + 15 + 4*count, " %02X\r\012 " , 256 - sum);
if(verb) fprintf(stderr, " %s " , txbuf);
for(i=0;i & lt; 256;i++) rxbuf[i]=0;
SendFrame(txbuf);
/* Odbieranie odpowiedzi */
ptr = rxbuf;
t0 = time(NULL);
//

eptr=ebuf; ebuf[0]=0; ecnt = 0;

while(!err & & !fin)
{
if(1 == (stat = read(fd, & rr, 1)))
{
rc=mw2asc[rr];
if(verb) fputc(rc, stderr);
if(rc == ’:’) flag = 1;
if(flag)
{
*ptr++ = rc;

34

if(rc == 0xa) fin = 1;
*ptr = 0;
}
}
else
{
if(stat==0){
if(time(NULL)-t0 & lt; TOUT_SEC) continue;
else{
err ++; werr++;
if(verb) fprintf(stderr, " \n!!! timeout: %d, %s \n " ,
err, rxbuf);
fprintf(stderr, " \nwerr #%d\n " ,werr);
return ERR_TOUT;
}
}
else{
err ++;werr++;
if(verb) fprintf(stderr, " \n!!! blad przy odpowiedzi na 16\n " );
fprintf(stderr, " \neurr #%d\n " ,werr);
return ERR_UNKN;
}
}
if(fin)
{
fprintf(stderr, " \nfin #r:%d w:%d i:%d\n " ,rerr,werr,ierr);
if(verb) fprintf(stderr, " %s " , rxbuf);
ptr = rxbuf;
if(2 != sscanf(ptr, " :%02X%02X " , & slrx, & fcrx))
return ERR_FORM;
if(verb) fprintf(stderr, " \nslave: %d\nfunct: %d\n " , slrx, fcrx);
sum = slrx + fcrx;
if(fcrx & 0x80)
{
if(2 != sscanf(rxbuf + 5, " %02X%02X " , & nbrx, & sumx))
return ERR_FORM;
if(0 != sum + nbrx + sumx)
return ERR_CSUM;
if(slrx != slave) return ERR_SLVN;
if(fcrx == 0x90)
{

35

ModErrno = nbrx;
if(verb) fprintf(stderr, " \nerror: %d\n " , nbrx);
return ERR_MBUS;
}
else
return ERR_FUNC;
}
if(3 != sscanf( rxbuf + 5, " %04X%04X%02X " , & firstx, & numberx, & sumx))
return ERR_FORM;
if(verb) fprintf(stderr, " \nfirst: %d\nnumbr: %d\n " ,
firstx, numberx);
sum += firstx%256 + firstx/256 + numberx%256 + numberx/256 + sumx;
if(verb) fprintf(stderr, " \nsuma : %02X (%02X)\n " , sum%256, sumx);
if(0 != (sum%256))
return ERR_CSUM;
else return 0;
}
}
}
/* Funkcja 17 - identify */
int Identify(unsigned char slave,
unsigned char * buffer)
{
char txbuf[30];
char rxbuf[256];
char tc, rc;
unsigned char rr;
char *ptr = txbuf;
unsigned char sum = 17;
unsigned int slrx, fcrx, nbrx, sumx;
int err = 0, flag =0, fin = 0, ecnt=0;
char *eptr, ebuf[80];
int i, hibuf, lobuf, stat, t0;
sum += slave;
sum = 256 - sum;
/* Zestawianie ramki dla funkcji 17 */
sprintf(txbuf, " :%02X11%02X\r\012 " , slave, sum);
if(verb) fprintf(stderr, " %s " , txbuf);

36

for(i=0;i & lt; 256;i++) rxbuf[i]=0;
SendFrame(txbuf);
/* Odbieranie odpowiedzi */
ptr = rxbuf;
t0 = time(NULL);
while(!err & & !fin)
{
if(1 == (stat = read(fd, & rr, 1)))
{
rc=mw2asc[rr];
if(verb) fputc(rc, stderr);
if(rc == ’:’) flag = 1;
if(flag)
{
*ptr++ = rc;
if(rc == 0xa) fin = 1;
*ptr = 0;
}
}
else
{
if(stat==0){
if(time(NULL)-t0 & lt; TOUT_SEC) continue;
else{
err ++; ierr++;
if(verb) fprintf(stderr, " \n!!! timeout: %d, %s \n " , err, rxbuf);
fprintf(stderr, " \nierr #%d\n " ,ierr);
return ERR_TOUT;
}
}
else{
err ++;ierr++;
if(verb) fprintf(stderr, " \n!!! blad przy odpowiedzi na 17\n " );
fprintf(stderr, " \niurr #%d\n " ,ierr);
return ERR_UNKN;
}
}
if(fin)

37

{
fprintf(stderr, " \nfin #r:%d w:%d i:%d\n " ,rerr,werr,ierr);
if(verb) fprintf(stderr, " %s\n " , rxbuf);
ptr = rxbuf;
if(3 != sscanf(ptr, " :%02X%02X%02X " , & slrx, & fcrx, & nbrx))
return ERR_FORM;
if(verb) fprintf(stderr, " \nslave: %d\nfunct: %d\nnumbr: %d\n " ,
slrx, fcrx, nbrx);
sum = slrx + fcrx + nbrx;
if(fcrx & 0x80)
{
if(1 != sscanf(rxbuf + 5, " %02X " , & sumx))
return ERR_FORM;
if(0 != sum + sumx)
return ERR_CSUM;
if(slrx != slave) return ERR_SLVN;
if(fcrx == 0x91)
{
ModErrno = nbrx;
if(verb) fprintf(stderr, " \nerror: %d\n " , nbrx);
return ERR_MBUS;
}
else
return ERR_FUNC;
}
if(slrx != slave) return ERR_SLVN;
if(fcrx != 17) return ERR_FUNC;
else
{
buffer[0] = nbrx;
for(i=0; i & lt; nbrx; i++)
{
ptr = rxbuf + 7 + 2*i;
if(1 != sscanf(ptr, " %02x " , & buffer[i+1])) return ERR_FORM;
sum += buffer[i+1];
}
ptr = rxbuf + 7 + 2*nbrx;
if(1 != sscanf(ptr, " %02x " , & sumx)) return ERR_FORM;
sum += sumx;
if(verb) fprintf(stderr, " \nsuma : %02X (%02X)\n " ,
sum%256, sumx);

38

if(sum) return ERR_CSUM;
if(verb)
{
for(i=1; i & lt; =nbrx; i++)
{
fprintf(stderr, " %02X " ,
}
fprintf(stderr, " \n " );
}
return 0;
}
}
}
}
/* koniec pliku modbus.c */

39

buffer[i]);

/*
* modbus.h
*
* Definicje do obslugi MODBUS-Master
*
* MW 2000
*-----------------------------------------------------------* 2000/05/23
pierwsza wersja
*-----------------------------------------------------------*/
#ifndef _MODBUS_MW_
#define _MODBUS_MW_
#define TOUT_SEC

2

#define
#define
#define
#define
#define
#define
#define
#define

-1
-2
-3
-4
-5
-6
-7
-8

ERR_UNKN
ERR_MBUS
ERR_FORM
ERR_CSUM
ERR_SLVN
ERR_TOUT
ERR_FUNC
ERR_PARM

/*
/*
/*
/*
/*
/*
/*
/*

nieznany blad przy transmisji */
odpowiedz slave z sygnalizacja bledu */
blad formatu ramki */
blad sumy kontrolnej odpowiedzi */
nieprawidlowy numer wezla */
przekroczenie czasu odpowiedzi */
nieprawidlowy kod funkcji */
nieprawidlowe parametry odpowiedzi */

#ifdef _DEFINE_MW_
#define EXTERN
const unsigned char asc2mw[128] = {0,0,0,0,0,0,0,0,0,0,0xa6,0,0,0xa9,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0x33,0x35,0x36,0x53,0x56,0x59,0x5a,
0x65,0x66,0x69,0x6a,0,0,0,0,0,
0,0x93,0x95,0x96,0x99,0x9a,0xa5,0,0,0,
0,0,0,0,0,0,
0,0,0,0,0,0x55,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
#else
#define EXTERN extern
extern const unsigned char asc2mw[];
#endif

40

/* zmienne globalne */
EXTERN int ModErrno;
/* kod bledu odpowiedzi przy ERR_MBUS */
EXTERN unsigned char mw2asc[256];
EXTERN int fd;
/* Funkcje do obslugi MODBUS */
EXTERN void initmw2asc();
/* Inicjalizacja portu */
EXTERN int SetCom(int fd);
EXTERN int InitPort(char * port);
/* Funkcja 03 - read n-registers */
EXTERN int ReadRegs(unsigned
unsigned
unsigned
unsigned

char
short
short
short

slave,
index,
count,
* buffer);

/* Funkcja 16 - write n-registers */
EXTERN int WriteRegs(unsigned
unsigned
unsigned
unsigned

char
short
short
short

slave,
index,
count,
* buffer);

/* Funkcja 17 - identify slave */
EXTERN int Identify(unsigned char slave,
unsigned char * buffer);
#endif
/* koniec pliku modbus.h */

41

/*
* mod.c
* Przykladowy program do komunikacji ze sterownikiem
* wyposazonym w oprogramowanie MODBUS-slave
*
* Korzysta z funkcji w modbus.c
*
* (c) MW 2000-2002
*-----------------------------------------------------------* 2000/05/23
pierwsza wersja
mw
* 2002/06/17
kodowanie MODBUS dla BiM2
mw
*-----------------------------------------------------------*/
#include
#include
#include
#include
#include
#include
#include

& lt; stdio.h & gt;
& lt; fcntl.h & gt;
& lt; unistd.h & gt;
& lt; stdio.h & gt;
& lt; stdlib.h & gt;
& lt; string.h & gt;
& lt; errno.h & gt;

#include " modbus.h "
#define DEFPORT

" /dev/ttyS1 "

/* COM2 */

int main(int argc, char *argv[]){
unsigned
unsigned
unsigned
unsigned
unsigned
unsigned
int

char
short
short
short
short
char

slvaddr;
first;
number;
value;
recbuf[256];
idbuf[256];
i, result;

initmw2asc();
fprintf(stderr, " \n*** Test komunikacji MODBUS:\n " );
/*....... Otwarcie COM2 do odczytu i zapisu bez blokowania .*/
if ((fd = open( " /dev/ttyS1 " ,O_RDWR | O_NONBLOCK)) & lt; 0)
{

42

switch (fd)
{
case EACCES: fprintf(stderr, " *** brak dostepu\n " );break;
case ENOENT: fprintf(stderr, " *** objekt nie istnieje \n " );break;
case ETXTBSY: fprintf(stderr, " *** zajete :) \n " );
default: fprintf(stderr, " Blad otwarcia portu, kod: %d\n " ,errno);
}
exit(1);
};
SetCom(fd);
fprintf(stderr, " Port otwarty\n " );
slvaddr = 1;
first
= 1001;
number = 5;
value
= 0;
while(1)
{
if(0 != (result = Identify(slvaddr, idbuf)))
{
switch(result)
{
case ERR_TOUT:
fprintf(stderr, " !ID TIMEOUT\n " );
break;
case ERR_MBUS:
fprintf(stderr, " !ID BLAD MODBUS: %d\n " , ModErrno);
break;
default:
fprintf(stderr, " !ID INNY BLAD: %d\n " , result);
break;
}
}
else
{
for(i=1; i & lt; =idbuf[0]; i++)
{
fprintf(stderr, " %02X " , idbuf[i]);
}
fprintf(stderr, " \n " );
}
value ++;
if(0 != (result = WriteRegs(slvaddr, 1003, 1, & value)))

43

{
switch(result)
{
case ERR_TOUT:
fprintf(stderr, " !TX TIMEOUT\n " );
break;
case ERR_MBUS:
fprintf(stderr, " !TX BLAD MODBUS: %d\n " , ModErrno);
break;
default:
fprintf(stderr, " !TX INNY BLAD: %d\n " , result);
break;
}
}
if(0 != (result = ReadRegs(slvaddr, first, number, recbuf)))
{
switch(result)
{
case ERR_TOUT:
fprintf(stderr, " !RX TIMEOUT\n " );
break;
case ERR_MBUS:
fprintf(stderr, " !RX BLAD MODBUS: %d\n " , ModErrno);
break;
default:
fprintf(stderr, " !RX INNY BLAD: %d\n " , result);
break;
}
}
else
{
for(i=0; i & lt; number; i++)
{
fprintf(stderr, " (%d) = %04X\n " , first+i, recbuf[i]);
}
fprintf(stderr, " \n " );
}
}
}
/* koniec pliku mod.c */

44

dr in˙ . Marek Wnuk
z
Instytut Cybernetyki Technicznej
Politechniki Wrocławskiej
ul. Janiszewskiego 11/17
50-372 Wrocław

Niniejszy raport otrzymuja:
 

1. OINT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . - 1 egz.
2. Zleceniodawca . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . - 2 egz.
3. Autor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . - 2 egz.

Raport wpłynał do redakcji I-6
we wrze´niu 2002 roku.
s
 

45

5 egz
¥

Razem :


MODBUS_materiały.rar > Modbus Application Protocol v1.pdf

MODBUS.ORG

MODBUS Application Protocol Specification

1

Content

Introduction .......................................................................... 2
1.1
1.2

Scope of this document .......................................................... 2
References ............................................................................. 2

2

Abbreviations ....................................................................... 3

3

Context................................................................................. 3

4

General description .............................................................. 5
4.1
4.2
4.3
4.4

5

Function Code Categories .................................................. 11
5.1

6

modbus.org
8May02

http://www.modbus.org/

Public Function Code Definition .............................................12

Function codes descripitons................................................ 12
6.1
6.2
6.3
6.4
6.5
6.6
6.7
6.8
6.9
6.10
6.11
6.12

7

Protocol description................................................................ 5
Data Encoding........................................................................ 7
MODBUS data model ............................................................. 7
Define MODBUS Transaction ................................................. 9

01 (0x01) Read Coils .............................................................12
02 (0x02) Read Discrete Inputs..............................................14
03 (0x03) Read Holding Registers .........................................17
04 (0x04) Read Input Registers .............................................18
05 (0x05) Write Single Coil ....................................................20
06 (0x06) Write Single Register .............................................22
15 (0x0F) Write Multiple Coils................................................25
16 (0x10) Write Multiple registers ..........................................28
20 (0x14) Read File Record ...................................................29
22 (0x16) Mask Write Register ...........................................34
23 (0x17) Read/Write Multiple registers..............................35
43 (0x2B) Read Device Identification ..................................38

MODBUS Exception Responses......................................... 43

1/45

1

Introduction

1.1

Scope of this document

MODBUS is an application layer messaging protocol, positioned at level 7 of the OSI model, that provides client/server communication
between devices connected on different types of buses or networks.
The industry’ serial de facto standard since 1979, Modbus continues to enable millions of automation devices to communicate. Today,
s
support for the simple and elegant structure of MODBUS continues to grow. The Internet community can access MODBUS at a reserved
system port 502 on the TCP/IP stack.
MODBUS is a request/reply protocol and offers services specified by function codes. MODBUS function codes are elements of
MODBUS request/reply PDUs. The objective of this document is to describe the function codes used within the framework of MODBUS
transactions.

1.2

References

1.

RFC 791, Internet Protocol, Sep81 DARPA

2.

MODBUS Protocol Reference Guide Rev J, MODICON, June 1996, doc # PI_MBUS_300

MODBUS is an application layer messaging protocol for client/server communication between devices connected on different types of
buses or networks.
It is currently implemented using:
Ÿ TCP/IP over Ethernet.
Ÿ Asynchronous serial transmission over a variety of media (wire : EIA/TIA-232-E, EIA-422, EIA/TIA-485-A; fiber, radio, etc.)
Ÿ MODBUS PLUS, a high speed token passing network.

MODBUS APPLICATION LAYER

Modbus on TCP
TCP
IP

Other

MODBUS+ / HDLC

Master / Slave

Ethernet II /802.3

Other

Physical layer

EIA/TIA-232 or
EIA/TIA-485

Ethernet
Physical layer

Figure 1:

modbus.org
8May02

http://www.modbus.org/

MODBUS communication stack

2/45

MODBUS.ORG

MODBUS Application Protocol Specification

2

Abbreviations

ADU

Application Data Unit

HDLC

High level Data Link Control

HMI

Human Machine Interface

IETF

Internet Engineering Task Force

I/O

Input/Output

IP

Internet Protocol

MAC

Medium Access Control

MB

MODBUS Protocol

MBAP MODBUS Application Protocol
PDU

Protocol Data Unit

PLC

Programmable Logic Controller

TCP

Transport Control Protocol

3

Context

The MODBUS protocol allows an easy communication within all types of network architectures.

MODBUS COMMUNICATION

Drive

PLC

HMI

I/ O

I/ O

PLC

I/ O

MODBUS ON TCP/IP

Gateway

HMI

MODBUS ON RS485

PLC

Gateway

MODBUS ON RS232

MODBUS ON MB+

Gateway

Device

PLC
I/ O
I/ O

Drive
I/ O

Device

I/ O
Figure 2:

Example of MODBUS Network Architecture

Every type of devices (PLC, HMI, Control Panel, Driver, Motion control, I/O Device… ) can use MODBUS protocol to initiate a remote
operation.

modbus.org
8May02

http://www.modbus.org/

3/45

MODBUS.ORG

MODBUS Application Protocol Specification

The same communication can be done as well on serial line as on an Ethernet TCP/IP networks.
Some gateway allows a communication between several types of buses or network using the MODBUS protocol.

modbus.org
8May02

http://www.modbus.org/

4/45

MODBUS.ORG

MODBUS Application Protocol Specification

4
4.1

General description
Protocol description

The MODBUS protocol defined a simple protocol data unit (PDU) independent of the underlying communication layers. The mapping of
MODBUS protocol on specific buses or network can introduce some additional fields on the application data unit (ADU).

ADU
Additional address

Function code

Data

Error check

PDU
Figure 3:

General MODBUS frame

The MODBUS application data unit is built by the client that initiates a MODBUS transaction. The function indicates to the server what
kind of action to perform.
The MODBUS application protocol establishes the format of a request initiated by a client.
The function code field of a MODBUS data unit is coded in one byte. Valid codes are in the range of 1 ... 255 decimal (128 – 255
reserved for exception responses). When a message is sent from a Client to a Server device the function code field tells the server what
kind of action to perform.
Sub-function codes are added to some function codes to define multiple actions.
The data field of messages sent from a client to server devices contains additional information that the server uses to take the action
defined by the function code. This can include items like discrete and register addresses, the quantity of items to be handled, and the
count of actual data bytes in the field.
The data field may be nonexistent (of zero length) in certain kinds request, in this case the server does not require any additional
information. The function code alone specifies the action.
If no error occurs related to the MODBUS function requested in a properly received MODBUS ADU the data field of a response from a
server to a client contains the data requested. If an error related to the MODBUS function requested occurs, the field contains an
exception code that the server application can use to determine the next action to be taken.
For example a client can read the ON / OFF states of a group of discrete outputs or inputs or it can read/write the data contents of a
group of registers.
When the server responds to the client, it uses the function code field to indicate either a normal (error-free) response or that some kind
of error occurred (called an exception response). For a normal response, the server simply echoes the original function code.

Client

Server

Initiate request
Function code

Data Request

Perform the action
Initiate the response
Function code

Data Response

Receive the response

modbus.org
8May02

http://www.modbus.org/

5/45

MODBUS.ORG

MODBUS Application Protocol Specification

Figure 4:

MODBUS transaction (error free)

For an exception response, the server returns a code that is equivalent to the original function code with its most significant bit set to
logic 1.

Client

Server

Initiate request
Function code

Data Request

Error detected in the action
Initiate an error
Error code

Exception code

Receive the response

Figure 5:

F

MODBUS transaction (exception response)

Note: It is desirable to manage a time out in order not to indefinitely wait for an answer which will perhaps never arrive.

The size of the Modbus PDU is limited by the size constraint inherited from the first Modbus implementation on Serial Line network (max.
RS485 ADU = 256 bytes).
Therefore, MODBUS PDU for serial line communication = 256 - Server adress (1 byte) - CRC (2 bytes) = 253 bytes.
Consequently :
RS232 / RS485 ADU

= 253 bytes + Server adress (1 byte) + CRC (2 bytes) = 256 bytes.

TCP MODBUS ADU

= 249 bytes + MBAP (7 bytes) = 256 bytes .

The MODBUS protocol defines three PDUs. They are :
• MODBUS Request PDU, mb_req_pdu
• MODBUS Response PDU, mb_rsp_pdu
• MODBUS Exception Response PDU, mb_excep_rsp_pdu

The mb_req_pdu is defined :
mb_req_pdu = { function_code, request_data),

where

function_code - [1 byte] MODBUS function code
request_data - [n bytes] This field is function code dependent and usually contains information such as
variable references, variable counts, data offsets, sub-function codes etc.

The mb_rsp_pdu is defined :

modbus.org
8May02

http://www.modbus.org/

6/45

MODBUS.ORG

MODBUS Application Protocol Specification

mb_rsp_pdu = { function_code, response_ data),

where

function_code - [1 byte] MODBUS function code
response_data - [n bytes] This field is function code dependent and usually contains information
such as variable references, variable counts, data offsets, sub-function codes, etc.

The mb_excep_rsp_pdu is defined :
mb_excep_rsp_pdu = { function_code, request_data),

where

function_code - [1 byte] MODBUS function code + 0x80
exception_code - [1 byte] MODBUS Exception Code Defined in table
below.

4.2

Data Encoding

• MODBUS uses a ‘
big-Endian’representation for addresses and data items. This means that when a numerical quantity larger than a
single byte is transmitted, the most significant byte is sent first. So for example
Register size

value

16 - bits

F
4.3

0x1234

the first byte sent is

0x12

then 0x34

Note: For more details, see [1] .

MODBUS data model

MODBUS bases its data model on a series of tables that have distinguishing characteristics. The four primary tables are:

Primary tables

Object type

Type of access

Discretes Input

Single bit

Read-Only

Coils

Single bit

Read-Write

Input Registers

16-bit word

Read-Only

Holding Registers

16-bit word

Read-Write

Comments
This type of data can be provided by an I/O system.
This type of data can be alterable by an application program.
This type of data can be provided by an I/O system
This type of data can be alterable by an application program.

The distinctions between inputs and outputs, and between bit-addressable and word-addressable data items, do not imply any application
behavior. It is perfectly acceptable, and very common, to regard all four tables as overlaying one another, if this is the most natural
interpretation on the target machine in question.
For each of the primary tables, the protocol allows individual selection of 65536 data items, and the operations of read or write of those
items are designed to span multiple consecutive data items up to a data size limit which is dependent on the transaction function code.
It’ obvious that all the data handled via MODBUS (bits, registers) must be located in device application memory. But physical address in
s
memory should not be confused with data reference. The only requirement is to link data reference with physical address.
MODBUS logical reference number, which are used in MODBUS functions, are unsigned integer indices starting at zero.

modbus.org
8May02

http://www.modbus.org/

7/45

MODBUS.ORG

MODBUS Application Protocol Specification

• Implementation examples of MODBUS model
The examples below show two ways of organizing the data in device. There are different organizations possible, all are not described in
this document. Each device can have its own organization of the data according to its application
Example 1 : Device having 4 separate blocks
The example below shows data organization in a device having digital and analog, inputs and outputs. Each block is separate from each
other, because data from different block have no correlation. Each block is thus accessible with different MODBUS functions.
Device application memory

MODBUS access

Input Discrete
Coils

MODBUS Request

Input Registers
Holding
Registers

MODBUS SERVER DEVICE

Figure 6

MODBUS Data Model with separate block

Example 2: Device having only 1 block
In this example, the device have only 1 data block. A same data can be reached via several MODBUS functions, either via a 16 bits
access or via an access bit.

Device application memory

MODBUS access

Input Discrete
R
W

Coils
R

W

MODBUS Request

Input Registers
Holding
Registers

MODBUS SERVER DEVICE

Figure 7

modbus.org
8May02

http://www.modbus.org/

MODBUS Data Model with only 1 block

8/45

MODBUS.ORG

MODBUS Application Protocol Specification

4.4

Define MODBUS Transaction

The following state diagram describes the generic processing of a MODBUS transaction in server side.
Wait for a MB
indication

[Receive MB indication]
Validate function
code

ExeptionCode_1

[Invalid]
[Valid]
Validate data
Address

ExceptionCode_2

[Invalid]
[valid]
Validate data
value

ExceptionCode_3

[Invalid]
[valid]
Execute MB
function

ExceptionCode_4_5_6

[Invalid]
[Valid]

Send Modbus
Exception
Response

Figure 8

Send Modbus
Response

MODBUS Transaction state diagram

Once the request has been processed by a server, a MODBUS response using the adequate MODBUS server
transaction is built.
Depending on the result of the processing two types of response can be built :
§ A positive MODBUS response :

modbus.org
8May02

http://www.modbus.org/

9/45

MODBUS.ORG

MODBUS Application Protocol Specification

§ the response function code = the request function code
§ A MODBUS Exception response ( see chapter 6.14):
§ the objective is to provide to the client relevant information concerning the error detected during the
processing ;
§ the response function code = the request function code + 0x80 ;
§

modbus.org
8May02

an exception code is provided to indicate the reason of the error.

http://www.modbus.org/

10/45

MODBUS.ORG

MODBUS Application Protocol Specification

5

Function Code Categories

There are three categories of MODBUS Functions codes. They are :
Public Function Codes
• Are well defined function codes ,
• guaranteed to be unique,
• validated by the modbus.org community,
• publically documented
• have available conformance test,
• are documented in the MB IETF RFC,
• includes both defined public assigned function codes as well as unassigned function codes reserved for future use.
User-Defined Function Codes
• there is a defined two ranges of user-defined function codes, ie 65 to 72 and from 100 to 110 decimal.
• user can select and implement a function code without any approval from modbus.org
• there is no guarantee that the use of the selected function code will be unique
• if the user wants to re-position the functionality as a public function code, he must initiate an RFC to introduce the change into
the public category and to have a new public function code assigned.
Reserved Function Codes
• Function Codes currently used by some companies for legacy products and that are not available for public use.

127

PUBLIC function codes
110
100

User Defined Function codes
PUBLIC function codes

72
65

User Defined Function codes

PUBLIC function codes

1
Figure 9

modbus.org
8May02

http://www.modbus.org/

MODBUS Function Code Categories

11/45

MODBUS.ORG

MODBUS Application Protocol Specification

5.1

Public Function Code Definition

Function Codes
code
Physical Discrete Inputs Read Input Discrete

Sub code (hex)

Page

02

02

11

Read Coils

01

01

10

Write Single Coil

05

05

16

Write Multiple Coils

15

0F

37

Physical Input Registers Read Input Register

04

04

14

Read Multiple Registers

03

03

13

Write Single Register

06

06

17

Write Multiple Registers

16

10

39

Read/Write Multiple Registers

23

17

47

Mask Write Register

22

16

46

Read File record

20

6

14

42

Write File record

21

6

15

44

Read Device Identification

43

14

2B

Internal Bits
Or
Physical coils

Bit access

Data
Access
16 bits
access

Internal Registers
Or
Physical Output
Registers

File record access

Encapsulated Interface

6
6.1

Function codes descripitons
01 (0x01) Read Coils

This function code is used to read from 1 to 2000 contiguous status of coils in a remote device. The Request PDU specifies the starting
address, ie the address of the first coil specified, and the number of coils. Coils are addressed starting at zero. Therefore coils 1-16 are
addressed as 0-15.
The coils in the response message are packed as one coil per bit of the data field. Status is indicated as 1= ON and 0= OFF. The LSB of
the first data byte contains the output addressed in the query. The other coils follow toward the high order end of this byte, and from low
order to high order in subsequent bytes.
If the returned output quantity is not a multiple of eight, the remaining bits in the final data byte will be padded with zeros (toward the high
order end of the byte). The Byte Count field specifies the quantity of complete bytes of data.
Request PDU
Function code

1 Byte

0x01

Starting Address

2 Bytes

0x0000 to 0xFFFF

Quantity of coils

2 Bytes

1 to 2000 (0x7D0)

1 Byte

0x01

Response PDU
Function code

modbus.org
8May02

http://www.modbus.org/

12/45

MODBUS.ORG

MODBUS Application Protocol Specification

Byte count

1 Byte

N*

Coil Status

n Byte

n = N or N+1

*N = Quantity of Outputs / 8, if the remainder is different of 0 ⇒ N = N+1
Error
Function code

1 Byte

Function code + 0x80

Exception code

1 Byte

01 or 02 or 03 or 04

Here is an example of a request to read discrete outputs 20–38:
Request

Response

Field Name

(Hex)

Field Name

(Hex)

Function

01

Function

01

Starting Address Hi

00

Byte Count

03

Starting Address Lo

13

Outputs status 27-20

CD

Quantity of Outputs Hi

00

Outputs status 35-28

6B

Quantity of Outputs Lo

13

Outputs status 38-36

05

The status of outputs 27–20 is shown as the byte value CD hex, or binary 1100 1101. Output 27 is the MSB of this byte, and output 20 is
the LSB.
By convention, bits within a byte are shown with the MSB to the left, and the LSB to the right. Thus the outputs in the first byte are ‘
27
through 20’ from left to right. The next byte has outputs ‘ through 28’ left to right. As the bits are transmitted serially, they flow from
,
35
,
LSB to MSB: 20 . . . 27, 28 . . . 35, and so on.
In the last data byte, the status of outputs 38-36 is shown as the byte value 05 hex, or binary 0000 0101. Output 38 is in the sixth bit
position from the left, and output 36 is the LSB of this byte. The five remaining high order bits are zero filled.

F

Note: The five remaining bits (toward the high order end) are zero filled.

modbus.org
8May02

http://www.modbus.org/

13/45

MODBUS.ORG

MODBUS Application Protocol Specification

ENTRY
MB Server receives mb_req_pdu

NO
Function code
supported
YES
ExceptionCode = 01

NO

0x0001 ≤Quantity of Outputs ≤0x07D0

YES
ExceptionCode = 03
NO

Starting Address == OK
AND
Starting Address + Quantity of Outputs == OK
YES

ExceptionCode = 02
Request Processing

NO
ReadDiscreteOutputs

== OK

YES
ExceptionCode = 04
MB Server Sends mb_rsp

MB Server Sends mb_exception_rsp

Figure 10:

6.2

EXIT

Read Coils state diagram

02 (0x02) Read Discrete Inputs

This function code is used to read from 1 to 2000 contiguous status of discrete inputs in a remote device. The Request PDU specifies the
starting address, ie the address of the first input specified, and the number of inputs. Inputs are addressed starting at zero. Therefore
inputs 1-16 are addressed as 0-15.
The discrete inputs in the response message are packed as one input per bit of the data field. Status is indicated as 1= ON; 0= OFF. The
LSB of the first data byte contains the input addressed in the query. The other inputs follow toward the high order end of this byte, and
from low order to high order in subsequent bytes.
If the returned input quantity is not a multiple of eight, the remaining bits in the final data byte will be padded with zeros (toward the high
order end of the byte). The Byte Count field specifies the quantity of complete bytes of data.
Request PDU
Function code

1 Byte

0x02

Starting Address

2 Bytes

0x0000 to 0xFFFF

Quantity of Inputs

2 Bytes

1 to 2000 (0x7D0)

modbus.org
8May02

http://www.modbus.org/

14/45

MODBUS.ORG

MODBUS Application Protocol Specification
Response PDU
Function code

1 Byte

0x02

Byte count

1 Byte

N*

Input Status

N* x 1 Byte

*N = Quantity of Inputs / 8 if the remainder is different of 0 ⇒ N = N+1
Error
Error code

1 Byte

0x82

Exception code

1 Byte

01 or 02 or 03 or 04

Here is an example of a request to read discrete inputs 197 – 218:
Request

Response

Field Name

(Hex)

Function

Field Name

(Hex)

02

Function

02

Starting Address Hi

00

Byte Count

03

Starting Address Lo

C4

Inputs Status 204-197

AC

Quantity of Inputs Hi

00

Inputs Status 212-205

DB

Quantity of Inputs Lo

16

Inputs Status 218-213

35

The status of discrete inputs 204–197 is shown as the byte value AC hex, or binary 1010 1100. Input 204 is the MSB of this byte, and
input 197 is the LSB.
The status of discrete inputs 218–213 is shown as the byte value 35 hex, or binary 0011 0101. Input 218 is in the third bit position from
the left, and input 213 is the LSB.

F

Note: The two remaining bits (toward the high order end) are zero filled.

modbus.org
8May02

http://www.modbus.org/

15/45

MODBUS.ORG

MODBUS Application Protocol Specification

ENTRY
MB Server receives mb_req_pdu

NO
Function code
supported
YES
ExceptionCode = 01

NO

0x0001 ≤ Quantity of Inputs ≤ 0x07D0

YES
ExceptionCode = 03
NO

Starting Address == OK
AND
Starting Address + Quantity of Inputs == OK
YES

ExceptionCode = 02

Request Processing

NO
ReadDiscreteInputs

== OK

YES

ExceptionCode = 04

MB Server Sends mb_rsp

MB Server Sends mb_exception_rsp

Figure 11:

modbus.org
8May02

http://www.modbus.org/

EXIT

Read Discrete Inputs state diagram

16/45

MODBUS.ORG

MODBUS Application Protocol Specification

6.3

03 (0x03) Read Holding Registers

This function code is used to read the contents of a contiguous block of holding registers in a remote device. The Request PDU specifies
the starting register address and the number of registers. Registers are addressed starting at zero. Therefore registers 1-16 are
addressed as 0-15.
The register data in the response message are packed as two bytes per register, with the binary contents right justified within each byte.
For each register, the first byte contains the high order bits and the second contains the low order bits.
Request
Function code

1 Byte

0x03

Starting Address

2 Bytes

0x0000 to 0xFFFF

Quantity of Registers

2 Bytes

1 to 125 (0x7D)

Function code

1 Byte

0x03

Byte count

1 Byte

2 x N*

Register value

N* x 2 Bytes

Response

*N = Quantity of Registers
Error
Error code

1 Byte

0x83

Exception code

1 Byte

01 or 02 or 03 or 04

Here is an example of a request to read registers 108 – 110:
Request

Response

Field Name

(Hex)

Function

Field Name

(Hex)

03

Function

03

Starting Address Hi

00

Byte Count

06

Starting Address Lo

6B

Register value Hi (108)

02

No. of Registers Hi

00

Register value Lo (108)

2B

No. of Registers Lo

03

Register value Hi (109)

00

Register value Lo (109)

00

Register value Hi (110)

00

Register value Lo (110)

64

The contents of register 108 are shown as the two byte values of 02 2B hex, or 555 decimal. The contents of registers 109–110 are 00 00
and 00 64 hex, or 0 and 100 decimal, respectively.

modbus.org
8May02

http://www.modbus.org/

17/45

MODBUS.ORG

MODBUS Application Protocol Specification

ENTRY
MB Server receives mb_req_pdu

NO
Function code
supported
YES
ExceptionCode = 01

NO

0x0001 ≤ Quantity of Registers ≤0x007D

YES
ExceptionCode = 03
NO

Starting Address == OK
AND
Starting Address + Quantity of Registers == OK
YES

ExceptionCode = 02
Request Processing

NO
ReadMultipleRegisters ==

OK

YES

ExceptionCode = 04

MB Server Sends mb_rsp

MB Server Sends mb_exception_rsp

Figure 12:

6.4

EXIT

Read Holding Registers state diagram

04 (0x04) Read Input Registers

This function code is used to read from 1 to approx. 125 contiguous input registers in a remote device. The Request PDU specifies the
starting register address and the number of registers. Registers are addressed starting at zero. Therefore input registers 1-16 are
addressed as 0-15.
The register data in the response message are packed as two bytes per register, with the binary contents right justified within each byte.
For each register, the first byte contains the high order bits and the second contains the low order bits.
Request
Function code

1 Byte

0x04

Starting Address

2 Bytes

0x0000 to 0xFFFF

Quantity of Input Registers

2 Bytes

0x0001 to 0x007D

Function code

1 Byte

0x04

Byte count

1 Byte

2 x N*

Input Registers

N* x 2 Bytes

Response

*N = Quantity of Input Registers

modbus.org
8May02

http://www.modbus.org/

18/45

MODBUS.ORG

MODBUS Application Protocol Specification
Error
Error code

1 Byte

0x84

Exception code

1 Byte

01 or 02 or 03 or 04

modbus.org
8May02

http://www.modbus.org/

19/45

MODBUS.ORG

MODBUS Application Protocol Specification

Here is an example of a request to read input register 9:
Request

Response

Field Name

(Hex)

Field Name

(Hex)

Function

04

Function

04

Starting Address Hi

00

Byte Count

02

Starting Address Lo

08

Input Reg. 9 Hi

00

Quantity of Input Reg. Hi

00

Input Reg. 9 Lo

0A

Quantity of Input Reg. Lo

01

The contents of input register 9 are shown as the two byte values of 00 0A hex, or 10 decimal.

ENTRY
MB Server receives mb_req_pdu

NO
Function code
supported
YES
ExceptionCode = 01

NO

0x0001 ≤Quantity of Registers ≤ 0x007D

YES
ExceptionCode = 03
NO

Starting Address == OK
AND
Starting Address + Quantity of Registers == OK
YES

ExceptionCode = 02
Request Processing

NO
ReadInputRegisters

== OK

YES

ExceptionCode = 04

MB Server Sends mb_rsp

MB Server Sends mb_exception_rsp

Figure 13:

6.5

EXIT

Read Input Registers state diagram

05 (0x05) Write Single Coil

This function code is used to write a single output to either ON or OFF in a remote device.

modbus.org
8May02

http://www.modbus.org/

20/45

MODBUS.ORG

MODBUS Application Protocol Specification

The requested ON/OFF state is specified by a constant in the request data field. A value of FF 00 hex requests the output to be ON. A
value of 00 00 requests it to be OFF. All other values are illegal and will not affect the output.
The Request PDU specifies the address of the coil to be forced. Coils are addressed starting at zero. Therefore coil 1 is addressed as 0.
The requested ON/OFF state is specified by a constant in the Coil Value field. A value of 0XFF00 requests the coil to be ON. A value of
0X0000 requests the coil to be off. All other values are illegal and will not affect the coil.
The normal response is an echo of the request, returned after the coil state has been written.
Request
Function code

1 Byte

0x05

Output Address

2 Bytes

0x0000 to 0xFFFF

Output Value

2 Bytes

0x0000 or 0xFF00

Function code

1 Byte

0x05

Output Address

2 Bytes

0x0000 to 0xFFFF

Output Value

2 Bytes

0x0000 or 0xFF00

Error code

1 Byte

0x85

Exception code

1 Byte

01 or 02 or 03 or 04

Response

Error

Here is an example of a request to write Coil 173 ON:
Request

Response

Field Name

(Hex)

Field Name

(Hex)

Function

05

Function

05

Output Address Hi

00

Output Address Hi

00

Output Address Lo

AC

Output Address Lo

AC

Output Value Hi

FF

Output Value Hi

FF

Output Value Lo

00

Output Value Lo

00

modbus.org
8May02

http://www.modbus.org/

21/45

MODBUS.ORG

MODBUS Application Protocol Specification

ENTRY
MB Server receives mb_req_pdu

NO
Function code
supported
YES
ExceptionCode = 01

NO
Output Value == 0x0000
OR 0xFF00
YES

ExceptionCode = 03

NO

Output Address == OK

YES
ExceptionCode = 02
Request Processing

NO
WriteSingleOutput ==

OK

YES
ExceptionCode = 04
MB Server Sends mb_rsp

MB Server Sends mb_exception_rsp

Figure 14:

6.6

EXIT

Write Single Output state diagram

06 (0x06) Write Single Register

This function code is used to write a single holding register in a remote device.
The Request PDU specifies the address of the register to be written. Registers are addressed starting at zero. Therefore register 1 is
addressed as 0.
The normal response is an echo of the request, returned after the register contents have been written.
Request
Function code

1 Byte

0x06

Register Address

2 Bytes

0x0000 to 0xFFFF

Register Value

2 Bytes

0x0000 or 0xFFFF

Function code

1 Byte

0x06

Register Address

2 Bytes

0x0000 to 0xFFFF

Register Value

2 Bytes

0x0000 or 0xFFFF

Error code

1 Byte

0x86

Exception code

1 Byte

01 or 02 or 03 or 04

Response

Error

modbus.org
8May02

http://www.modbus.org/

22/45

MODBUS.ORG

MODBUS Application Protocol Specification

modbus.org
8May02

http://www.modbus.org/

23/45

MODBUS.ORG

MODBUS Application Protocol Specification

Here is an example of a request to write register 2 to 00 03 hex:
Request

Response

Field Name

(Hex)

Field Name

(Hex)

Function

06

Function

06

Register Address Hi

00

Register Address Hi

00

Register Address Lo

01

Register Address Lo

01

Register Value Hi

00

Register Value Hi

00

Register Value Lo

03

Register Value Lo

03

ENTRY
MB Server receives mb_req_pdu

NO
Function code
supported
YES
ExceptionCode = 01

NO

0x0000 ≤Register Value ≤ 0xFFFF

YES
ExceptionCode = 03

NO

Register Address == OK

YES
ExceptionCode = 02
Request Processing

NO

WriteSingleRegister ==

OK

YES
ExceptionCode = 04
MB Server Sends mb_rsp

MB Server Sends mb_exception_rsp

Figure 15:

modbus.org
8May02

http://www.modbus.org/

EXIT

Write Single Register state diagram

24/45

MODBUS.ORG

MODBUS Application Protocol Specification

6.7

15 (0x0F) Write Multiple Coils

This function code is used to force each coil in a sequence of coils to either ON or OFF in a remote device. The Request PDU specifies
the coil references to be forced. Coils are addressed starting at zero. Therefore coil 1 is addressed as 0.
The requested ON/OFF states are specified by contents of the request data field. A logical '1' in a bit position of the field requests the
corresponding output to be ON. A logical '0' requests it to be OFF.
The normal response returns the function code, starting address, and quantity of coils forced.
Request PDU
Function code

1 Byte

0x0F

Starting Address

2 Bytes

0x0000 to 0xFFFF

Quantity of Outputs

2 Bytes

0x0001 to 0x07B0

Byte Count

1 Byte

N*

Outputs Value

N* x 1 Byte

*N = Quantity of Outputs / 8, if the remainder is different of 0 ⇒ N = N+1
Response PDU
Function code

1 Byte

0x0F

Starting Address

2 Bytes

0x0000 to 0xFFFF

Quantity of Outputs

2 Bytes

0x0001 to 0x07B0

Error code

1 Byte

0x8F

Exception code

1 Byte

01 or 02 or 03 or 04

Error

modbus.org
8May02

http://www.modbus.org/

25/45

MODBUS.ORG

MODBUS Application Protocol Specification

Here is an example of a request to write a series of 10 coils starting at coil 20:
The request data contents are two bytes: CD 01 hex (1100 1101 0000 0001 binary). The binary bits correspond to the outputs in the
following way:
Bit:

1

1

0

0

1

1

0

1

0

0

0

0

0

0

0

1

Output:

27

26

25

24

23

22

21

20













29

28

The first byte transmitted (CD hex) addresses outputs 27-20, with the least significant bit addressing the lowest output (20) in this set.
The next byte transmitted (01 hex) addresses outputs 29-28, with the least significant bit addressing the lowest output (28) in this set.
Unused bits in the last data byte should be zero–filled.
Request

Response

Field Name

(Hex)

Field Name

(Hex)

Function

0F

Function

0F

Starting Address Hi

00

Starting Address Hi

00

Starting Address Lo

13

Starting Address Lo

13

Quantity of Outputs Hi

00

Quantity of Outputs Hi

00

Quantity of Outputs Lo

0A

Quantity of Outputs Lo

0A

Byte Count

02

Outputs Value Hi

CD

Outputs Value Lo

01

ENTRY
MB Server receives mb_req_pdu

NO
Function code
supported

*N = Quantity of Outputs / 8, if the
remainder is different of 0 ⇒ N = N+1

YES
ExceptionCode = 01
NO

0x0001 ≤ Quantity of Outputs ≤ 0x07B0
AND
Byte Count = N*
YES

ExceptionCode = 03
NO

Starting Address == OK
AND
Starting Address + Quantity of Outputs == OK
YES

ExceptionCode = 02
Request Processing

NO
WriteMultipleOutputs

== OK

YES

ExceptionCode = 04

MB Server Sends mb_rsp

MB Server Sends mb_exception_rsp

modbus.org
8May02

http://www.modbus.org/

EXIT

26/45

MODBUS.ORG

MODBUS Application Protocol Specification

Figure 16:

modbus.org
8May02

http://www.modbus.org/

Write Multiple Outputs state diagram

27/45

MODBUS.ORG

MODBUS Application Protocol Specification

6.8

16 (0x10) Write Multiple registers

This function code is used to write a block of contiguous registers (1 to approx. 120 registers) in a remote device.
The requested written values are specified in the request data field. Data is packed as two bytes per register.
The normal response returns the function code, starting address, and quantity of registers written.
Request PDU
Function code

1 Byte

0x10

Starting Address

2 Bytes

0x0000 to 0xFFFF

Quantity of Registers

2 Bytes

0x0001 to 0x0078

Byte Count

1 Byte

2 x N*

Registers Value

N* x 2 Bytes

value

Function code

1 Byte

0x10

Starting Address

2 Bytes

0x0000 to 0xFFFF

Quantity of Registers

2 Bytes

1 to 123 (0x7B)

*N = Quantity of Registers
Response PDU

Error
Error code

1 Byte

0x90

Exception code

1 Byte

01 or 02 or 03 or 04

Here is an example of a request to write two registers starting at 2 to 00 0A and 01 02 hex:
Request

Response

Field Name

(Hex)

Field Name

(Hex)

Function

10

Function

10

Starting Address Hi

00

Starting Address Hi

00

Starting Address Lo

01

Starting Address Lo

01

Quantity of Registers Hi

00

Quantity of Registers Hi

00

Quantity of Registers Lo

02

Quantity of Registers Lo

02

Byte Count

04

Registers Value Hi

00

Registers Value Lo

0A

Registers Value Hi

01

Registers Value Lo

02

modbus.org
8May02

http://www.modbus.org/

28/45

MODBUS.ORG

MODBUS Application Protocol Specification

ENTRY
MB Server receives mb_req_pdu

NO
Function code
supported
YES
ExceptionCode = 01
0x0001 ≤ Quantity of Registers ≤ 0x007B
AND
Byte Count == Quantity of Registers x 2

NO

YES
ExceptionCode = 03
NO

Starting Address == OK
AND
Starting Address + Quantity of Registers == OK
YES

ExceptionCode = 02
Request Processing

NO
WriteMultipleRegisters

== OK

YES

ExceptionCode = 04

MB Server Sends mb_rsp

MB Server Sends mb_exception_rsp

Figure 17:

6.9

EXIT

Write Multiple Registers state diagram

20 (0x14) Read File Record

This function code is used to perform a file record read. All Request Data Lengths are provided in terms of number of bytes and all
Record Lengths are provided in terms of registers.
A file is an organization of records. Each file contains 10000 records, addressed 0000 to 9999 decimal or 0X0000 to 0X270F. For
example, record 12 is addressed as 12.
The function can read multiple groups of references. The groups can be separating (non-contiguous), but the references within each
group must be sequential.
Each group is defined in a separate ‘
sub-request’field that contains 7 bytes:
The reference type: 1 byte (must be specified as 6)
The File number: 2 bytes
The starting record number within the file: 2 bytes
The length of the record to be read: 2 bytes.

modbus.org
8May02

http://www.modbus.org/

29/45

MODBUS.ORG

MODBUS Application Protocol Specification

The quantity of registers to be read, combined with all other fields in the expected response, must not exceed the allowable length of
MODBUS messages: 256 bytes.
The normal response is a series of ‘
sub-responses’ one for each ‘
,
sub-request’ The byte count field is the total combined count of bytes
.
in all ‘
sub-responses’ In addition, each ‘
.
sub-response’contains a field that shows its own byte count.
Request PDU
Function code

1 Byte

0x14

Byte Count

1 Byte

0x07 to 0xF5 bytes

Sub-Req. x, Reference Type

1 Byte

06

Sub-Req. x, File Number

2 Bytes

0x0000 to 0xFFFF

Sub-Req. x, Record Number

2 Bytes

0x0000 to 0x270F

Sub-Req. x, Register Length

2 Bytes

N

Function code

1 Byte

0x14

Resp. data Length

1 Byte

0x07 to 0xF5

Sub-Req. x, File Resp. length

1 Byte

0x07 to 0xF5

Sub-Req. x, Reference Type

1 Byte

6

Sub-Req. x, Record Data

N x 2 Bytes

Sub-Req. x+1, ...

Response PDU

Sub-Req. x+1, ...

Error
Error code

1 Byte

0x94

Exception code

1 Byte

01 or 02 or 03 or 04 or 08

Here is an example of a request to read two groups of references from remote device:
§

Group 1 consists of two registers from file 4, starting at register 1 (address 0001).

§

Group 2 consists of two registers from file 3, starting at register 9 (address 0009).
Request

Response

Field Name

(Hex)

Field Name

(Hex)

Function

14

Function

14

Byte Count

0C

Resp. Data length

0E

Sub-Req. 1, Ref. Type

06

Sub-Req. 1, File resp. length

05

Sub-Req. 1, File Number Hi

00

Sub-Req. 1, Ref. Type

06

Sub-Req. 1, File Number Lo

04

Sub-Req. 1, Record. Data Hi

0D

Sub-Req. 1, Record number Hi

00

Sub-Req. 1, Record. Data Lo

FE

Sub-Req. 1, Record number Lo

01

Sub-Req. 1, Record. Data Hi

00

Sub-Req. 1, Record Length Hi

00

Sub-Req. 1, Record. Data Lo

20

Sub-Req. 1, Record Length Lo

02

Sub-Req. 2, File resp. length

05

Sub-Req. 2, Ref. Type

06

Sub-Req. 2, Ref. Type

06

Sub-Req. 2, File Number Hi

00

Sub-Req. 2, Record. Data Hi

33

Sub-Req. 2, File Number Lo

03

Sub-Req. 2, Record. Data Lo

CD

Sub-Req. 2, Record number Hi

00

Sub-Req. 2, Record. Data Hi

00

Sub-Req. 2, Record number Lo

09

Sub-Req. 2, Record. Data Lo

40

modbus.org
8May02

http://www.modbus.org/

30/45

MODBUS.ORG

MODBUS Application Protocol Specification

Sub-Req. 2, Record Length Hi

00

Sub-Req. 2, Record Length Lo

02

ENTRY
MB Server receives mb_req_pdu

NO
Function code
supported
YES
ExceptionCode = 01

NO
0x07 ≤ Byte Count ≤ 0xF5
For each Sub-Req
YES

ExceptionCode = 03

Reference Type == OK
AND
File Number == OK
AND
Starting Address == OK
AND
Starting Address + Register Count == OK

NO

YES
ExceptionCode = 02
Request Processing

NO
ReadGeneralReference

== OK

YES

ExceptionCode = 04

MB Server Sends mb_rsp

EXIT

MB Server Sends mb_exception_rsp

Figure 18:

6.9.1

Read File Record state diagram

21 (0x15) Write File Record

This function code is used to perform a file record write. All Request Data Lengths are provided in terms of number of bytes and all
Record Lengths are provided in terms of the number of 16-bit words.
A file is an organization of records. Each file contains 10000 records, addressed 0000 to 9999 decimal or 0X0000 to 0X270F. For
example, record 12 is addressed as 12.
The function can write multiple groups of references. The groups can be separate, ie non–contiguous, but the references within each
group must be sequential.
Each group is defined in a separate ‘
sub-request’field that contains 7 bytes plus the data:

The reference type: 1 byte (must be specified as 6)
The file number: 2 bytes
The starting record number within the file: 2 bytes
The length of the record to be written: 2 bytes

modbus.org
8May02

http://www.modbus.org/

31/45

MODBUS.ORG

MODBUS Application Protocol Specification

The data to be written: 2 bytes per register.
The quantity of registers to be written, combined with all other fields in the query, must not exceed the allowable length of MODBUS
messages: 256 bytes.

The normal response is an echo of the request.
Request PDU
Function code

1 Byte

0x15

Request data length

1 Byte

0x07 to 0xF5

Sub-Req. x, Reference Type

1 Byte

06

Sub-Req. x, File Number

2 Bytes

0x0000 to 0xFFFF

Sub-Req. x, Record Number

2 Bytes

0x0000 to 0x270F

Sub-Req. x, Record length

2 Bytes

N

Sub-Req. x, Record data

N x 2 Bytes

Sub-Req. x+1, ...

Response PDU
Function code

1 Byte

0x15

Response Data length

1 Byte

Sub-Req. x, Reference Type

1 Byte

06

Sub-Req. x, File Number

2 Bytes

0x0000 to 0xFFFFF

Sub-Req. x, Record number

2 Bytes

0x0000 to 0xFFFFF

Sub-Req. x, Record length

2 Bytes

0x0000 to 0xFFFFF N

Sub-Req. x, Record Data

N x 2 Bytes

Sub-Req. x+1, ...

Error
Error code

1 Byte

0x95

Exception code

1 Byte

01 or 02 or 03 or 04 or 08

Here is an example of a request to write one group of references into remote device:
Ÿ The group consists of three registers in file 4, sta rting at register 7 (address 0007).
Request

Response

Field Name

(Hex)

Field Name

(Hex)

Function

15

Function

15

Request Data length

0D

Request Data length

0D

Sub-Req. 1, Ref. Type

06

Sub-Req. 1, Ref. Type

06

Sub-Req. 1, File Number Hi

00

Sub-Req. 1, File Number Hi

00

Sub-Req. 1, File Number Lo

04

Sub-Req. 1, File Number Lo

04

Sub-Req. 1, Record number Hi

00

Sub-Req. 1, Record number Hi

00

Sub-Req. 1, Record number Lo

07

Sub-Req. 1, Record number Lo

07

modbus.org
8May02

http://www.modbus.org/

32/45

MODBUS.ORG

MODBUS Application Protocol Specification

Sub-Req. 1, Record length Hi

00

Sub-Req. 1, Record length Hi

00

Sub-Req. 1, Record length Lo

03

Sub-Req. 1, Record length Lo

03

Sub-Req. 1, Record Data Hi

06

Sub-Req. 1, Record Data Hi

06

Sub-Req. 1, Record Data Lo

AF

Sub-Req. 1, Record Data Lo

AF

Sub-Req. 1, Record Data Hi

04

Sub-Req. 1, Record Data Hi

04

Sub-Req. 1, Record Data Lo

BE

Sub-Req. 1, Record Data Lo

BE

Sub-Req. 1, Record Data Hi

10

Sub-Req. 1, Record Data Hi

10

Sub-Req. 1, Reg. Data Lo

0D

Sub-Req. 1, Reg. Data Lo

0D

ENTRY
MB Server receives mb_req_pdu

NO
Function code
supported
YES
ExceptionCode = 01

NO
0x07 ≤ Byte Count ≤ 0xF5
For each Sub-Req
YES

ExceptionCode = 03

Reference Type == OK
AND
File Number == OK
AND
Starting Address == OK
AND
Starting Address + Register Count == OK

NO

YES
ExceptionCode = 02
Request Processing

NO
WriteGeneralReference

== OK

YES

ExceptionCode = 04

MB Server Sends mb_rsp

MB Server Sends mb_exception_rsp

Figure 19:

modbus.org
8May02

http://www.modbus.org/

EXIT

Write File Record state diagram

33/45

MODBUS.ORG

MODBUS Application Protocol Specification

6.10 22 (0x16) Mask Write Register
This function code is used to modify the contents of a specified holding register using a combination of an AND mask, an OR mask, and
the register's current contents. The function can be used to set or clear individual bits in the register.
The request specifies the holding register to be written, the data to be used as the AND mask, and the data to be used as the OR mask.
Registers are addressed starting at zero. Therefore registers 1-16 are addressed as 0-15.
The function’ algorithm is:
s
Result = (Current Contents AND And_Mask) OR (Or_Mask AND And_Mask)
For example:
Hex

Binary

Current Contents =
And_Mask =
Or_Mask =
And_Mask =

12
F2
25
0D

0001 0010
1111 0010
0010 0101
0000 1101

Result =

17

0001 0111

F

Note:
Ÿ That if the Or_Mask value is zero, the result is simply the logical ANDing of the current contents and And_Mask. If the And_Mask value is zero, the
result is equal to the Or_Mask value.
Ÿ The contents of the register can be read with the Read Holding Registers function (function code 03). They could, however, be changed subsequently as
the controller scans its user logic program.

The normal response is an echo of the request. The response is returned after the register has been written.
Request PDU
Function code

1 Byte

0x16

Reference Address

2 Bytes

0x0000 to 0xFFFF

And_Mask

2 Bytes

0x0000 to 0xFFFF

Or_Mask

2 Bytes

0x0000 to 0xFFFF

Function code

1 Byte

0x16

Reference Address

2 Bytes

0x0000 to 0xFFFF

And_Mask

2 Bytes

0x0000 to 0xFFFF

Or_Mask

2 Bytes

0x0000 to 0xFFFF

Response PDU

Error
Error code

1 Byte

0x96

Exception code

1 Byte

01 or 02 or 03 or 04

Here is an example of a Mask Write to register 5 in remote device, using the above mask values.
Request

Response

Field Name

(Hex)

Field Name

(Hex)

Function

16

Function

16

Reference address Hi

00

Reference address Hi

00

modbus.org
8May02

http://www.modbus.org/

34/45

MODBUS.ORG

MODBUS Application Protocol Specification

Reference address Lo

04

Reference address Lo

04

And_Mask Hi

00

And_Mask Hi

00

And_Mask Lo

F2

And_Mask Lo

F2

Or_Mask Hi

00

Or_Mask Hi

00

Or_Mask Lo

25

Or_Mask Lo

25

ENTRY
MB Server receives mb_req_pdu

NO
Function code
supported
YES
ExceptionCode = 01

NO
Reference Address == OK

YES
ExceptionCode = 02

NO

AND_Mask == OK
AND
OR_Mask == OK
YES

ExceptionCode = 03
Request Processing

NO
MaskWriteRegister

ExceptionCode = 04

== OK

YES
MB Server Sends mb_rsp

MB Server Sends mb_exception_rsp

Figure 20:

EXIT

Mask Write Holding Register state diagram

6.11 23 (0x17) Read/Write Multiple registers
This function code performs a combination of one read operation and one write operation in a single MODBUS transaction.
Holding registers are addressed starting at zero. Therefore holding registers 1-16 are addressed as 0-15.
The request specifies the starting address and number of holding registers to be read as well as the starting address, number of holding
registers, and the data to be written. The byte count specifies the number of bytes to follow in the write data field.
The normal response contains the data from the group of registers that were read. The byte count field specifies the quantity of bytes to
follow in the read data field.
Request PDU
Function code

modbus.org
8May02

1 Byte

http://www.modbus.org/

0x17

35/45

MODBUS.ORG

MODBUS Application Protocol Specification

Read Starting Address

2 Bytes

0x0000 to 0xFFFF

Quantity to Read

2 Bytes

0x0001 to approx.0x0076

Write Starting Address

2 Bytes

0x0000 to 0xFFFF

Quantity to Write

2 Bytes

0x0001 to approx. 0X0076

Write Byte Count

1 Byte

2 x N*

Write Registers Value

N* x 2 Bytes

*N = Quantity to Write

Response PDU
Function code

1 Byte

0x17

Byte Count

1 Byte

2 x N'*

Read Registers value

N'* x 2 Bytes

*N' = Quantity to Read
Error
Error code

1 Byte

0x97

Exception code

1 Byte

01 or 02 or 03 or 04

Here is an example of a request to read six registers starting at register 4, and to write three registers starting at register 15:
Request

Response

Field Name

(Hex)

Field Name

(Hex)

Function

17

Function

17

Read Starting Address Hi

00

Byte Count

0C

Read Starting Address Lo

03

Read Registers value Hi

00

Quantity to Read Hi

00

Read Registers value Lo

FE

Quantity to Read Lo

06

Read Registers value Hi

0A

Write Starting Address Hi

00

Read Registers value Lo

CD

Write Starting address Lo

0E

Read Registers value Hi

00

Quantity to Write Hi

00

Read Registers value Lo

01

Quantity to Write Lo

03

Read Registers value Hi

00

Write Byte Count

06

Read Registers value Lo

03

Write Registers Value Hi

00

Read Registers value Hi

00

Write Registers Value Lo

FF

Read Registers value Lo

0D

Write Registers Value Hi

00

Read Registers value Hi

00

Write Registers Value Lo

FF

Read Registers value Lo

FF

Write Registers Value Hi

00

Write Registers Value Lo

FF

modbus.org
8May02

http://www.modbus.org/

36/45

MODBUS.ORG

MODBUS Application Protocol Specification

ENTRY
MB Server receives mb_req_pdu

NO
Function code
supported
YES
ExceptionCode = 01
0x0001 ≤ Quantity of Read ≤0x007D
AND
0x0001 ≤ Quantity of Write ≤ 0x0079
AND
Byte Count == Quantity of Write x 2

NO

YES
ExceptionCode = 03
Read Starting Address == OK
AND
Read Starting Address + Quantity of Read == OK
AND
Write Starting Address == OK
AND
Write Starting Address + Quantity of Write == OK

NO

YES
ExceptionCode = 02
Request Processing

NO
Read/WriteMultipleRegisters == OK

YES

ExceptionCode = 04

MB Server Sends mb_rsp

MB Server Sends mb_exception_rsp

Figure 21:

modbus.org
8May02

http://www.modbus.org/

EXIT

Read/Write Multiple Registers state diagram

37/45

MODBUS.ORG

MODBUS Application Protocol Specification

6.12 43 (0x2B) Read Device Identification
This function code allows reading the identification and additional information relative to the physical and functional description of a
remote device.
The Read Device Identification interface is modeled as an address space composed of a set of addressable data elements. The data
elements are called objects and an object Id identifies them.
The interface consists of 3 categories of objects :
§

Basic Device Identification. All objects of this category are mandatory : VendorName, Product code, and revision number.

§

Regular Device Identification. In addition to Basic data objects, the device provides additional and optional identification and
description data objects. All of the objects of this category are defined in the standard but their implementation is optional .

§

Extended Device Identification. In addition to regular data objects, the device provides additional and optional identification and
description private data. All of these data are device dependent.
Object
Id

Object Name / Description

Type

M/O

category
Basic

0x00

VendorName

ASCII String

Mandatory

0x01

ProductCode

ASCII String

Mandatory

0x02

MajorMinorRevision

ASCII String

Mandatory

0x03

VendorUrl

ASCII String

Optional

0x04

ProductName

ASCII String

Optional

0x05

ModelName

ASCII String

Optional

0x06

UserApplicationName

ASCII String

Optional

0x07

0x7F

Reserved

0x80

0xFF

Private objects may be optionally defined

Optional

The range [0x80 – 0xFF] is Product dependant.

device
dependant

Optional

Request PDU
Function code

1 Byte

0x2B

MEI Type

1 Byte

0x0E

Read Device ID code

1 Byte

01 / 02 / 03 / 04

Object Id

1 Byte

0x00 to 0xFF

Response PDU
Function code

1 Byte

0x2B

MEI Type

1 byte

0x0E

Read Device ID code

1 Byte

Conformity level

1 Byte

More Folows

1 Byte

00 / FF

Next Object Id

1 Byte

Object ID number

Number of objects

1 Byte

01 / 02 / 03 / 04

List Of
Object ID

modbus.org
8May02

Regular

1 Byte

http://www.modbus.org/

38/45

Extended

MODBUS.ORG

MODBUS Application Protocol Specification

Object length

1 Byte

Object Value

1 Byte

Error
Function code

1 Byte

0xAB :

MEI Type

1 Byte

14

Exception code

1 Byte

01, 02, 03, 04

Fc 0x2B + 0x80

Request parameters decsription :
A Modbus Encapsulated Interface assigned number 14 identifies the Read identification request. Four access types are defined :
01 : request to get the basic device identification (stream access)
02 : request to get the regular device identification (stream access)
03 : request to get the extended device identification (stream access)
04 : request to get one specific identification object (individual access)
In the case where the identification data does not fit into a single response, several request/response transactions may be required.
The Object Id byte gives the identification of the first object to obtain. For the first transaction, the client must set the Object Id to 0
to obtain the start of the device identification data. For the following transactions, the client must set the Object Id to the value
returned by the server in its previous response.
If the Object Id does not match any known object, the server responds as if object 0 were pointed out (restart at the beginning).
In case of an individual access: ReadDevId code 04, the Object Id in the request gives the identification of the object to obtain.
If the Object Id doesn't match to any known object, the server returns an exception response with exception code = 02 (Illegal data
address).
Response parameter description :
Function code :

Function code 43 (decimal) 0x2B (hex)

MEI Type

14 (0x0E) MEI Type assigned number for Device Identification Interface

ReadDevId code :

Same as request ReadDevId code : 01, 02, 03 or 04

Conformity Level

Identification conformity level of the device and type of supported access
01 :
basic identification (stream access only)
02 :
regular identification (stream access only)
03 :
extended identification (stream access only)
81 :
basic identification (stream access a nd individual access)
82 :
regular identification (stream access and individual access)
83 :
extended identification (stream access and individual access)

More Follows

In case of ReadDevId codes 01, 02 or 03 (stream access),
If the identification data doesn't fit into a single response, several request/response transactions may be
required.
00 : no more Object are available
FF : other identification Object are available and further Modbus transactions are required
In case of ReadDevId code 04 (individual access),
this field must be set to 00.

Next Object Id

If " MoreFollows = FF " , identification of the next Object to be asked for.
if " MoreFollows = 00 " , must be set to 00 (useless)

Number Of Objects

Number of identification Object returned in the response
(for an individual access, Number Of Objects = 1)

Object0.Id

Identification of the first Object returned in the PDU (stream access)
or the requested Object (individual access)

modbus.org
8May02

http://www.modbus.org/

39/45

MODBUS.ORG

MODBUS Application Protocol Specification

Object0.Length

Length of the first Object in byte

Object0.Value

Value of the first Object (Object0.Length bytes)


ObjectN.Id

Identification of the last Object (within the response)

ObjectN.Length

Length of the last Object in byte

ObjectN.Value

Value of the last Object (ObjectN.Length bytes)

Example of a Read Device Identification request for " Basic device identification " : In this example all information are sent in one
response PDU.

Request

Response

Field Name

Value

Field Name

Value

Function

2B

Function

2B

MEI Type

0E

MEI Type

0E

Read Dev Id code

01

Read Dev Id Code

01

Object Id

00

Conformity Level

01

More Follows

00

NextObjectId

00

Number Of Objects

03

Object Id

00

Object Length

16

Object Value

" Company identification "

Object Id

01

Object Length

0A

Object Value

" Product code "

Object Id

02

Object Length

05

Object Value

" V2.11 "

In case of a device that required several transactions to send the response the following transactions is intiated.
First transaction :
Request

Response

Field Name

Value

Field Name

Value

Function

2B

Function

2B

MEI Type

0E

MEI Type

0E

Read Dev Id code

01

Read Dev Id Code

01

Object Id

00

Conformity Level

01

More Follows

FF

NextObjectId

02

Number Of Objects

03

Object Id

00

Object Length

16

Object Value

" Company identification "

modbus.org
8May02

http://www.modbus.org/

40/45

MODBUS.ORG

MODBUS Application Protocol Specification

Object Id

01

Object Length

1A

Object Value

" Product code
XXXXXXXXXXXXXXXX "

Second transaction :
Request

Response

Field Name

Value

Field Name

Value

Function

2B

Function

2B

MEI Type

0E

MEI Type

0E

Read Dev Id code

01

Read Dev Id Code

01

Object Id

02

Conformity Level

01

More Follows

00

NextObjectId

00

Number Of Objects

03

Object Id

02

Object Length

05

Object Value

" V2.11 "

modbus.org
8May02

http://www.modbus.org/

41/45

MODBUS.ORG

MODBUS Application Protocol Specification

ENTRY
MB Server receives mb_req_pdu

NO
Function code
supported
YES
ExceptionCode = 01

NO

Object Id OK
YES

ExceptionCode = 02
Request Processing

Segmentation required

NO
More follows = FF
Next Object ID = XX

More follows = 00
Next Object ID = 00

MB Server Sends mb_rsp

MB Server Sends
mb_exception_rsp

Figure 22:

modbus.org
8May02

http://www.modbus.org/

EXIT

Read Device Identification state diagram

42/45

MODBUS.ORG

MODBUS Application Protocol Specification

7

MODBUS Exception Responses

When a client device sends a request to a server device it expects a normal response. One of four possible events can occur from the
master’ query:
s
• If the server device receives the request without a communication error, and can handle the query normally, it returns a normal
response.
• If the server does not receive the request due to a communication error, no response is returned. The client program will eventually
process a timeout condition for the request.
• If the server receives the request, but detects a communication error (parity, LRC, CRC, ...), no response is returned. The client
program will eventually process a timeout condition for the request.
• If the server receives the request without a communication error, but cannot handle it (for example, if the request is to read a non–
existent output or register), the server will return an exception response informing the client of the nature of the error.
The exception response message has two fields that differentiate it from a normal response:
Function Code Field: In a normal response, the server echoes the function code of the original request in the function code field of the
response. All function codes have a most–significant bit (MSB) of 0 (their values are all below 80 hexadecimal). In an exception
response, the server sets the MSB of the function code to 1. This makes the function code value in an exception response exactly 80
hexadecimal higher than the value would be for a normal response.
With the function code’ MSB set, the client's application program can recognize the exception response and can examine the data field
s
for the exception code.
Data Field: In a normal response, the server may return data or statistics in the data field (any information that was requested in the
request). In an exception response, the server returns an exception code in the data field. This defines the server condition that caused
the exception.
Example of a client request and server exception response
Request

Response

Field Name

(Hex)

Function

Field Name

(Hex)

01

Function

81

Starting Address Hi

04

Exception Code

02

Starting Address Lo

A1

Quantity of Outputs Hi

00

Quantity of Outputs Lo

01

In this example, the client addresses a request to server device. The function code (01) is for a Read Output Status operation. It
requests the status of the output at address 1245 (04A1 hex). Note that only that one output is to be read, as specified by the number of
outputs field (0001).
If the output address is non–existent in the server device, the server will return the exception response with the exception code shown
(02). This specifies an illegal data address for the slave.
A listing of exception codes begins on the next page.

modbus.org
8May02

http://www.modbus.org/

43/45

MODBUS.ORG

MODBUS Application Protocol Specification

MODBUS Exception Codes
Code

Name

Meaning
The function code received in the query is not an allowable
action for the server (or slave). This may be because the
function code is only applicable to newer devices, and was not
implemented in the unit selected. It could also indicate that the
server (or slave) is in the wrong state to process a request of
this type, for example because it is unconfigured and is being
asked to return register values.

01

ILLEGAL FUNCTION

02

ILLEGAL DATA ADDRESS

The data address received in the query is not an allowable
address for the server (or slave). More specifically, the
combination of reference number and transfer length is
invalid. For a controller with 100 registers, a request with
offset 96 and length 4 would succeed, a request with offset 96
and length 5 will generate exception 02.

03

ILLEGAL DATA VALUE

A value contained in the query data field is not an allowable
value for server (or slave). This indicates a fault in the
structure of the remainder of a complex request, such as that
the implied length is incorrect. It specifically does NOT mean
that a data item submitted for storage in a register has a value
outside the expectation of the application program, since the
MODBUS protocol is unaware of the significance of any
particular value of any particular register.

04

SLAVE DEVICE FAILURE

An unrecoverable error occurred while the server (or slave)
was attempting to perform the requested action.

05

ACKNOWLEDGE

Specialized use in conjunction with programming commands.
The server (or slave) has accepted the request and is
processing it, but a long duration of time will be required to do
so. This response is returned to prevent a timeout error from
occurring in the client (or master). The client (or master) can
next issue a Poll Program Complete message to determine if
processing is completed.

06

SLAVE DEVICE BUSY

Specialized use in conjunction with programming commands.
The server (or slave) is engaged in processing a long–
duration program command. The client (or master) should
retransmit the message later when the server (or slave) is
free.

08

MEMORY PARITY ERROR

Specialized use in conjunction with function codes 20 and 21
and reference type 6, to indicate that the extended file area
failed to pass a consistency check.
The server (or slave) attempted to read record file, but
detected a parity error in the memory. The client (or master)
can retry the request, but service may be required on the
server (or slave) device.

0A

GATEWAY PATH UNAVAILABLE

Specialized use in conjunction with gateways, indicates that
the gateway was unable to allocate an internal communication
path from the input port to the output port for processing the
request. Usually means that the gateway is misconfigured or
overloaded.

0B

GATEWAY TARGET DEVICE
FAILED TO RESPOND

Specialized use in conjunction with gateways, indicates that
no response was obtained from the target device. Usually
means that the device is not present on the network.

modbus.org
8May02

http://www.modbus.org/

44/45

MODBUS.ORG

MODBUS Application Protocol Specification

modbus.org
8May02

http://www.modbus.org/

45/45


MODBUS_materiały.rar > MODBUS_ES-1510.pdf

PROTOKÓŁ MODBUS DLA PRZETWORNIKA ES-1510

OPIS PROTOKOŁU MODBUS DLA
PRZETWORNIKA ES-1510
Format danych:






protokół:
prędkości:
ilość bitów danych:
ilość bitów parzystości:
ilość bitów STOPu

MODBUS RTU
2400, 4800, 9600, 19200 b/s
8
0
2
Format ramki:

Znacznik
początku
T1-T2-T3-T4

Adres

Funkcja

Dane

CRC

Znacznik końca

8 bitów

8 bitów

N x 8 bitów

16 bitów

T1-T2-T3-T4

T1-T2-T3-T4 – przerwa czasowa trwająca minimum 3.5 x (czas trwania pojedynczego znaku).

Zaimplementowane funkcje protokołu MODBUS:
Nr funkcji
0x01
0x03
0x06
0x10

Opis
Odczyt stanu wyjść binarnych
Odczyt rejestrów
Zapis do pojedynczego rejestru
Zapis do wielu rejestrów

Dane umieszczone są w rejestrach 8 bitowych, 16 bitowych lub 32 bitowych. Zmienne konfiguracyjne umieszczone
są w innym obszarze pamięci niż zmienne pomiarowe. Rejestry 32-bitowe zawierają liczby typu float w standardzie
IEEE-754 (http://standards.ieee.org/). W pierwszej kolejności przesyłane jest starsze słowo, a następnie młodsze
słowo. Aby zdekodować liczbę float należy zamienić miejscami rejestry.
Przykład: Otrzymano wartości kolejnych dwóch rejestrów: 4000 = 0xfbe7, 4001 = 0x4009. Aby zdekodować liczbę
float trzeba zamienić miejscami rejestry. W wyniku powinniśmy otrzymać liczbę 32-bitową: 0x4009fbe7, co jest
równe “2.156”.
Stany wyjść binarnych formatowane są jako dane 8-bitowe – dopełnienie do 8 bitów jest wypełniane zerami.
W przypadku odczytu wielu rejestrów (funkcja 0x03) możliwe jest odczytanie max 50 rejestrów (100B) w jednej
ramce.

Mapa rejestrów:

Mapa rejestrów podzielona została na następujące obszary:
Zakres adresów
0000-0001
3000-3004
4000-4045

Typ danych
stan binarny 0,1
integer (16 bitów), float (32 bity)
integer (16 bitów), float (32 bity)

© 2003 Elektro-System s.c.

99-300 Kutno, ul. Sienkiewicza 25
tel. 024 355-05-63 www.elektro-system.com.pl

Opis
Patrz Tabela 1
Patrz Tabela 2
Patrz Tabela 3

1

PROTOKÓŁ MODBUS DLA PRZETWORNIKA ES-1510

Parametry dostępne dla funkcji 0x01:
Lp. Adres (dec)
Symbol
Format danych
Opis
Zakres
1
0000
OUT_1
1 bit
Stan wyjścia OUT_1
0 lub 1
2
0001
OUT_2
1 bit
Stan wyjścia OUT_2
0 lub 1
Tabela 1. Parametry dostępne dla funkcji 0x01 (odczyt stanów wyjść binarnych).

Jedn.
-

Przykład dla funkcji 0x01 (odczyt stanu wyjść binarnych).
Wysyłane jest zapytanie do urządzenia o adresie 0x25 o stan trzech kolejnych wyjść binarnych począwszy od
adresu 0x0002.
W odpowiedzi otrzymujemy stan trzech wyjść binarnych (0x07 - 0b00000111). Pozostałe bity zostały wypełnione
zerami.
Zapytanie
Nazwa pola
Adres urządzenia
Funkcja
Początkowy adres: Hi
Początkowy adres: Lo
Ilość wyjść binarnych: Hi
Ilość wyjść binarnych: Lo
CRC

(HEX)
0x25
0x01
0x00
0x02
0x00
0x03
16 bitów

Odpowiedź
Nazwa pola
Adres urządzenia
Funkcja
Ilość bajtów
Stan wyjść: 0x02-0x04
CRC

(HEX)
0x25
0x01
0x01
0x07
16 bitów

Parametry dostępne dla funkcji 0x03:
Lp. Adres (dec)
Symbol
Format danych
1
3000-3001
T
float (32 bity)
2
3002-3003
RH
float (32 bity)
3
3004
STATUS
integer (16 bitów)
Tabela 2. Parametry dostępne dla funkcji 0x03 (odczyt

Opis
Temperatura
Wilgotność
Status pracy
rejestrów).

Zakres
-40...+120
0...+100
Patrz opis

Jedn.
°C
%
-

Młodszy bajt rejestru STATUS podzielony jest na dwie tetrady (każda po 4 bity). Starsza tetrada (bity 7,6,5,4)
przedstawia status dla wilgotności, a młodsza tetrada (bity 3,2,1,0) przedstawia status dla temperatury.
Poniżej przedstawiono możliwe wartości dla poszczególnych tetrad w rejestrze STATUS.
Bin:
Bin:
Bin:
Bin:
Bin:
Bin:
Bin:
Bin:

Wartość
0000, Hex
0001, Hex
0010, Hex
0011, Hex
0101, Hex
0110, Hex
0111, Hex
1000, Hex

0x00
0x01
0x02
0x03
0x05
0x06
0x07
0x08

Opis
Brak alarmów
Alarm LO
Alarm LOLO
Alarm LO + Alarm LOLO
Alarm HI
Alarm HIHI
Alarm HI + Alarm HIHI
Błąd [ERR]

Przykład dla funkcji 0x03 (odczyt rejestrów).
Wysyłane jest zapytanie do urządzenia o adresie 0x25 o wartości trzech kolejnych rejestrów począwszy od adresu
0x0873.
W odpowiedzi otrzymujemy wartości następujących rejestrów:
• rejestr 0x0873 – wartość 0x0700
• rejestr 0x0874 – wartość 0x5241
• rejestr 0x0875 – wartość 0x653A

© 2003 Elektro-System s.c.

99-300 Kutno, ul. Sienkiewicza 25
tel. 024 355-05-63 www.elektro-system.com.pl

2

PROTOKÓŁ MODBUS DLA PRZETWORNIKA ES-1510

Zapytanie
Nazwa pola
Adres urządzenia
Funkcja
Początkowy adres: Hi
Początkowy adres: Lo
Ilość rejestrów: Hi
Ilość rejestrów: Lo
CRC

(HEX)
0x25
0x03
0x08
0x73
0x00
0x03
16 bitów

Odpowiedź
Nazwa pola
(HEX)
Adres urządzenia
0x25
Funkcja
0x03
Ilość bajtów
0x06
Rejestr 0x0873: Hi
0x07
Rejestr 0x0873: Lo
0x00
Rejestr 0x0874: Hi
0x52
Rejestr 0x0874: Lo
0x41
Rejestr 0x0875: Hi
0x65
Rejestr 0x0875: Lo
0x3A
CRC
16 bitów

Parametry dostępne dla funkcji 0x03, 0x06, 0x10:
Lp. Adres (dec)
Symbol
Format danych
Opis
1
4000-4001
Al_TempHiHi
float (32 bity)
Próg alarmu HiHi (T)
2
4002-4003
Al_TempHi
float (32 bity)
Próg alarmu Hi (T)
3
4004-4005
Al_TempLo
float (32 bity)
Próg alarmu Lo (T)
4
4006-4007
Al_TempLoLo
float (32 bity)
Próg alarmu LoLo (T)
5
4008-4009
Al_WilgHiHi
float (32 bity)
Próg alarmu HiHi (RH)
6
4010-4011
Al_WilgHi
float (32 bity)
Próg alarmu Hi (RH)
7
4012-4013
Al_WilgLo
float (32 bity)
Próg alarmu Lo (RH)
8
4014-4015
Al_WilgLoLo
float (32 bity)
Próg alarmu LoLo (RH)
9
4016-4017
Hi_TempHiHi
float (32 bity)
Histereza dla progu HiHi (T)
10
4018-4019
Hi_TempHi
float (32 bity)
Histereza dla progu Hi (T)
11
4020-4021
Hi_TempLo
float (32 bity)
Histereza dla progu Lo (T)
12
4022-4023
Hi_TempLoLo
float (32 bity)
Histereza dla progu LoLo (T)
13
4024-4025
Hi_WilgHiHi
float (32 bity)
Histereza dla progu HiHi (RH)
14
4026-4027
Hi_WilgHi
float (32 bity)
Histereza dla progu Hi (RH)
15
4028-4029
Hi_WilgLo
float (32 bity)
Histereza dla progu Lo (RH)
16
4030-4031
Hi_WilgLoLo
float (32 bity)
Histereza dla progu LoLo (RH)
17
4032-4033
PoprawkaTemp
float (32 bity)
Poprawka temperatury
18
4034-4035
PoprawkaWilg
float (32 bity)
Poprawka wilgotności
19
4036
Cz_TempHiHi
integer (16 bitów) Czas zwłoki dla alarmu HiHi (T)
20
4037
Cz_TempHi
integer (16 bitów) Czas zwłoki dla alarmu Hi (T)
21
4038
Cz_TempLo
integer (16 bitów) Czas zwłoki dla alarmu Lo (T)
22
4039
Cz_TempLoLo
integer (16 bitów) Czas zwłoki dla alarmu LoLo (T)
23
4040
Cz_WilgHiHi
integer (16 bitów) Czas zwłoki dla alarmu HiHi (RH)
24
4041
Cz_WilgHi
integer (16 bitów) Czas zwłoki dla alarmu Hi (RH)
25
4042
Cz_WilgLo
integer (16 bitów) Czas zwłoki dla alarmu Lo (RH)
26
4043
Cz_WilgLoLo
integer (16 bitów) Czas zwłoki dla alarmu LoLo (RH)
27
4044
Al_statusTemp integer (16 bitów) Aktywacja alarmów temperatury
28
4045
Al_statusWilg
integer (16 bitów) Aktywacja alarmów wilgotności
Tabela 3. Parametry dostępne dla funkcji 0x03, 0x06, 0x10. (zapis i odczyt rejestrów).

Zakres
jak dla float
jak dla float
jak dla float
jak dla float
jak dla float
jak dla float
jak dla float
jak dla float
jak dla float
jak dla float
jak dla float
jak dla float
jak dla float
jak dla float
jak dla float
jak dla float
jak dla float
jak dla float
0...+32768
0...+32768
0...+32768
0...+32768
0...+32768
0...+32768
0...+32768
0...+32768
0 lub 1
0 lub 1

Jedn.
°C
°C
°C
°C
%
%
%
%
°C
°C
°C
°C
%
%
%
%
°C
%
sek
sek
sek
sek
sek
sek
sek
sek
-

Aktywacja alarmów temperatury oraz wilgotności (Al_statusTemp, Al_statusWilg) – 0 alarmy nieaktywne,
1 – alarmy aktywne.

© 2003 Elektro-System s.c.

99-300 Kutno, ul. Sienkiewicza 25
tel. 024 355-05-63 www.elektro-system.com.pl

3

PROTOKÓŁ MODBUS DLA PRZETWORNIKA ES-1510
Przykład dla funkcji 0x06 (zapis pojedynczego rejestru).
Wysyłane jest zapytanie do urządzenia o adresie 0x25, aby zapisało do rejestru 0x0002 wartość 0x1255.
W odpowiedzi otrzymujemy potwierdzenie wykonanej operacji.
Zapytanie
Nazwa pola
Adres urządzenia
Funkcja
Początkowy adres: Hi
Początkowy adres: Lo
Wartość: Hi
Wartość: Lo
CRC

(HEX)
0x25
0x06
0x00
0x02
0x12
0x55
16 bitów

Odpowiedź
Nazwa pola
(HEX)
Adres urządzenia
0x25
Funkcja
0x06
Początkowy adres: Hi
0x00
Początkowy adres: Lo
0x02
Wartość: Hi
0x12
Wartość: Lo
0x55
CRC
16 bitów

Przykład dla funkcji 0x10 (zapis do wielu rejestrów).
Wysyłane jest zapytanie do urządzenia o adresie 0x25 aby zapisało do swoich rejestrów następujące dane:
1.pod adres 0x3000 wartość 0x0015
2.pod adres 0x3001 wartość 0x0134
3.pod adres 0x3002 wartość 0x201F
W odpowiedzi otrzymujemy potwierdzenie wykonanej operacji.
Zapytanie
Nazwa pola
Adres urządzenia
Funkcja
Początkowy adres: Hi
Początkowy adres: Lo
Ilość rejestrów: Hi
Ilość rejestrów: Lo
Ilość bajtów
Wartość Hi
Wartość Lo
Wartość Hi
Wartość Lo
Wartość Hi
Wartość Lo
CRC

(HEX)
0x25
0x10
0x30
0x00
0x00
0x03
0x06
0x00
0x15
0x01
0x34
0x20
0x1F
16 bitów

Odpowiedź
Nazwa pola
(HEX)
Adres urządzenia
0x25
Funkcja
0x10
Początkowy adres: Hi
0x30
Początkowy adres: Lo
0x00
Ilość rejestrów: Hi
0x00
Ilość rejestrów: Lo
0x03
CRC
16 bitów

W przypadku błędu urządzenie zwraca kod błędu w polu danych a w polu funkcji ustawiany jest 7 bit:
Odpowiedź
Nazwa pola
(HEX)
Adres urządzenia
0x25
Funkcja
0x81
Kod błędu
0x02
CRC
16 bitów

W tabeli przedstawione są możliwe kody błędów i ich znaczenie:
Kod
0x01
0x02
0x03

© 2003 Elektro-System s.c.

Znaczenie
Niedozwolona funkcja
Niedozwolony adres danych
Niedozwolona wartość danej

99-300 Kutno, ul. Sienkiewicza 25
tel. 024 355-05-63 www.elektro-system.com.pl

4

PROTOKÓŁ MODBUS DLA PRZETWORNIKA ES-1510
Uwaga !!! Zaimplementowano też funkcje nie będące standardem w protokole MODBUS:
Nr funkcji
0x64
0x65
0x66

Opis
Odczyt parametrów konfiguracyjnych (numer seryjny, prędkość, adres)
Zapis parametrów konfiguracji (prędkość, adres)
Reset urządzenia

Przykład dla funkcji 0x64 (odczyt parametrów konfiguracyjnych - numer seryjny, prędkość, adres).
Każde urządzenie posiada 6-cyfrowy unikatowy numer seryjny. Odczyt parametrów konfiguracyjnych odbywa się po
przez wysłanie na magistralę ramki rozgłoszeniowej (adres urządzenia 0). Według standardu MODBUS na ramkę
rozgłoszeniową żadne urządzenie nie może odpowiedzieć. W tym przypadku (funkcja 0x64), urządzenia będą się
zgłaszać kolejno po sobie. W odpowiedzi prześlą numer seryjny, prędkość na jaką są ustawione oraz adres w sieci:
Po wysłaniu zapytania, otrzymujemy odpowiedź od urządzenia o adresie seryjnym '015892', który pracuje z
prędkością 9600 b/s (0x02) i posiada adres sieciowy 0x25. Numer seryjny przesyłany jest w postaci stringu (6
znaków ASCII).
Zapytanie
Nazwa pola
Adres urządzenia (tryb rozgłoszeniowy)
Funkcja
Zawsze 0x00
CRC

(HEX)
0x00
0x64
0x00
16 bitów

Odpowiedź
Nazwa pola
Adres urządzenia (zawsze 0xff)
Funkcja
Numer seryjny: 1
Numer seryjny: 2
Numer seryjny: 3
Numer seryjny: 4
Numer seryjny: 5
Numer seryjny: 6
Prędkość transmisji
Adres w sieci
CRC

(HEX)
0xff
0x64
0x30 - '0'
0x31 - '1'
0x35 - '5'
0x38 - '8'
0x39 - '9'
0x32 - '2'
0x02
0x25
16 bitów

Tabela prędkości:
Wartość
0x00
0x01
0x02
0x03

© 2003 Elektro-System s.c.

Prędkość transmisji [b/s]
2400
4800
9600
19200

99-300 Kutno, ul. Sienkiewicza 25
tel. 024 355-05-63 www.elektro-system.com.pl

5

PROTOKÓŁ MODBUS DLA PRZETWORNIKA ES-1510
Przykład dla funkcji 0x65 (zapis parametrów konfiguracyjnych - prędkość, adres).
Zapis parametrów konfiguracyjnych umożliwia zmianę prędkości transmisji danego urządzenia a także jego adresu.
Wysłanie ramki rozgłoszeniowej (adres 0x00) dla funkcji 0x65 z numerem seryjnym urządzenia, prędkością
transmisji oraz adresem powoduje, że urządzenie do którego wysłana jest informacja zapisze wysłane informacje,
ustawi nową prędkość transmisji oraz nowy adres sieciowy. Urządzenie nie wysyła potwierdzenia.
Wysyłane jest zapytanie w trybie rozgłoszeniowym (adres: 0x00) do urządzenia o numerze seryjnym '015892' aby
ustalił prędkość transmisji na 19200 b/s (0x03) oraz zmienił adres sieciowy na 0x10.

Zapytanie
Nazwa pola
Adres urządzenia (tryb rozgłoszeniowy)
Funkcja
Numer seryjny: 1
Numer seryjny: 2
Numer seryjny: 3
Numer seryjny: 4
Numer seryjny: 5
Numer seryjny: 6
Prędkość transmisji
Adres w sieci
CRC

(HEX)
0x00
0x65
0x30 - '0'
0x31 - '1'
0x35 - '5'
0x38 - '8'
0x39 - '9'
0x32 - '2'
0x03
0x10
16 bitów

Przykład dla funkcji 0x66 (reset urządzenia).
Reset urządzenie możliwy jest po przesłaniu zapytania z funkcją 0x66 pod dany adres sieciowy. Możliwy jest reset
wszystkich urządzeń w sieci (tryb rozgłoszeniowy). Urządzenie w trybie adresowalnym jak i w trybie
rozgłoszeniowym nie wysyła żadnej odpowiedzi.
Wysyłane jest zapytanie do urządzenia o adresie 0x08. Urządzenie o tym adresie nie wysyła odpowiedzi. Następuje
reset urządzenia.
Zapytanie
Nazwa pola
Adres urządzenia
Funkcja
Zawsze 0x00
CRC

(HEX)
0x08
0x66
0x00
16 bitów

Przetwornik ES1510 umożliwia oprócz mierzenia temperatury i wilgotności sygnalizację przekroczenia ustalonych
progów alarmowych.
Zdefiniowano następujące progi alarmowe

Al_TempHiHi

Al_TempHi

Al_TempLo

Al_TempLoLo

dla temperatury:
– najwyższy próg alarmowy dla temperatury
– wysoki próg alarmowy dla temperatury
– niski próg alarmowy dla temperatury
– najniższy próg alarmowy dla temperatury

Zdefiniowano następujące progi alarmowe

Al_WilgHiHi

Al_WilgHi

Al_WilgLo

Al_WilgLoLo

dla wilgotności:
– najwyższy próg alarmowy dla wilgotności
– wysoki próg alarmowy dla wilgotności
– niski próg alarmowy dla wilgotności
– najniższy próg alarmowy dla wilgotności

© 2003 Elektro-System s.c.

99-300 Kutno, ul. Sienkiewicza 25
tel. 024 355-05-63 www.elektro-system.com.pl

6

PROTOKÓŁ MODBUS DLA PRZETWORNIKA ES-1510
Wartość histerezy dla każdego z progu alarmowego umożliwia ustawienie progu nieczułości. Dokładną zasadę
ilustruje poniższy rysunek.
Czas zwłoki dla każdego z progu alarmowego umożliwia zdefiniowanie opóźnienia zadziałania alarmu (w
sekundach). Dokładną zasadę ilustruje rysunek.
Funkcja alarmów może być aktywowana osobno dla każdego z pomiarów: Al_statusTemp, Al_statusWilg.

Poprawka temperatury (PoprawkaTemp) oraz poprawka wilgotności (PoprawkaWilg) umożliwia wprowadzenie
korekty mierzonych wartości (kalibracja urządzenia).

Dodatkowe informacje na temat protokołu MODBUS na stronie http://www.modbus.org/

© 2003 Elektro-System s.c.

99-300 Kutno, ul. Sienkiewicza 25
tel. 024 355-05-63 www.elektro-system.com.pl

7


MODBUS_materiały.rar > 404.HTM

INPUT {
BORDER-TOP-WIDTH: 1px; BORDER-LEFT-WIDTH: 1px; BORDER-BOTTOM-WIDTH: 1px; BORDER-RIGHT-WIDTH: 1px
}
TEXTAREA {
BORDER-TOP-WIDTH: 1px; BORDER-LEFT-WIDTH: 1px; BORDER-BOTTOM-WIDTH: 1px; BORDER-RIGHT-WIDTH: 1px
}
SELECT {
BORDER-TOP-WIDTH: 1px; BORDER-LEFT-WIDTH: 1px; BORDER-BOTTOM-WIDTH: 1px; BORDER-RIGHT-WIDTH: 1px
}
INPUT {
TEXT-INDENT: 2px
}
INPUT.button {
BORDER-TOP-WIDTH: 1px; BORDER-LEFT-WIDTH: 1px; BORDER-BOTTOM-WIDTH: 1px; BORDER-RIGHT-WIDTH: 1px
}
.postbody {
LINE-HEIGHT: 18px
}


MODBUS_materiały.rar > modbus, kontrola ramki danych crc; pomocy!!!.htm

modbus, kontrola ramki danych crc; pomocy!!!








stats

Regulamin & nbsp;| & nbsp; Punkty & nbsp;| & nbsp; Ostatnie & nbsp;| & nbsp; Szukaj & nbsp;| & nbsp; Wyloguj
[ Udios ]


" );
//-- & gt;





modbus,
kontrola ramki danych crc; pomocy!!! & nbsp;



& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;
& nbsp; & nbsp; & nbsp; Forum elektroda.pl
Strona G³ówna - & gt; Mikrokontrolery



Zobacz poprzedni
temat :: Zobacz nastêpny
temat & nbsp;

Autor
Wiadomo¶æ

KEN Pisz±cy
u¿ytkownik 2 Do³±czy³: 08 Lut 2003 Posty:
76 punkty: 145.58 Ofiarowanie
punktów Down: 0.74MB





Wys³any: 16 Sty 2004
20:29 & nbsp; & nbsp; & nbsp;Temat postu: modbus,
kontrola ramki danych crc; pomocy!!!






CWitam! tworze urz±dzenie do
komunikacji z uk³adami PLC, lecz niestety powali³a mnie transmisja w
protokole MODBAS! nie moge obliczyæ sumy kontrolnej ramki danych
CRC . do tego urz±dzenia
wykorzystuje AVR-a zaprogramowanego w Bascimie, jest tam funkcja
wyliczaj±ca CRC16 ale mi zle wylicza (lub ja cos zle robiê)
przyk³adowe ramki z dobrze wyliczonym CRC : 01 03 00 09 00 01 54
08 (dwa ostatnie bajty czyli 54 i 08 to wlasnie ta nieszczesna suma
kontrolna CRC ) 01
03 02 21 A0 A0 6C (dwa ostatnie bajty to CRC ) Jajk to wyliczyæ zeby
siê zgada³o???? Dzieki za wszelkie rady!!
Raportuj

Powrót
do góry





& nbsp;






document.write(' ');


& nbsp;


document.write(' ');





juntom Pisz±cy
U¿ytkownik 3 Do³±czy³: 11 Wrz 2003 Posty:
91 Pomóg³ osobom:
1 punkty: 19.78 Ofiarowanie
punktów Down: 0.20MB





Wys³any: 16 Sty 2004
20:38 & nbsp; & nbsp; & nbsp;Temat postu: Re:
modbus, kontrola ramki danych crc; pomocy!!!






Ponizej przedstwiam fragment
mojego kodu ¼ród³owego w C /AVR GCC/ liczacy crc16 dla Modbus RTU. Przerobienie tego
na Basic na pewno nie nalezy do trudnych rzeczy. Pamietaj ze w tym
podprogramie zwracana jest suma CRC z zamieniona czescia Hi i
Low. Pozdr. unsigned int CRC16 (unsigned char *buf ,
unsigned char len) { unsigned int temp=0xffff,flag;
unsigned char cnt; while (len--) { temp=temp^*buf++;
cnt=8; while (cnt--) { flag=temp & amp;0x0001;
temp=temp & gt; & gt;1; if (flag) temp=temp^0xa001; } }
cnt=temp & gt; & gt;8; return (temp & lt; & lt;8 | cnt);
}

Raportuj

Powrót
do góry





& nbsp;






document.write(' ');


& nbsp;


document.write(' ');





juntom Pisz±cy
U¿ytkownik 3 Do³±czy³: 11 Wrz 2003 Posty:
91 Pomóg³ osobom:
1 punkty: 19.78 Ofiarowanie
punktów Down: 0.20MB





Wys³any: 16 Sty 2004
22:10 & nbsp; & nbsp; & nbsp;Temat postu: Re:
modbus, kontrola ramki danych crc; pomocy!!!






Zapomnia³em dodaæ ,¿e mam tak¿e
wersjê tablicow± ( szybsz± ale zajmuje wiêcej miejsca w programie ).
Oto ona : /* static prog_char auchCRCHi[256] = {
0x00,0xc1,0x81,0x40,0x01,0xc0,0x80,0x41,0x01,0xc0,
0x80,0x41,0x00,0xc1,0x81,0x40,0x01,0xc0,0x80,0x41,
0x00,0xc1,0x81,0x40,0x00,0xc1,0x81,0x40,0x01,0xc0,
0x80,0x41,0x01,0xc0,0x80,0x41,0x00,0xc1,0x81,0x40,
0x00,0xc1,0x81,0x40,0x01,0xc0,0x80,0x41,0x00,0xc1,
0x81,0x40,0x01,0xc0,0x80,0x41,0x01,0xc0,0x80,0x41,
0x00,0xc1,0x81,0x40,0x01,0xc0,0x80,0x41,0x00,0xc1,
0x81,0x40,0x00,0xc1,0x81,0x40,0x01,0xc0,0x80,0x41,
0x00,0xc1,0x81,0x40,0x01,0xc0,0x80,0x41,0x01,0xc0,
0x80,0x41,0x00,0xc1,0x81,0x40,0x00,0xc1,0x81,0x40,
0x01,0xc0,0x80,0x41,0x01,0xc0,0x80,0x41,0x00,0xc1,
0x81,0x40,0x01,0xc0,0x80,0x41,0x00,0xc1,0x81,0x40,
0x00,0xc1,0x81,0x40,0x01,0xc0,0x80,0x41,0x01,0xc0,
0x80,0x41,0x00,0xc1,0x81,0x40,0x00,0xc1,0x81,0x40,
0x01,0xc0,0x80,0x41,0x00,0xc1,0x81,0x40,0x01,0xc0,
0x80,0x41,0x01,0xc0,0x80,0x41,0x00,0xc1,0x81,0x40,
0x01,0xc1,0x81,0x40,0x01,0xc0,0x80,0x41,0x01,0xc0,
0x80,0xc1,0x00,0xc1,0x81,0x40,0x01,0xc0,0x80,0x41,
0x00,0x41,0x81,0x40,0x00,0xc1,0x81,0x40,0x01,0xc0,
0x80,0x41,0x00,0xc1,0x81,0x40,0x01,0xc0,0x80,0x41,
0x01,0xc0,0x80,0x41,0x00,0xc1,0x81,0x40,0x01,0xc0,
0x80,0x41,0x00,0xc1,0x81,0x40,0x00,0xc1,0x81,0x40,
0x01,0xc0,0x80,0x41,0x01,0xc0,0x80,0x41,0x00,0xc1,
0x81,0x40,0x00,0xc1,0x81,0x40,0x01,0xc0,0x80,0x41,
0x00,0xc1,0x81,0x40,0x01,0xc0,0x80,0x41,0x01,0xc0,
0x80,0x41,0x00,0xc1,0x81,0x40 }; static prog_char
auchCRCLo [256] = {
0x00,0xc0,0xc1,0x01,0xc3,0x03,0x02,0xc2,0xc6,0x06,
0x07,0xc7,0x05,0xc5,0xc4,0x04,0xcc,0x0c,0x0d,0xcd,
0x0f,0xcf,0xce,0x0e,0x0a,0xca,0xcb,0x0b,0xc9,0x09,
0x08,0xc8,0xd8,0x18,0x19,0xd9,0x1b,0xdb,0xda,0x1a,
0x1e,0xde,0xdf,0x1f,0xdd,0x1d,0x1c,0xdc,0x14,0xd4,
0xd5,0x15,0xd7,0x17,0x16,0xd6,0xd2,0x12,0x13,0xd3,
0x11,0xd1,0xd0,0x10,0xf0,0x30,0x31,0xf1,0x33,0xf3,
0xf2,0x32,0x36,0xf6,0xf7,0x37,0xf5,0x35,0x34,0xf4,
0x3c,0xfc,0xfd,0x3d,0xff,0x3f,0x3e,0xfe,0xfa,0x3a,
0x3b,0xfb,0x39,0xf9,0xf8,0x38,0x28,0xe8,0xe9,0x29,
0xeb,0x2b,0x2a,0xea,0xee,0x2e,0x2f,0xef,0x2d,0xed,
0xec,0x2c,0xe4,0x24,0x25,0xe5,0x27,0xe7,0xe6,0x26,
0x22,0xe2,0xe3,0x23,0xe1,0x21,0x20,0xe0,0xa0,0x60,
0x61,0xa1,0x63,0xa3,0xa2,0x62,0x66,0xa6,0xa7,0x67,
0xa5,0x65,0x64,0xa4,0x6c,0xac,0xad,0x6d,0xaf,0x6f,
0x6e,0xae,0xaa,0x6a,0x6b,0xab,0x69,0xa9,0xa8,0x68,
0x78,0xb8,0xb9,0x79,0xbb,0x7b,0x7a,0xba,0xbe,0x7e,
0x7f,0xbf,0x7d,0xbd,0xbc,0x7c,0xb4,0x74,0x75,0xb5,
0x77,0xb7,0xb6,0x76,0x72,0xb2,0xb3,0x73,0xb1,0x71,
0x70,0xb0,0x50,0x90,0x91,0x51,0x93,0x53,0x52,0x92,
0x96,0x56,0x57,0x97,0x55,0x95,0x94,0x54,0x9c,0x5c,
0x5d,0x9d,0x5f,0x9f,0x9e,0x5e,0x5a,0x9a,0x9b,0x5b,
0x99,0x59,0x58,0x98,0x88,0x48,0x49,0x89,0x4b,0x8b,
0x8a,0x4a,0x4e,0x8e,0x8f,0x4f,0x8d,0x4d,0x4c,0x8c,
0x44,0x84,0x85,0x45,0x87,0x47,0x46,0x86,0x82,0x42,
0x43,0x83,0x41,0x81,0x80,0x40 }; */ /*unsigned
int CRC16 (unsigned char *puchMsg,unsigned char usDataLen) {
static unsigned char uIndex=0; static unsigned char
uchCRCHi; static unsigned char uchCRCLo; uchCRCHi=0xff;
uchCRCLo=0xff; while (usDataLen --) { uIndex =
uchCRCHi ^ *puchMsg++; uchCRCHi = uchCRCLo ^
PRG_RDB( & amp;auchCRCHi[uIndex]); uchCRCLo =
PRG_RDB( & amp;auchCRCLo [uIndex]); } return
(uchCRCHi & lt; & lt;8 | uchCRCLo); } */ Mo¿e komu¶ siê
to przyda
Raportuj

Powrót
do góry





& nbsp;






document.write(' ');


& nbsp;


document.write(' ');










Wy¶wietl posty z ostatnich:
Wszystkie
Posty 1 Dzieñ 7
Dni 2 Tygodnie 1
Miesi±c 3 Miesi±ce 6 Miesiêcy 1
Rok & nbsp; Najpierw Starsze Najpierw Nowsze & nbsp;



& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;
& nbsp; & nbsp; & nbsp; Forum elektroda.pl
Strona G³ówna - & gt; Mikrokontrolery
Wszystkie czasy w
strefie EET (Europa)

Strona 1 z
1



¦led¼
odpowiedzi w tym temacie Dodaj
do ulubionych na forum Dodaj
t± wiadomo¶æ do ulubionych & nbsp;










Skocz do: & nbsp; Wybierz forum Schematu/instrukcji/artyku³u |
Requests Bazar
Podzespo³y Og³oszenia Elektronika i
Biznes Elektronika Pocz±tkuj±cy
Serwisanci TV VCR VCP DVD SAT Audio Radia
samochodowe Telefony Komórkowe
GSM Telefony Stacjonarne, Faxy i
Centrale Radiotechnika - CB, KF, UKF,
TV Retro i Lampy AGD Inne Usterki Monitory Komputery
Hardware Overclocking Komputery Software Sieæ
Internet, Sieci LAN WLAN Drukarki,
kserokopiarki i plotery Co kupiæ i gdzie
kupiæ? Akustyka Efekty Wizualne Warsztat Pocz±tkuj±cy,
Laborki, Teoria, Referaty Elektronika
Przemys³owa i Energoelektronika Zabezpieczenia i Alarmy Szukam -
Samochody Usterki
Samochody Tuning samochody i
CarAudio Download
Samochody Uk³ady
scalone Schematy TV Schematy monitorów Schematy
Audio Schematy
Telefonów Schematy VCR VCP SAT
DVD Schematy komputerów,
kopiarek Schematy
Inne Mikrokontrolery Automatyka i
Robotyka Programowanie
ogólne DSP i Transmisja Programy EDA Download Proste Projekty
Hobby Uk³ady elektroniczne - pomys³y i
problemy Baza Wiedzy Upload projekty, programy,
artyku³y Odsy³acze, linki Newsy na
stronie Cwaniacy Na weso³o Elektroda.pl Ogólnie Kosz - Serwisanci sprzêtu
elektronicznego. & nbsp; Mo¿esz pisaæ nowe tematy Mo¿esz odpowiadaæ
w tematach Mo¿esz zmieniaæ swoje posty Nie mo¿esz
usuwaæ swoich postów Mo¿esz g³osowaæ w
ankietach Mo¿esz wysy³aæ raporty do moderatorów w tym
forum Mo¿esz dodawaæ za³±czniki do tego forum Mo¿esz
pobieraæ pliki w tym forum



[ Page generation time:
0.497 seconds ] :: [ 14 queries excuted ] :: [ GZIP compression enabled ]

Administrator Moderatorzy


MODBUS_materiały.rar > Instrukcja%20-%20Modbus.pdf

INSTRUKCJA LABORATORYJNA
(KSR, PSK, IP, SP)

Sieć MODBUS
Rew. pl. 1.26

INSTYTUT INFORMATYKI
ZESPÓŁ PRZEMYSŁOWYCH ZASTOSOWAŃ INFORMATYKI
GLIWICE 2004

Sieć MODBUS

Wstęp

Spis treści
1
2
3
4

5
6
7

Wstęp .......................................................................................................................................................3
Transakcje ................................................................................................................................................4
Adresacja..................................................................................................................................................4
Ramki .......................................................................................................................................................4
4.1 Ramka w trybie znakowym (ASCII).................................................................................................4
4.2 Ramka w trybie binarnym (RTU) .....................................................................................................5
4.3 Pola ramki .........................................................................................................................................5
4.4 Typy przesyłanych zmiennych..........................................................................................................5
4.5 Kontrola poprawności wymian .........................................................................................................5
Przygotowanie scenariusza wymian i opis wymiany informacji..............................................................6
5.1 Powstawanie „dziur” w sieci.............................................................................................................8
Parametryzacja wymian ...........................................................................................................................9
Procedury MODBUS w module BASIC sterownika C50/C100 ............................................................10
7.1 Informacje ogólne o module BASIC...............................................................................................10
7.1.1 Przeznaczenie Modułu BASIC.............................................................................................11
7.1.2 Zmienne................................................................................................................................11
7.1.3 Stałe......................................................................................................................................11
7.2 PROC 0 ...........................................................................................................................................11
7.3 PROC 1 – PROC 2..........................................................................................................................12
7.3.1 PROC1 – wysłanie zapytania lub rozkazu............................................................................12
7.3.2 PROC1 – wysłanie zapytania lub rozkazu............................................................................13
7.4 PROC 3 – PROC 4..........................................................................................................................14
7.4.1 PROC3 – analiza zapytania lub rozkazu ..............................................................................14
7.5 PROC4 – wysyłanie odpowiedzi.....................................................................................................15

2

Sieć MODBUS

1

Wstęp

Wstęp

Standard interfejsu transmisyjnego MODBUS jest szeroko implementowany przez producentów układów
automatyki przemysłowej. Z tego też powodu może on być stosowany do łączenia ze sobą elementów instalacji
pochodzących od różnych producentów. Sieć MODBUS reprezentuje architekturę „Master-Slave” nadaje się
szczególnie dla systemów, w których dane produkowane przez urządzenia peryferyjne przesyłane są do
centralnej stacji nadzorczej. Wydzielona stacja Master posługując się listą wymian cyklicznych oraz
wyzwalanych odpytuje kolejno poszczególnych abonentów sieci. Na podstawie zebranych informacji stacja
nadrzędna podejmuje decyzje i rozsyła dane oraz polecenia sterujące do poszczególnych elementów
wykonawczych. W typowych rozwiązaniach sprzętowych sieć pracuje z niewielkimi szybkościami transmisji
danych (typowe: 9.6 Kb/s, 19.2 Kb/s) na ograniczonym dystansie. Parametry te wynikają z typu zastosowanego
łącza komunikacyjnego (RS-232, RS-422, RS-485, Modem). Moduły PLC oraz sterowniki programowe sieci
MODBUS pozwalają na szeroką diagnostykę pracy abonentów sieci, odczyt liczników błędnych ramek, kodów
błędów itp.
Protokół MODBUS stanowi rozwiązanie firmy Modicon wprowadzone na rynek w 1980r. Prostota tego
protokołu pozwala na łatwą implementację w dowolnym urządzeniu posiadającym mikrokontroler, co
w znacznym stopniu wpłynęło na niskie koszty i popularność. Szczególnie szerokie zastosowanie protokół ten
znalazł w aplikacjach przemysłowych o niskich wymaganiach dotyczących szybkości i częstości przesyłu
danych.
Reguły transmisji są sztywne i uniemożliwiają prowadzenie optymalizacji wymian, celem skrócenia czasu
trwania cyklu pracy sieci. W zamian za to, kosztem wielu ograniczeń, zdecydowanie upraszcza się proces
konfiguracji sieci, minimalizowane są wymagania co do oprogramowania stacji abonenckiej z poziomu aplikacji
a tym samym analiza czasowa przepływu informacji jest bardziej przejrzysta i prostsza do wykonania.
Zasadniczą cechą tego typu sieci jest możliwość bezpośredniej wymiany informacji tylko pomiędzy
wyróżnioną stacją MASTER a dowolnym abonentem, który nosi miano SLAVE, choć znane są odstępstwa od
tej reguły. Stacja MASTER pełni rolę dystrybutora wymian i inicjuje każdą transmisję.
Innymi wyróżnikami tych sieci są:

dwa podstawowe rodzaje wymian:




„zapytanie / polecenie – odpowiedź” będąca wymianą informacji z wybraną stacją abonencką
SLAVE. Wymiana zawiera zawsze żądanie i towarzyszącą jej odpowiedź. Mogą tu mieć miejsce
wymiany cykliczne bądź wyzwalane,

„rozgłoszenie bez odpowiedzi” będąca transmisją do wszystkich abonentów SLAVE, i zawierającą
jedynie ramkę rozgłoszenia,

stały zestaw rozkazów stacji MASTER umożliwiający tylko określone transakcje wymiany,

brak ramek serwisowych,

niezmienne, bez zatrzymania i ponownego uruchomienia sieci, sekwencje cyklicznych wymian danych,
Uproszczenie protokołu transmisji ma jeszcze inną ważną zaletę. Przyspiesza znacznie proces uruchamiania
systemu komunikacyjnego, co nie jest bez znaczenia.
W odróżnieniu od sieci o dostępie „TOKEN – BUS” czy „PDC” w sieci „MASTER–SLAVE”, programuje
się jedynie koprocesor stacji MASTER. Cały ciężar konfiguracji sieci, przeniesiony jest na projekt tak zwanego
scenariusza wymian, który umieszczony jest w pamięci koprocesora stacji MASTER. Upraszcza to analizę pracy
sieci. Koprocesory stacji SLAVE nie są zwykle programowane a realizują jedynie przesłane ze stacji MASTER
polecenia – żądania, dotyczące wymian na styku „koprocesor – jednostka centralna”. Jest to realizowane na
poziomie sprzętowym.

3

Sieć MODBUS

2

Transakcje

Transakcje

Sieć MODBUS działa według modelu wymiany danych „MASTER-SLAVE”. Transakcje przebiegają wg
schematu przedstawionego na poniższym rysunku.

MASTER
(adres, kod funkcji, dane, CRC)
Transakcja n

Transakcja 1
Transakcja 2

SLAVE 1
(adres, kod funkcji,
dane, CRC)

SLAVE 2
(adres, kod funkcji,
dane, CRC)

SLAVE n
(adres, kod funkcji,
dane, CRC)

Rys. 1Transakcje protokołu MODBUS
Kolejność transakcji zależy od przyjętego scenariusza wymian, definiowanego w stacji Master.

3

Adresacja
0
adres typu broadcast

4

od 1 do 247
indywidualne adresy urządzeń Slave

od 248 do 255
Zarezerwowane

Ramki

W omawianym protokole wyróżnia się dwa podstawowe typy ramek:
• „zapytanie / polecenie” – transmisja MASTER–SLAVE,
• „odpowiedź” – transmisja SLAVE–MASTER.
Protokół przewiduje również ramkę „rozgłoszenia”, ale jej budowa jest identyczna jak pozostałych
(występują te same pola informacyjne).
Podstawową strukturę ramki przedstawia rys. 2.

ADU (application data unit)
1B
Adres abonenta

1B

„m” B

Kod funkcji

2B
Słowo kontrolne
(CRC lub LRC)

DANE

PDU (protocol data unit)
Rys. 2. Ogólna budowa ramki MODBUS
4.1

Ramka w trybie znakowym (ASCII)




Start
1 znak
:

bajty są wysyłane szesnastkowo (po dwa znaki ASCII)
odstępy pomiędzy kolejnymi znakami ramki & lt; 1s
maksymalny rozmiar ramki wynosi 513 znaków
Adres
2 znaki

Kod funkcji
2 znaki

Dane
od 0 do 2x252 znaki
...

LRC
2 znaki

End
2 znaki
CR (0D) LF (0A)
4

Sieć MODBUS

Ramki

W polu danych mogą się znaleźć informacje dokładane przez warstwę aplikacji takie jak:
• liczba przesyłanych zmiennych,
• kody sub-funkcji,
• offsety danych,
• wartości danych, itp.

4.2

Ramka w trybie binarnym (RTU)
• Bajty są wysyłane binarnie jako znaki ośmiobitowe,
• każda ramka jest poprzedzona odstępem (cisza na linii) & gt; 3:5T
• odstępy pomiędzy kolejnymi znakami ramki & lt; 1:5T
• wielkość maksymalna 256 bajtów
gdzie T oznacza czas transmisji jednego znaku.
Adres Slave-a

Dane

1 bajt

4.3

Kod funkcji
1 bajt

0-252 bajtów

Kod funkcji

4.4

CRC Low

CRC Hi

Pola ramki

Pole
Adres

Dane

CRC
2 bajty

Zakres
0
1-247
1
2
3
4
5
6
7
8
15
16
17
128-255

znaczenie
Rozgłaszanie (broadcast)
Adres jednostki Slave
Odczyt wyjść binarnych (dyskretnych)
Odczyt wejść binarnych (dyskretnych)
Odczyt n rejestrów (słów)
Odczyt n rejestrów (słów) wejściowych
Zapis jednego bitu
Zapis jednego rejestru
Odczyt statusu
Test diagnostyczny
Zapis n bitów
Zapis n rejestrów
Identyfikacja urządzenia Slave
zarezerwowane
16 bitowe rejestry

Typy przesyłanych zmiennych

• Bitowe
• Dwubajtowe (słowa)
• Czterobajtowe (podwójne słowa)
W celu ułatwienia przesyłania danych przy pomocy ramek z funkcją „odczyt (zapis) n rejestrów” rejestry
powinny zajmować spójny obszar adresowany od 0 do max.

4.5

Kontrola poprawności wymian

Wykrywanie błędów transmisji następuje dzięki kontroli parzystości poprzecznej (bit parzystości znaku) i
wzdłużnej (LRC, CRC). Wykrywanie i diagnozowanie błędów komunikacji następuje przez:
• odesłanie przez stację Slave ramki z kodem błędu:
− 01 – niedozwolona funkcja,
− 02 – niedozwolony zakres danych,
− 03 – niedozwolona wartość danej,
− 04 – uszkodzenie w przyłączonym urządzeniu,
− 05 – potwierdzenie pozytywne,
− 06 – brak gotowości, komunikat usunięty,
− 07 – potwierdzenie negatywne,
− 08 – błąd parzystości pamięci
• przekroczenie czasu oczekiwania na odpowiedź (timeout w jednostce Master).
5

Sieć MODBUS

Przygotowanie scenariusza wymian i opis wymiany informacji

Slave nie odsyła odpowiedzi przy błędach w ramce żądania.

5

Przygotowanie scenariusza wymian i opis wymiany informacji

W polu „DANE” mogą być, w zależności od kodu realizowanej funkcji, zawarte dodatkowe informacje
takie jak:
• kod funkcji dodatkowej (są to dodatkowe funkcje takie jak na przykład: zatrzymanie pracy jednostki
centralnej abonenta, przesłanie programu do jednostki centralnej abonenta, zdalny restart),
• adres danych do odczytu lub zapisu,
• długość łańcucha danych.
Postać poszczególnych pól zależeć będzie oczywiście od konkretnego rozwiązania firmowego, co
w żadnym stopniu nie ogranicza, dalszych rozważań. Przedstawiona na rys. 2 ramka jest typowa zarówno dla
transferu MASTER–SLAVE jak i SLAVE – MASTER. Dwa pola w ramce odpowiedzi stacji SLAVE są takie
same jak w ramce „żądania”. Są to: „Adres Abonenta” oraz „Kod Funkcji”.
Dzięki temu stacja MASTER może dokonać wstępnej weryfikacji poprawności transmisji. Pole danych ma
zmienną długość i w zależności od rozwiązań firmowych może mieć od kilkudziesięciu do kilkuset bajtów.
Podstawowe funkcje realizowane przez stację SLAVE opisano w 4.3. Do omówienia konstrukcji scenariusza
wymian można przyjąć następującą listę funkcji:
• żądanie odczytu ze stacji SLAVE „n” bitów,
• żądanie odczytu ze stacji SLAVE „n” słów,
• żądanie zapisu do stacji SLAVE jednego bitu,
• żądanie zapisu do stacji SLAVE jednego słowa,
• żądanie „szybkiego” odczytu ze stacji SLAVE, nie zsynchronizowanego z cyklem jednostki centralnej
stacji SLAVE, wartości jednego bajtu,
• żądanie zapisu „n” bitów do stacji SLAVE,
• żądanie zapisu „n” słów do stacji SLAVE,
• odczyt ze stacji SLAVE zawartości licznika wymian,
• odczyt / zerowanie w stacji SLAVE rejestrów diagnostycznych.
Mając zdefiniowane funkcje można przystąpić do konstrukcji scenariusza wymian. Scenariusz wymian to
nic innego jak lista zawierająca nazwy zmiennych, których wartości mają być transmitowane. Zawiera ona,
oprócz nazw zmiennych, również kierunek transmisji i co jest bardzo ważne, proponowany zazwyczaj przez
technologię czas ich „odświeżania”. Umieszcza się na niej również planowane wymiany wyzwalane. Stanowi to
pierwszy krok do konfiguracji sieci i poprzedza proces analizy czasowej, której rezultaty zazwyczaj spowodują
modyfikację scenariusza wymian. Ilustruje to rys. 3. Stacja MASTER żąda transmisji wartości zmiennych Z1,
Z2, Z3, Z4, Z5 a sama wysyła wartości zmiennych Z6, Z7, Z8, Z9. Dodatkowo stacja SLAVE 2 żąda transmisji
wartości zmiennej Z4. Są to żądania transmisji cyklicznej.

6

Sieć MODBUS

Maksymalny
cykl sieci














Przygotowanie scenariusza wymian i opis wymiany informacji
odczyt Z1
odczyt Z2
odczyt Z3
odczyt Z4
odczyt Z5
zapis Z6
zapis Z7
zapis Z8
zapis Z9
zapis Z4
zapis Z10
zapis Z11

co 50ms
co 100ms
co 100ms
co 100ms
co 100ms
co 50ms
co 50ms
co 100ms
co 50ms
co 100ms

Cykl wymian

Wymiany
wyzwalane
S1

MASTER
Z1
Z3

Z7

S2

Z10

Z2
Z5

Z4
Z6

S3

Z11

Z4

Z8
Z9

Rys. 3. Scenariusz wymian
Ponadto wprowadzono do scenariusza wymian dwie wymiany wyzwalane Z10 i Z11, których realizacja
będzie inicjowana przez program aplikacyjny jednostki centralnej stacji MASTER. Widać wyraźnie znaczne
„usztywnienie” możliwości transmisji w porównaniu z siecią o dostępie „TOKEN – BUS” ale jak już
wspomniano, ułatwia to znacznie analizę czasową. W sieci o dostępie „TOKEN – BUS” bowiem, nie planuje się
na poziomie koprocesora wymian wyzwalanych. Jakkolwiek w obu typach sieci, są one inicjowane przez
jednostki centralne, to tylko w sieci MASTER-SLAVE konieczne jest ich zaprogramowanie (wprowadzenie do
scenariusza wymian) w koprocesorze Wszystkie bowiem żądania transmisji muszą być zaplanowane a jedynie
ich liczba musi być ograniczona ze względu na maksymalny czas wymiany danych a tym samym ze względu na
gwarantowany czas dostępu do medium. Innymi słowy w sieci MASTER-SLAVE nie można zrealizować
wymiany nie zaplanowanej. Na rys. 4 przedstawiono sposób wymiany informacji dla przyjętego scenariusza
wymian.

7

Sieć MODBUS

Przygotowanie scenariusza wymian i opis wymiany informacji

S1

MASTER

S2

S3

Ż1
Z1
Ż2
Z2
Ż3
Z3
Ż4
Z4
Ż5
Z5
Wymiany
cykliczne

Ż6
Z6
Ż7
Z7
Ż8
Z8
Ż9
Z9
Ż4
Z4

Ż10
Wymiany
wyzwalane

Z10
Ż11
Z11

Rys. 4. Realizacja scenariusza wymian
5.1

Powstawanie „dziur” w sieci

Podobnie jak w innych sieciach, tu również może nastąpić zjawisko powstawania „dziur”. Przyczyną tego
zjawiska jest tylko faktyczny brak abonenta lub jego uszkodzenie. Nie powstaną „dziury” wskutek błędnej
adresacji jak to miało miejsce poprzednio. Każda bowiem wymiana, umieszczona w scenariuszu jest adresowana
do konkretnego abonenta. Oczywiście można zrobić błąd planując wymianę do nieistniejącego abonenta, ale
analizując słowo raportu, na etapie choćby testowania, jest on łatwy do wychwycenia. Brak krążącego żetonu nie
wymaga, aby adresy abonentów były ciągiem kolejnych liczb naturalnych. Bezpośrednim natomiast efektem
braku abonenta jest opóźnienie w pracy sieci, które równe jest czasowi oczekiwania na odpowiedź,
powiększonemu o czas transmisji ramki od stacji MASTER. Na pierwszy rzut oka wydawało by się, że mamy do
czynienia z identyczną sytuacją jak w sieciach z żetonem. Otóż tak nie jest. Należy bowiem pamiętać, że w
8

Sieć MODBUS

Parametryzacja wymian

sieciach z żetonem, aby się przekonać o tym, że abonent jest nieobecny, wystarczyło wysłać krótką ramkę –
żeton. Tutaj natomiast może być tak, że do nieistniejącego abonenta wysyłana jak ramka bardzo długa, której
czas transmisji nie jest pomijalnie mały. W sieciach o dostępie „TOKEN – BUS”, ze względu na sekwencyjne
przekazywanie żetonu, można było utworzyć listę nieobecności, na której mogli znaleźć się najbliżsi sąsiedzi
posiadacza żetonu. W sieciach o dostępie MASTER–SLAVE jest to niemożliwe. Z drugiej zaś strony, nie można
nie brać pod uwagę opóźnień wynikających z nieobecności abonenta. Pamiętając o tym i o fakcie zapewnienia
ponownego przyłączenia abonenta do sieci bez konieczności jej restartowania, należy zaproponować inny
mechanizm minimalizujący opóźnienia będące rezultatem powstawania „dziur”. Jedną z propozycji, które
spotyka się w rozwiązaniach firmowych, jest określenie liczby cykli sieci, w czasie trwania których, nieobecny
abonent nie będzie „odpytywany”. Po zakończeniu realizacji określonej liczby cykli, ponawiana jest próba
nawiązania z nim łączności. Jeśli abonent jest ciągle nieobecny, znów na wcześniej określoną liczbę cykli,
wstrzymywana jest z nim próba realizacji wymian. Nie może to być mechanizm, którego nie da się wyłączyć.
Może być bowiem tak, że nawiązanie łączności musi nastąpić najszybciej jak to jest tylko możliwe. Opisany
sposób nosi nazwę „autousuwania” nieobecnego abonenta. Decyzję o uruchamianiu tego mechanizmu
pozostawia się programiście, który konfigurując sieć i tworząc scenariusz wymian, decyduje przez określenie,
zazwyczaj specjalnego parametru, czy autousuwanie ma mieć miejsce czy nie.

6

Parametryzacja wymian

Jak już wspomniano, oprogramowanie wymian jest umieszczone w koprocesorze stacji MASTER.
Programowanie koprocesora polega na wprowadzeniu wcześniej opracowanego scenariusza wymian,
dotyczącego jednego cyklu sieci. W skład cyklu mogą wchodzić również wymiany wyzwalane. Programowanie
a właściwie parametryzacja koprocesora polega na wypełnieniu tablicy wymian takimi informacjami jak:
• numer wymiany,
• numer (adres) abonenta, do którego jest adresowana dana wymiana,
• kod operacji,
• adres pobrania danych z pamięci jednostki centralnej stacji MASTER,
• adres przesłania danych do jednostki centralnej abonenta,
• liczba danych,
• wybór trybu przesłania (periodyczna – wyzwalana),
• autousuwanie abonenta sieci przy braku odpowiedzi,
• adres słowa raportu wymiany z danym abonentem.
Dla każdej wymiany należy ponadto wypełnić tablicę parametrów każdej wymiany. Tymi parametrami są:
• graniczny czas oczekiwania na odpowiedź od abonenta TOD,
• liczba prób nawiązania łączności z abonentem w przypadku braku z nim komunikacji,
• liczba cykli sieci, podczas których nie będzie dokonywana próba nawiązania łączności z abonentem,
którego nieobecność wykryto w sieci,
• interwał czasowy pomiędzy dwiema transmisjami typu „rozgłoszenie”,
• czas opóźnienia przed i po transmisji ramki i czas autoryzacji przy pracy z modemami.
• Globalnie oczywiście deklaruje się dodatkowo takie wielkości jak:
• tryb transmisji (RTU – kodowanie binarne, ASCII – kodowanie znakowe),
• liczba bitów stopu i parzystość,
• liczba bitów przypadających na jeden znak transmisji LBZ,
• prędkość transmisji V.
Znaczenie większości z wymienionych parametrów jest oczywiste. Omówione zostaną tylko te, które są
istotne z punktu widzenia czasu wymiany informacji.

Numer wymiany
Wprowadzenie numeru wymiany jest niezbędne ze względu na możliwość generowania wymian
wyzwalanych. Ponieważ wymiany te są inicjowane przez program aplikacyjny, to musi być możliwość
określenia, o którą wymianę chodzi. W zależności od konkretnych rozwiązań liczba wymian w jednym cyklu
sieci waha się od kilku do kilkuset.

Tryb przesłania
Wybór trybu pracy polega na określeniu czy dana wymiana o konkretnym numerze ma być realizowana bez
inicjalizacji przez jednostkę centralną stacji MASTER, czy też ma się odbywać w każdym cyklu sieci.

9

Sieć MODBUS

Procedury MODBUS w module BASIC sterownika C50/C100

Autousuwanie abonenta z sieci
W trybie pracy cyklicznej (bez udziału jednostki centralnej stacji MASTER) koprocesor może „usunąć”
abonenta z sieci, jeśli jest on nieobecny lub stwierdzono błędy podczas transmisji. Wykrycie notorycznych
błędów transmisji może w sposób automatyczny (bez udziału programu aplikacyjnego – program obsługi
błędów) zablokować dostęp do abonenta.
Jest to bardzo silne narzędzie, z którego trzeba bardzo umiejętnie korzystać gdyż z jednej strony, bez
nakładów czasowych związanych z koniecznością realizacji specjalnego programu obsługi błędów, można
przyspieszyć proces wymiany informacji, z drugiej zaś, można zablokować dostęp abonenta do sieci.

Graniczny czas oczekiwania na odpowiedź TOD
Parametr ten jest niesłychanie ważny i jego wartość powinna być rezultatem bardzo precyzyjnej analizy
obciążenia sieci. Określa on maksymalny czas oczekiwania na odpowiedź od abonenta. Po upływie tego czasu
w słowie raportu wymiany znajdują się informacje o jej przebiegu. Na ustalenie tego parametru będzie miał
wpływ rezultat analizy pracy abonenta, jego zadania i czas ich wykonania. Innymi słowy na wartość tego
parametru zasadniczy wpływ będzie miał czas trwania cyklu jednostki centralnej TA.

Liczba prób nawiązania łączności
Jest to również bardzo istotny parametr mający wpływ na przepustowość sieci, a o którym była mowa przy
okazji omawiania powstawania zjawiska „dziur” w sieci. Jeśli stacja MASTER wykryje nieobecność abonenta,
to zgodnie z wartością tego parametru, może przez określoną liczbę razy, próbować nawiązać z nim łączność.
Parametr ten będzie miał małą wartość lub wręcz przyjmie wartość zero dla wymian mało istotnych i dużą dla
wymian o podstawowym znaczeniu dla pracy całego systemu. Za pomocą tego parametru można również
niejako przydzielić dodatkowy czas dla stacji SLAVE, jeśli z góry wiadomo, że w określonych okolicznościach
nie jest ona w stanie przygotować na czas odpowiedzi. Dzięki temu parametrowi można optymalizować czas
wymiany. Czyniąc to, nie należy zapominać, przy analizie czasowej, o braniu pod uwagę najgorszego
przypadku. Najgorszy przypadek dotyczy okoliczności, w których stacja MASTER będzie, zgodnie z tym
parametrem, starać się nawiązać łączność maksymalną liczbę razy.

Maksymalna liczba cykli sieci przy braku odpowiedzi
O tym parametrze również wspomniano opisując zjawisko „dziur”. Jeżeli stacja MASTER wykryje brak
abonenta, to przez określoną tym parametrem liczbę cykli sieci, nie będzie próbowała z nim nawiązać
komunikacji. Ma to znaczny wpływ na przepustowość sieci. Przy pomocy tego parametru podobnie jak przy
pomocy poprzedniego można przydzielić „dodatkowy” czas dla określonego abonenta jeśli wiadomo, że nie
będzie on w stanie, w pewnych ekstremalnych przypadkach, przygotować odpowiedzi w zadanym czasie TOD.

7

Procedury MODBUS w module BASIC sterownika C50/C100

7.1

Informacje ogólne o module BASIC

Moduł BASIC jest niezależnym modułem koprocesora, wspomagającym prace jednostki centralnej, z
wbudowanym interpreterem języka BASIC. Jest on zrealizowany w postaci standardowego modułu, wpinanego
do raka sterownika. Dzięki wyposażeniu w niezależny procesor wykonuje on swój program równolegle z
programem wykonywanym przez jednostkę centralna. Dzięki wyposażeniu modułu w pamięć EEPROM,
program wykonywany przez BASIC i umieszczony w tej pamięci jest przechowywany również po wyłączeniu
napięcia zasilania. Daje to możliwość natychmiastowego użycia raz zaprogramowanego modułu bez żadnych
dodatkowych działań programistycznych.
Moduł BASIC dzięki dostępowi do magistrali sterownika pozwala na odczyt jak i zapis dowolnych stref
pamięci jednostki centralnej. Istnieje wiec możliwość dwukierunkowego przesyłania danych, zmiennych i
komunikatów pomiędzy jednostka centralna a modułem BASIC. Dostęp do magistrali umożliwia modułowi
śledzenie na bieżąco stanu wejść i wyjść sterownika, a także innych informacji dotyczących sterowanego
procesu. Pozwala to na takie oprogramowanie modułu, przy którym jednostka centralna nie musi wykonywać
1
żadnych dodatkowych operacji związanych z praca modułu BASIC. .

1

Za wyjątkiem inicjalizacji modułu.
10

Sieć MODBUS

Procedury MODBUS w module BASIC sterownika C50/C100

Dostęp do stref pamięci jednostki centralnej realizowany jest pod koniec każdego cyklu pracy automatu patrz ilustracja 1. Z tego faktu wynika ograniczenie na szybkość dostępu do stref pamięci jednostki centralnej. W
2
jednym cyklu automatu istnieje możliwość zapisu bądź odczytu jednej strefy pamięci sterownika.
Informacje szczegółowe dotyczące listy rozkazów języka oraz budowy i działania modułu można znaleźć w
instrukcji laboratoryjnej pt. „Moduł BASIC sterowników C50 / C100”.

7.1.1

Przeznaczenie Modułu BASIC

Moduł BASIC sterowników C50/C100 jest modułem koprocesora wspomagającego prace jednostki
centralnej sterownika i umożliwia przejecie części wykonywanych przez nią zadań Nadaje się on w sposób
naturalny do rozwiązywania takich problemów jak:
• wykonywanie operacji arytmetyczno-logicznych,
• przetwarzanie tekstów,
• wykonywanie operacji konwersji danych,
• przygotowywanie i obróbka danych dla sterownika,
• odczyt i zapis danych do pamięci modułu głównego,
• komunikacja sterownik - operator,
• proste aplikacje sieciowe sterowników,
• wizualizacja pracy sterownika.

7.1.2 Zmienne
Nazwa zmiennej wykorzystywanej przez program modułu BASIC powinna składać się z jednego lub dwu
znaków, przy czym pierwszy znak powinien być litera np.: A, TA, Z5 itp.
Można definiować tablice jednowymiarowe o maksymalnej ilości pól równej 256.
Zmienne numeryczne mogą przyjmować wartości z przedziału od -0.99999999*10+127 do 0.99999999*10+127
dla liczb rzeczywistych, oraz od 0 do 65535 dla liczb całkowitych (INTEGER).
Zmienne tekstowe wyróżniane są przez znak $ występujący po nazwie zmiennej np.: A$, AS$ itp. Zmienne
znakowe mogą zawierać w sumie maksymalnie 256 znaków.

7.1.3

Stałe

Stale dziesiętne mogą być zapisywane w postaci normalnej, jak i w notacji matematycznej np.: 123000, 123E+3.
Stale szesnastkowe powinny być poprzedzane znakami & H np.: & HF0F0.

7.2

PROC 0

Składnia:

PROC 0, R → RTU
PROC 0, A → ASCII
PROC 0, OFF
Uruchamia tryb obsługi sieci MODBUS RTU lub ASCII.

PROC 0, R → tryb RTU
Koniec ramki jest wykrywany wówczas, gdy nie zostanie wykryty żaden znak przez czas 3.5C (3.5C = 3.5 x
czas potrzebny na przesłanie jednego znaku przy danej szybkości transmisji). Jeżeli wcześniej użyto CONTROL
XON lub CONTROL XON TX, moduł zostanie ustawiony na CONTROL OFF. W trybie RTU parametry
transmisji są stałe: 8 bitów danych, bez parzystości, 1 bit stopu. Ustawienie mikroprzełączników jest
ignorowane.

PROC 0, A – tryb ASCII
Koniec ramki jest wykrywany na podstawie detekcji znaku LF (0Ah).

PROC 0, OFF

– stop

Podczas zatrzymania obsługi, inicjalizowany jest program obsługujący transmisję i odbiór danych.

2

W standardowych zastosowaniach sterownika czas ten nie powinien przekraczać 8 ms. dla sterownika C50 i
10 ms. dla sterownika C100 dla programu zawierającego 1000 instrukcji.
11

Sieć MODBUS

Procedury MODBUS w module BASIC sterownika C50/C100

TRMTER = CR, LF
(0Dh, 0Ah)
RCPTER = CR
TEMPOC = 0
CONTROL OFF
(tylko wówczas gdy moduł był w stanie CONTROL XON lub CONTROL
XON TX podczas wykonywania PROC 0, R)
Ustawienia mikroprzełączników zaczynają obowiązywać.
UWAGA:

Procedura obsługuje sygnały RTS i CTS jeśli były wydane wcześniej polecenia CONTROL
MODEM lub CONTROL MODEM TX.
Poniższa linia programu musi być wykona przed każdym wywołaniem PROC 0, jeżeli procedura
PROC 0 używana jest wielokrotnie.

100 IF TMR=0 THEN 100
110 PROC 0,...
7.3

PROC 1 – PROC 2

Procedury uaktywniają obsługę ramek typu MASTER. Dane będące wysyłane bądź odbierane są
zapisywane / czytane do / z tablicy zmiennych deklarowanej przez użytkownika w module BASIC. Obliczenie
pól kontrolnych, przygotowanie ramek oraz ich dekodowanie jest automatycznie realizowane przez te procedury.

7.3.1

PROC1 – wysłanie zapytania lub rozkazu

Składnia:

PROC 1, Exp Num1, Exp Num2, Exp Num3, Exp Num4, NV
Zapytania lub wymiany w trybie odczytu:
Exp Num1:
Liczba abonentów (1..63)
Exp Num2:
Kod operacji
01/02 odczyt n bitów
03/04 odczyt n słów
07
szybki odczyt bajtu
08
odczyt raportu
0Bh
liczniki
Exp Num3:
Adres danych otrzymywanych z innego systemu.
Exp Num3 jest adresem sieciowym.
operacja 7 i Bh: Exp Num3 jest nieistotne
operacja 8
: Exp Num3 odpowiada numerowi licznika (1 2 3 4 5 8)
Liczba wartości do odczytu.
Exp Num4:
operacja 7, 8 i Bh: Exp Num4 jest nieistotne
NV:
Zmienna tablicowa do której otrzymane dane będą składowane po analizie
odpowiedzi przez PROC 2.
Rozkazy i wymiany w trybie zapisu:
Liczba abonentów (1..63) 0 =rozgłoszenie
Exp Num1:
Exp Num2:
Kod operacji
05h
zapis 1 bitu
06h
zapis 1 słowa
0Fh
zapis n bitów
10h
zapis n słów
Exp Num3:
Adres gdzie dane będą zapamiętywane.
Exp Num3 jest adresem sieciowym.
Exp Num4:
Liczba wartości do przesłania.
operacja 5, 6
: Exp Num4 jest nieistotne
NV:
Zmienna tablicowa z której dane będą transmitowane.
Odczyt odpowiedzi:
Program pracujący w module BASIC jest informowany o otrzymaniu odpowiedzi przez ustawienie flagi
RCP na 1.

12

Sieć MODBUS

7.3.2

Procedury MODBUS w module BASIC sterownika C50/C100

PROC1 – wysłanie zapytania lub rozkazu

Składnia:

PROC 2, NV
PROC 2 sprawdza czy ramka otrzymana jest oczekiwaną ramką odpowiedzi na wymianę zainicjowaną przez
PROC 1.
Zapytania lub wymiany w trybie odczytu:
− Sprawdza odpowiedź.
− Zapisuje raport do zmiennej NV.
− Transferuje otrzymane dane do zmiennej tablicowej wskazanej w PROC 1.
Rozkazy i wymiany w trybie zapisu:
− Sprawdza odpowiedź.
− Zapisuje raport do zmiennej NV.

wartość
00
02
02
06
08

Znaczenie wartości zmiennej raportu
znaczenie
poprawna odpowiedź
błędna odpowiedź
zły adres
adres niezrozumiały przez abonenta
błędna odpowiedź
za dużo danych dla abonenta
błędna odpowiedź
abonent zajęty
niepoprawna ramka

Przykładowy program:
Odczyt słów W100 i W101 od abonenta numer 2
Zapis otrzymanych danych w słowie W383, 384.
Adres słowa W100 w sterowniku C100:
W100 → 0640h

5
10
20
30
40
50
60
70
80
...
1000
...

DIM VA(15)
PROC 0, R REM Modbus RTU
AB=02: OP=03: AD=#H640: NB=2
PROC 1, AB, OP, AD, NB, VA(0) REM send frame
IF RCP=0 THEN 40
PROC 2, CP
IF CP & lt; & gt; 0 THEN 1000
REM CORRECT FRAME
WRITE W383 WITH VA(0), VA(1)
REM INCORRECT FRAME

linia 30 może być zastąpiona przez:

30

PROC 1, 2, 3, #H640, 2, VA(0)

UWAGA:
Dla operacji na bitach:
− Wymiana w trybie zapisu: Transferowane zmienne muszą być równe 1 lub 0. Każda zmienna
reprezentuje jeden bit.
− Wymiana w trybie odczytu: Każdy odczytany bit jest zapisywany do osobnej zmiennej. Zmienne
przyjmują wartość 1 lub 0.
− aby ustawić 8 bitów danych, kontrola parzystości:
S1(C2) = 1
S2(C2) = 0
S3(C2) = 0

13

Sieć MODBUS

Procedury MODBUS w module BASIC sterownika C50/C100

Poniższa instrukcja jest potrzebna do zapisu dla bitów:

10
7.4

PROC 0, R: PROC 5, OFF

PROC 3 – PROC 4

Procedury uaktywniają obsługę ramek typu SLAVE. Dane będące wysyłane bądź odbierane są zapisywane /
czytane do / ze zmiennej tablicowej.
Odczyt zapytania lub rozkazu:7
Program pracujący w module BASIC jest informowany o nadejściu ramki przez ustawienie flagi RCP na 1.

7.4.1

PROC3 – analiza zapytania lub rozkazu

Składnia:

PROC 3, Exp Num, Nv1, Nv2, Nv3, Nv4, Nv5
PROC 3 analizuje otrzymane zapytanie lub rozkaz i wypełnia zmienne Nv1..Nv5. Po odczycie zmiennych
Nv1..Nv5 program użytkownika pracujący w module BASIC może zadecydować, którym zadaniem należy się
zająć.
Exp Num:
numer abonenta
Nv1..Nv4:
zmienne zapisywane po zdekodowaniu ramki
Nv5:
raport
Raport jest zapisywany po analizie ramki.
Wartość
0
1
2
3
4, 5
6
7
8

znaczenie
ramka poprawna
nieznany kod operacji
niepomyślna analiza ramki
niepoprawne dane (liczba danych & gt; rozmiaru tablicy)
nie używane
niepomyślna analiza ramki
adres abonenta poza zakresem
niepoprawna ramka

Zapytania lub wymiany w trybie odczytu:
Nv1:
Odczytany kod operacji
Rozpoznawane kody operacji:
01/02 odczyt bitów
03/04 odczyt słów
07
odczyt bajtu
08
odczyt licznika
0Bh
odczyt licznika 9
Nv2:
Adres słowa lub bitu do odczytu
Nv2 może być z zakresu 0..05535 (0..FFFFh)
Nv2 = 0 dla odczytu bajtu (07) i dla odczytu licznika 9
Nv2 = numer czytanego licznika (1 2 3 4 5 8) dla funkcji 08 (moduł BASIC nie zawiera
licznika błędów. Wartość ta będzie traktowana jako adres słowa)
Nv3:
Liczba danych do odczytu.
Nv4:
Zmienna tablicowa z której będą pobierane dane do realizacji odpowiedzi przez procedurę
PROC 4.
Odpowiednie przygotowanie tablicy jest czynnością, którą musi wykonać programista.
Jeżeli dana do wysłania jest bitem, wartości zmiennej tablicowej muszą być równa 0 lub 1.
Rozkazy i wymiany w trybie zapisu:
Nv1:
Kod operacji:
Rozpoznawane kody operacji:
05h
zapis 1 bitu
06h
zapis 1 słowa
0Fh
zapis n bitów
10h
zapis n słów
Nv2:
Adres bitu lub słowa do zapisu:
Nv2 może być z zakresu 0..05535 (0..FFFFh)

14

Sieć MODBUS

Nv3:
Nv4:

7.5

Procedury MODBUS w module BASIC sterownika C50/C100
Po odczycie Nv2 program użytkownika pracujący w module BASIC powinien wskazać gdzie
zapisać otrzymane dane.
Liczba danych do zapisu.
Zmienna tablicowa do której będą zapisywane odczytane dane. Jeśli odczytane dane są typu
bitowego, elementy zmiennej tablicowej przyjmują wartości 0 lub 1.

PROC4 – wysyłanie odpowiedzi

Składnia:

PROC 4
PROC 4 analizuje raport (PROC 3, Nv5) i wysyła odpowiednią odpowiedź.
Możliwe odpowiedzi:
wartość raportu
0
1
2
3
4, 5
6
7, 8

odpowiedź
wysłanie odpowiedzi na ramkę otrzymaną i zanalizowaną przez PROC 3
wysłanie błędu: nieprawidłowy numer funkcji
wysłanie błędu: nieprawidłowy adres
wysłanie błędu: niewłaściwe dane
nie używane
wysłanie błędu: moduł BASIC zajęty
brak odpowiedzi

Jeżeli wartość raportu wynosi 0:
− Zapytania lub wymiany w trybie odczytu
Odpowiedź wysłana po otrzymaniu danych z tablicy wskazanej w PROC 3.
− Rozkazy lub wymiany w trybie zapisu
Odpowiedź wysłana lub tylko potwierdzenia.
UWAGA:

Zmienna raportu Nv5 może być zapisana przez program w basicu w celu wymuszenia wysłania
odpowiedzi przez PROC 4.

Przykładowy program:
Zapamiętanie dwóch odczytanych słów w W300 i 383 jeśli odczytany adres jest równy numerowi abonenta
równemu 3.
W innym przypadku sygnalizowany jest błąd.

5

CONTROL MODEM

7
10
30
30
40
50
60
70
80
90
1000

DIM VA(15)
PROC 0, R
IF RCP=0 THEN 20
PROC 3, 3, OP, AD, NB, VA(0), CT
IF CT & lt; & gt; 0 THEN 1000
IF HP & lt; & gt; & H10 THEN CT=1: GOTO 1000
IF AD & lt; & gt; 10 THEN CT=2: GOTO 1000
IF NB & lt; & gt; 2 THEN CT=3: GOTO 1000
WRITE W300 WITH VA(0)
WRITE W383 WITH VA(1)
PROC 4: GOTO 10

obsługa sygnałów
modemowych
obsługa modbus RTU
oczekiwania na RCP
analiza odpowiedzi
błąd
błąd kodu operacji
błąd adresu
błąd liczby danych
zapis odczytanych słów
wysłanie odpowiedzi
i oczekiwanie na
następną ramkę

15

Sieć MODBUS

Procedury MODBUS w module BASIC sterownika C50/C100

Notatki
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
.........................................................................................................................................................................................
Tytuł:
Temat:
Stworzono:
Wydrukowano:
Nazwa pliku:
Wersja:

Instrukcja laboratoryjna
Sieć MODBUS
2003-03-12 18:34 PG
2004-04-20 10:54
Instrukcja - Modbus.doc
25822/4408/16
pl. 1.26

Wykonano na bazie informacji literaturowych, dokumentacji urządzeń C50/C100, BASIC oraz MWZPCiR-ICT-PWr. i www.modbus.org

16


MODBUS_materiały.rar > Sterowniki_komunikacja.pdf

5. KOMUNIKACJA W SYSTEMIE STEROWNIKÓW PLC


CPU – programator (PADT – Programming And Debugging Tool),
RS232 (RS 485) – protokół (SNP, Modbus, itp.), Ethernet;



Sieci lokalne (LAN – Local Area Network)
moduły komunikacyjne;



sieci polowe (Field Network lub Fieldbus)
rozproszone systemy sterowania (distributed control);



telefonia komórkowa GSM (Global System for Mobile Communication)
moduł do komunikacji GSM lub odpowiednia przystawka połączona z CPU za
pomocą standardowego łącza szeregowego, wymiana za pomocą SMS-ów (Short
Message Service).

Sieci lokalne (LAN)
Topologie sieci:

Pierścieniowa

Gwiaździsta

Magistralowa

W sieciach lokalnych i przemysłowych transmisja danych cyfrowych odbywa się przede
wszystkim z wykorzystaniem następujących mediów:
• przewód typu skrętka,
• kabel koncentryczny,
• światłowód.
Podstawowe metody dostępu do łącza to:
• metody przydziału łącza fizycznego, np. w komunikacji Master-Slave;
• metody kontrolowanego dostępu, np. oparte na przesyłaniu żetonu (token);
• metody przypadkowego dostępu (np. CSMA/CD w sieci Ethernet).

Protokół komunikacyjny
Wykorzystanie możliwości przesyłania informacji za pomocą łącza wymaga ustalenia
pewnego zbioru reguł określających:
• elektryczne, mechaniczne i funkcjonalne charakterystyki łącza komunikacyjnego;
• sposoby sterowania umożliwiające przesłanie danych od nadajnika do odbiornika.
Organizacje normalizacyjne, takie jak: ISO (ang. International Standards Organisation), EIA
(ang. Electronic Industries Association), CCITT (ang. Consultive Committee on International
Telephone and Telegraph) i inne zaproponowały wiele różnych wielowarstwowych
protokołów komunikacyjnych, dla których:
• każda warstwa definiuje różne funkcje i charakterystyki protokołu;
• każda warstwa jest niezależna od pozostałych, lecz do jej działania konieczne jest
funkcjonowanie warstw niższych.
Podstawę do opracowywania różnych protokołów stanowi norma ISO, określająca
organizację połączeń systemów otwartych OSI (ang. Open System Interconnection),
przedstawiająca siedmiowarstwową hierarchię protokołów komunikacyjnych:


warstwa aplikacji (application layer) – dostęp do usług komunikacyjnych z poziomu
aplikacji, identyfikacja i bezpieczeństwo danych;



warstwa prezentacji (presentation layer) – określenie syntaktyki dla kodowania,
formatowania, transformacji wymienianych danych;



warstwa sesji (session layer) – ustalanie i przerywanie połączeń na drodze
synchronizacji i dialogu, kontrola przepływu danych i buforowania;



warstwa transportowa (transport layer) – specyfikacja połączeń terminali, obsługa
komunikacji punkt-do-punktu;



warstwa sieci (network layer) – transparentna wymiana danych między węzłami,
obsługa adresów, ścieżek itp.;



warstwa łączenia danych (data link layer) – dostęp do medium, detekcja i obsługa
błędów transmisji;



warstwa fizyczna (physical layer) – przesyłanie ciągów bitów za pomocą medium,
definiuje interfejs elektryczny i mechaniczny.

Szczególne znaczenie w historii rozwoju rozproszonych systemów automatyki miał
opracowany w firmie General Motors standard MAP (ang. Manufacturing Automation
Protocol). Standard ten, bazując na modelu współpracy OSI, zakłada modularyzację
oprogramowania sieciowego z wykorzystaniem podziału funkcji.

Każdy moduł odpowiada jednej warstwie i jest odpowiedzialny za dostarczanie wybranych
usług sieciowych warstwie wyższej, korzystając jednocześnie z usług dostarczanych przez
warstwę niższą. Między warstwami przesyłane są dwa rodzaje informacji: dane i informacja
sterująca. W trakcie nadawania każda warstwa dołącza swoje informacje sterujące do danych
otrzymanych z warstwy wyższej i przekazuje je do warstwy niższej. Warstwy najniższe:
łączenia i fizyczna odpowiadają za przesyłanie informacji między dwoma sąsiednimi węzłami
sieci. Po stronie odbiorczej z kolei, każda z warstw przekazując dane do warstwy wyższej
usuwa z nich odpowiadające jej informacje sterujące, aż do całkowitego zaniku informacji
sterujących. W procesie tym dane użytkownika przekazywane są bez zmian.
Podstawowym celem standardu MAP było zdefiniowanie zespołu protokołów, który można
by zaimplementować w różnych komputerach, terminalach i programowanych urządzeniach,
i który zapewniałby użytkownikom kompatybilność urządzeń przy dołączaniu ich do tak
określonej sieci (tzn. sieci w standardzie MAP).

Sieci przemysłowe
Wymaganie pracy w czasie rzeczywistym (czas potrzebny na przesył informacji od stacji do
stacji jest zdeterminowany) oraz zwiększonej odporności na występujące w warunkach
przemysłowych zakłócenia.
W magistralowych sieciach przemysłowych najwcześniej stosowana była reguła wymiany
danych typu „nadrzędny-podrzędny” (Master-Slave), która uprawnia do inicjowania
transmisji (zapytania) jedynie element sieci posiadający status „nadrzędny” (Master).
Dopuszcza się tu dwa typy wymiany danych:


„zapytanie–odpowiedź” (Query-Response) – umożliwia wymianę informacji z wybraną
stacją Slave, przy czym każda taka wymiana zawiera pojedyncze zapytanie stacji Master
i odpowiedź stacji Slave;



„rozgłoszenie” (Broadcast) – oznacza wymianę ze wszystkimi abonentami Slave,
w której stacja Master wysyła jedynie ramkę rozgłoszenia (brak odpowiedzi stacji
Slave).

Zasadniczą cechą tego typu sieci jest stały format ramki i zestaw standardowych funkcji
służących wymianie danych. Typowy format ramki obejmuje: adres abonenta Slave (lub
znacznik Broadcast), kod funkcji, dane (potrzebne do wykonania funkcji) oraz słowo
kontrolne. Postać ramki odpowiedzi stacji Slave jest podobna, z tym że w polu danych
występują dane, których dostarczenia żądała stacja Master.
Powszechnie stosowanym przykładem komunikacji typu Master-Slave jest protokół
MODBUS, który przesyłane znaki organizuje w ramki w trybie ASCII albo RTU.
W zastosowaniach przemysłowych sieci wykorzystujące metodę dostępu z przesyłaniem
żetonu (Token-Passing) są dedykowane dla komunikacji między wieloma stacjami dając
gwarancję dużej niezawodności transmisji przy stosunkowo dużej prędkości. Charakteryzują
się one zdecentralizowaną architekturą (brak jednostki nadrzędnej), łatwą rozbudową
z możliwością tworzenia struktury drzewiastej, gwarantowanym czasem wymiany między
stacjami, ograniczoną długością ramki oraz możliwością pracy sieci nawet w przypadku
awarii którejś ze stacji.

W protokole dostępu do łącza wyróżnia się tu dwa typy ramek:


ramki serwisowe, do których należy tzw. żeton (token);



ramki danych.

Wymiana danych polega na przekazywaniu żetonu pomiędzy kolejnymi węzłami sieci,
a ramki danych może transmitować jedynie ten węzeł, który jest w posiadaniu żetonu.
Transmitowane dane dostępne są dla wszystkich innych stacji w sieci. Sieć taka
charakteryzuje się równoprawnym dostępem – każda stacja może wymieniać dane jak „równy
z równym” (peer-to-peer). Informacje są przesyłane ze stałym cyklem, zależnym od
szybkości transmisji, liczby transmitowanych bajtów, a także od liczby i typu elementów
włączonych do sieci.
Aby przekazywanie żetonu przebiegało prawidłowo każda stacja w sieci ma ustalone
(sprzętowo lub programowo) dwa istotne parametry:
• własny (unikalny) numer w sieci;
• numer ostatniej stacji.
W chwili przyłączenia nowej stacji należy nadać jej numer identyfikacyjny (różny od już
istniejących) oraz, jeśli jest taka potrzeba, zmienić wszystkim stacjom numer ostatniej stacji
w sieci, gdyż informacje te są niezbędne na etapie przekazywania żetonu. Przykładami sieci
typu Token-Passing są sieć Genius firmy GE Fanuc czy Sycoway N10 firmy CEGELEC.
Natomiast protokół PROFIBUS w zakresie dostępu do łącza wykorzystuje metodę przesłania
żetonu przy komunikacji między stacjami typu Master oraz metodę typu Master-Slave przy
komunikacji między stacją typu Master i prostymi urządzeniami typu Slave.
W omawianych wyżej rozwiązaniach stosowana jest głównie metoda komunikacji „punkt do
punktu” (point-to-point), dla której odpowiedni jest klasyczny model wymiany typu „klient –
serwer”. Proces – klient posiada tu inicjatywę w wymianie danych, a inny proces – serwer
wykonuje żądanie klienta. Model ten został zaadoptowany do komunikacji pionowej, tzn.
pomiędzy różnymi warstwami w hierarchii.
W przypadku stosowania komunikacji poziomej wykorzystywany jest raczej model dostępu
„producent – dystrybutor – konsument” (PDC, ang. Producer - Distributor - Customer).
W modelu tym „producent” jest odpowiedzialny na poziomie aplikacji za „produkowanie”
danych, natomiast „dystrybutor” (kontroler sieci) jest odpowiedzialny za transfer danych od
„producenta” do „konsumenta”. „Konsument” danych jest aplikacją, która w trakcie
wykonywania żąda danych. Model PDC stawia na pozycji uprzywilejowanej “konsumentów”
i doskonale nadaje się do wymiany poziomej. Model ten znalazł zastosowanie przede
wszystkim w tzw. sieciach polowych (ang. Field Network). Sieci takie stosowane są głównie
na poziomach sterowania i urządzeń. Pozwalają one na projektowanie rozproszonych
systemów sterowania i występują w różnych standardach komunikacyjnych, w tym m.in.: FIP
(Factory Instrumentation Protocol), CAN, Profibus DP, Device-Net, Interbus-S, itp.

Protokół Modbus
Cykl zapytanie – odpowiedź:

W trybie ASCII każdy bajt kodowany jest w formacie heksadecymalnym i przesyłany jako
dwa znaki ASCII (0..9, A..F).
Ramka w trybie ASCII:

Każdy przesyłany znak obejmuje dziesięć bitów:

Zaletą trybu ASCII jest możliwość przesyłania kolejnych znaków w dowolnych odstępach
czasu.
W trybie RTU (Remote Terminal Unit) transmisja rozpoczyna się ciszą na łączu trwającą co
najmniej przez czas odpowiadający przesłaniu 3,5 znaków, po czym wysyła się ośmiobitowy

adres i kod funkcji. Dalej występują dane jako ciąg 8–bitowych liczb w zakresie od 16#00 do
16#FF. Ramka kończy się 16–bitowym słowem kontrolnym obliczanym według algorytmu
CRC (Cyclical Redundancy Check). Następnie na łączu powinna wystąpić przerwa
odpowiadająca przesłaniu co najmniej 3,5 znaków, co jest znacznikiem końca ramki i
początku ewentualnej następnej ramki.
Ramka w trybie RTU:

Jednostka informacyjna zawiera 11 bitów:

Zaletą trybu RTU jest większa przepustowość łącza.
Kody typowych funkcji:
01 – Read Coil Status;
02 – Read Input Status;
03 – Read Holding Registers;
04 – Read Input Registers;
05 – Force Single Coil;
06 – Preset Single Register;
13 – Program Controller;
14 – Poll Controller;
15 – Force Multiple Coils;
16 – Preset Multiple Registers;
itp.
Adresowanie danych:


cewka 0001 w danych występuje jako adres 16#0000 a cewka 0127 jako 16#007E
(126 dziesiętnie);



rejestr 40001 wystąpi jako 16#0000, a rejestr 40108 jako 16#006B (107 dziesiętnie)

Przykład zapytania w trybach ASCII/RTU:

Przykład odpowiedzi w trybach ASCII/RTU:

W pakiecie Concept – blok funkcjonalny XMIT (grupa RTU w bibliotece COMM)

Sieć Modbus Plus
Przykład sieci Modbus Plus:

Podstawowe elementy sieci:

Przesyłanie żetonu w sieci:

W pakiecie Concept – bloki funkcjonalne (grupa MBP w bibliotece COMM):
CREADREG (Continuous Register Reading)
CWRITREG (Continuous Register Writing)
MBP_MSTR (Modbus Plus Master)
READREG (Read Register)
WRITEREG (Write Register)


MODBUS_materiały.rar > MOD.PDF

Protok´l komunikacyjny Modbus (Modicon)
o
s
• dostep do no´nika typu master – slave
o
• wykrywanie i sygnalizacja bled´w
• potwierdzanie wykonania komend
• zabezpieczenie przed blokada
z
sc
• mo˙ liwo´´ transmisji znakowej RS232C, RS485 itp.
Transakcja w systemie Modbus:
MASTER
adres
kod funkcji
dane
suma kontrolna

SLAVE


adres
kod funkcji
dane
suma kontrolna


MW-ZPCiR-ICT-PWr

1

Typy ramek protokolu Modbus
Ramka w trybie znakowym (ASCII)
:

adres

kod f.

dane
...

suma

CR

LF

• bajty sa wysylane szesnastkowo (po dwa znaki ASCII)
• odstepy pomiedzy kolejnymi znakami ramki & lt; 1s
Ramka w trybie binarnym (RTU)
adres

kod f.

dane
...

suma

• bajty sa wysylane binarnie jako znaki o´miobitowe
s
• ka˙ da ramka jest poprzedzona odstepem (cisza na linii)
z
& gt; 3.5T (gdzie T oznacza czas transmisji jednego znaku)
• odstepy pomiedzy kolejnymi znakami ramki & lt; 1.5T
MW-ZPCiR-ICT-PWr

2

Pola ramki Modbus (1)

adres
0
1 – 247




adres rozglaszania (broadcast)
adres jednostki slave

kod funkcji
1
2
3
4
5
6
7
8
15
16
17
128 – 255
MW-ZPCiR-ICT-PWr

$01
$02
$03
$04
$05
$06
$07
$08
$0F
$10
$11
$80–$FF

odczyt wyj´´ bitowych
sc
odczyt wej´´ bitowych
sc
odczyt n rejestr´w
o
odczyt n rejestr´w wej´ciowych
o
s
zapis 1 bitu
zapis 1 rejestru
odczyt statusu
test diagnostyczny
o
zapis n bit´w
zapis n rejestr´w
o
identyfikacja urzadzenia slave
zarezerwowane na odpowiedzi bledne
3

Pola ramki Modbus (2)

rejestry i zmienne
Urzadzenie jest widziane jako 16-bitowe rejestry Wn.
Typy zmiennych umieszczanych w rejestrach:
bitowe
2-bajtowe
4-bajtowe





bity rejestr´w W0 − W4095
o
cale rejestry Wn
sasiednie rejestry Wn : Wn+1

zalecenie
W celu ulatwienia przesylania danych przy pomocy ramek
z funkcja ”odczyt (zapis) n rejestr´w” rejestry powinny
o
zajmowa´ sp´jny obszar adresowany od 0 do rejmax.
c o

MW-ZPCiR-ICT-PWr

4

Przyklady ramek Modbus

o
zadanie (master): odczyt 2 rejestr´w od W30 do W31
˙
adres
slave
12

kod
fun.
03

dane
RAL RNH
1E
00

RAH
00

RNL
02

suma
LRC
CB

odpowied´ (slave): dane z rejestr´w od W30 do W31
z
o
adres
slave
12

kod
fun.
03

NB
04

W30H
01

dane
W30L W31H
23
02

W31L
34

suma
LRC
8D

odpowied´ (slave): blad – niedozwolony adres danych
z
adres
slave
12

MW-ZPCiR-ICT-PWr

kod
fun.
83

dane
kod
02

suma
LRC
69

5

Kontrola poprawno´ci w systemie Modbus
s
Wykrywanie bled´w transmisji nastepuje dzieki kontroli pao
rzysto´ci poprzecznej (bit parzysto´ci znaku) i wzdlu˙ nej (LRC,
s
s
z
CRC).
Wykrywanie i diagnozowanie bled´w komunikacji nastepuje
o
przez:
• odeslanie przez slave ramki z kodem bledu:
01
02
03
04
05
06
07
08










niedozwolona funkcja
niedozwolony zakres danych
niedozwolona warto´´ danej
sc
uszkodzenie w przylaczonym urzadzeniu
potwierdzenie pozytywne
brak gotowo´ci, komunikat usuniety
s
potwierdzenie negatywne
blad parzysto´ci pamieci
s

z
• przekroczenie czasu oczekiwania na odpowied´ (timeout w
jednostce master) – slave nie odsyla odpowiedzi przy bledach
w ramce zadania
˙
MW-ZPCiR-ICT-PWr

6


MODBUS_materiały.rar > Łącze RS-232, protokoły transmisji.txt

£¹cze RS-232, protoko³y transmisjiLaboratorium Sieci Komputerowych
Kierunek Informatyka
Studia Wieczorowe, semestr VII (Gliwice, ¯ory)
Uzupe³niaj¹ce Studia Magisterskie, semestr III


£¹cze RS-232, protoko³y transmisji

1. Cel æwiczenia

Celem æwiczenia jest zaznajomienie siê ze stosowanymi w praktyce protoko³ami
transmisyjnymi wykorzystuj¹cymi asynchroniczn¹ transmisjê znakow¹, okreœlon¹ w
standardzie RS-232, oraz zaimplementowanie, wed³ug wskazówek podanych przez
prowadz¹cego w trakcie æwiczenia, oprogramowania realizuj¹cego wybrany protokó³.
2. Sieæ Modbus

2.1. Wprowadzenie

Sieæ Modbus opracowano w firmie Modicon w latach siedemdziesi¹tych XX wieku.
Mimo up³ywu doœæ znacznego czasu od chwili jej wprowadzenia jest ona nadal
szeroko stosowana. Protokó³ u¿yty w tej sieci, o takiej samej jak sieæ nazwie,
jest obecnie typowym protoko³em wykorzystywanym dla organizacji komunikacji
urz¹dzeñ pomiarowo-kontrolnych z komputerem nadrzêdnym (tzw. komunikacji
pionowej). W procedury komunikacyjne realizuj¹ce protokó³ Modbus s¹ wyposa¿one
niemal wszystkie dostêpne na rynku pakiety SCADA (ang. Supervisory Control and
Data Acquisition).
Rysunek 1. Sieæ Modbus

Sieæ Modbus sw¹ popularnoœæ zawdziêcza prostocie zastosowanych w niej rozwi¹zañ
technicznych oraz jawnoœci specyfikacji protoko³u. Posiada ona topologiê
magistrali i umo¿liwia po³¹czenie wielu urz¹dzeñ pomiarowo-kontrolnych (rysunek
1) z komputerem. Komputer np. klasy PC stanowi wêze³ nadrzêdny (ang. master),
steruj¹cy prac¹ sieci, natomiast pozosta³e wêz³y s¹ wêz³ami podrzêdnymi (ang.
slaves). Wêz³y podrzêdne nie podejmuj¹ samodzielnie transmisji, odpowiadaj¹
tylko, z jednym wyj¹tkiem, na zdalne polecenia od wêz³a nadrzêdnego. Taka regu³a
komunikacji nosi w specyfikacji protoko³u Modbus nazwê regu³y
polecenie-odpowiedŸ (ang. query - response), u¿ywana jest tak¿e inna jej nazwa –
master-slave. Regu³a ta gwarantuje bezkonfliktowe wspó³dzielenie magistrali
przez wiele wêz³ów, ale przy poprawnym skonfigurowaniu sieci.
Do przesy³ania informacji przez magistralê sieci Modbus wykorzystywana jest
asynchroniczna transmisja znakowa okreœlona w standardzie RS232C. Maksymalna
prêdkoœæ transmisji wynosi, wed³ug specyfikacji protoko³u, 19200 b/s. Do
realizacji sprzêgu komunikacyjnego wêz³a sieci wystarczaj¹ dwa uk³ady: sterownik
asynchronicznej transmisji szeregowej i nadajnik/odbiornik interfejsu standardu
RS485 – ³¹cze fizyczne sieci Modbus jest ³¹czem wielopunktowym – oraz
odpowiednie oprogramowanie komunikacyjne.
Kompletn¹ specyfikacjê protoko³u zawiera dokument „Modicon Modbus Protocol
Reference Guide”; ostatnia wersja tego dokumentu jest oznaczona liter¹ J [3].

2.2. Charakterystyka protoko³u Modbus

2.2.1. Polecenia

Protokó³ Modbus opracowano dla sieci obiektowej, której wêz³y podrzêdne
stanowi³y programowalne sterowniki logiczne firmy Modicon. Wiêkszoœæ opisanych w
specyfikacji protoko³u poleceñ s³u¿y do realizacji operacji na sprzêtowych
zasobach tych sterowników – wejœciach i wyjœciach: cyfrowych, analogowych,
licznikowych oraz rejestrach ogólnego przeznaczenia, wykorzystywanych do
przechowywania zmiennych programu. Z punktu widzenia osoby tworz¹cej
oprogramowanie u¿ytkowe dla sterownika zasoby te s¹ rozmieszczone w czterech
roz³¹cznych obszarach adresowych, co przedstawiono w tabeli 1. Pojedynczy zasób
oznaczony jest symbolem o postaci
Ixxxx
gdzie:
I – identyfikator obszaru, okreœla on zarazem rodzaj zasobu,
xxxx – numer zasobu w zapisie dziesiêtnym, numeracja rozpoczyna siê od 1.

IZawartoϾ obszaru adresowego
0indywidualne: wyjœcia cyfrowe oraz znaczniki bitowe
1indywidualne wejœcia cyfrowe
316-bitowe rejestry wejœciowe, w których przechowywane s¹ wartoœci
odczytane z wejϾ analogowych i licznikowych
416-bitowe rejestry wyjœciowe – w czêœci z nich przechowywane s¹ wartoœci
wyprowadzanych na wyjœcia analogowe i licznikowe, natomiast czêœæ stanowi
rejestry ogólnego przeznaczenia

Tabela 1.
Rozmieszczenie zasobów sprzêtowych w sterownikach programowalnych firmy
Modicon



Zestawienie poleceñ u¿ywanych do realizacji operacji na poszczególnych zasobach
sterownika zawiera tabela 2; w nawiasach okr¹g³ych podano kody poleceñ. W
specyfikacji protoko³u Modbus opisanych jest jeszcze kilka poleceñ m. in.
umo¿liwiaj¹ce identyfikacjê wêz³a oraz jego diagnostykê. Jest rzecz¹ oczywist¹,
¿e urz¹dzenie pomiarowo-kontrolne, które ma stanowiæ wêze³ podrzêdny sieci
Modbus, powinno mieæ tak¹ sam¹, widzian¹ z zewn¹trz, organizacjê zasobów
sprzêtowych.

IPolecenia
0Read Coil Status (1) – odczyt bie¿¹cego stanu grupy wyjœæ
cyfrowych/znaczników
Force Single Coil (5) – ustawienie stanu jednego wyjœcia
cyfrowego/znacznika
Force Multiple Coils (15) – ustawienie stanu grupy wyjœæ
cyfrowych/znaczników
1Read Input Status (2) – odczyt stanu grupy wejœæ cyfrowych
3Read Input Registers (4) – odczyt zawartoœci grupy rejestrów wejœciowych
4Read Holding Registers (3) – odczyt zawartoœci grupy rejestrów
wyjœciowych
Preset Single Register (6) – zapis do pojedynczego rejestru wyjœciowego
Preset Multiple Registers (16) – zapis do grupy rejestrów wyjœciowych

Tabela 2.
Polecenia dla realizacji operacji na zasobach sprzêtowych sterowników
firmy Modicon



2.2.2. Transakcje w sieci Modbus, struktura komunikatów

Ka¿dy z wêz³ów podrzêdnych sieci Modbus posiada przypisany unikalny adres. Wêze³
nadrzêdny mo¿e wysy³aæ komunikat z poleceniem w trybie adresowania
indywidualnego lub rozg³aszania (ang. broadcast) tj. jednoczeœnie do wszystkich
wêz³ów podrzêdnych. Je¿eli polecenie by³o kierowane do pojedynczego wêz³a,
wówczas wêze³ ten po wykonaniu polecenia powinien odes³aæ odpowiedŸ. Pojedynczy
cykl komunikacji wêz³a nadrzêdnego z wêz³em podrzêdnym (lub ze wszystkimi w
przypadku rozg³aszania) nosi nazwê transakcji. Komunikaty zawieraj¹ce polecenia
i odpowiedzi maj¹ identyczn¹ strukturê, z³o¿on¹ z trzech pól, która zosta³a
przedstawiona na rysunku 2.
Rysunek 2. Struktura komunikatów: polecenia i odpowiedzi w sieci Modbus

Pierwsze pole ma rozmiar jednego bajtu. W poleceniu pole to zawiera adres wêz³a
podrzêdnego, bêd¹cy liczb¹ z zakresu 1...247, adres 0 zosta³ zarezerwowany dla
realizacji transmisji w trybie rozg³aszania. Wêze³ podrzêdny odsy³aj¹c odpowiedŸ
umieszcza w tym polu adres w³asny.
Drugie z pól komunikatu ma równie¿ rozmiar jednego bajtu i zawiera kod
polecenia, który okreœla dzia³anie, jakie ma podj¹æ zaadresowany wêze³ podrzêdny
na ¿¹danie wêz³a nadrzêdnego. Przyk³adowe polecenia to: odczyt zawartoœci grupy
rejestrów, zapis rejestru lub grupy rejestrów, odczyt zawartoœci rejestrów
statusowych. Kod polecenia jest liczb¹ z zakresu 1...127. W odpowiedzi pole to
jest wykorzystywane do pozytywnego lub negatywnego potwierdzenia wykonania
polecenia. Niezale¿nie od rodzaju potwierdzenia wêze³ podrzêdny umieszcza w nim
kod odebranego polecenia, a w przypadku potwierdzenia negatywnego dodatkowo
ustawia najstarszy bit tego pola na 1. Potwierdzenie negatywne, odsy³ane w
sytuacji, gdy wêze³ podrzêdny z pewnych przyczyn nie mo¿e wykonaæ polecenia,
nosi nazwê szczególnej odpowiedzi (ang. exception response). W szczególnej
odpowiedzi wêze³ podrzêdny przesy³a ponadto w polu danych kod b³êdu,
umo¿liwiaj¹cy wêz³owi nadrzêdnemu okreœlenie przyczyny jego wyst¹pienia.
D³ugoœæ pola danych, wyra¿ona w bajtach, jest zmienna, w niektórych przypadkach
równa 0. Wêze³ nadrzêdny przesy³a w polu danych argumenty poleceñ. W odpowiedzi
pole to mo¿e zawieraæ ¿¹dane przez wêze³ nadrzêdny dane lub kod b³êdu, je¿eli
jest to odpowiedŸ szczególna.
Maksymalna d³ugoœæ komunikatów protoko³u Modbus wynosi 256 bajtów.
Za³ó¿my, ¿e mamy wêze³ podrzêdny o adresie 7 zawieraj¹cy:
- 12 wyjœæ cyfrowych (00001¸00012) i 32 znaczniki bitowe (00013¸00044),
- 16 wejœæ cyfrowych (oznaczonych symbolami 10001¸10016),
- 4 wejœcia analogowe (30006¸30009),
- 386 rejestrów wyjœciowych (40001¸40386), z których dwa (40001¸4002) s¹
zwi¹zane z wyjœciami analogowymi.
W celu odczytania cyfrowych odpowiedników mierzonych wielkoœci analogowych z
wejœæ 30006¸30007 musimy do tego wêz³a wys³aæ komunikat o nastêpuj¹cej
zawartoœci (zawartoœæ bajtów podano w zapisie szesnastkowym, HI i LO oznaczaj¹
odpowiednio bardziej i mniej znacz¹cy bajt wartoœci 16-bitowej):

07Hadres wêz³a podrzêdnego
04Hkod polecenia
00Hadres pierwszego rejestru grupy HI
05Hadres pierwszego rejestru grupy LO
00Hliczba rejestrów HI
02Hliczba rejestrów LO


W polu danych przesy³ane s¹ argumenty polecenia, które s¹ liczbami 16-bitowymi:
adres – a nie numer (adres = numer – 1) – pierwszego rejestru oraz liczba
rejestrów. Je¿eli zawartoœæ odczytywanych rejestrów by³a równa np. 129 i 1716,
wêze³ podrzêdny odeœle odpowiedŸ o nastêpuj¹cej zawartoœci:


07Hadres wêz³a podrzêdnego
04Hkod polecenia
04Hliczba odsy³anych bajtów danych
00HzawartoϾ rejestru 30006 HI
81HzawartoϾ rejestru 30006 LO
06HzawartoϾ rejestru 30007 HI
B4HzawartoϾ rejestru 30007 LO


Ustawienie stanu logicznego ‘1’ na wyjœciu cyfrowym 00005 nast¹pi po odebraniu
przez wêze³ podrzêdny komunikatu o nastêpuj¹cej zawartoœci:

07Hadres wêz³a podrzêdnego
05Hkod polecenia
00Hadres wyjœcia HI
04Hadres wyjœcia LO
FFHustawiany stan wyjœcia HI
00Hustawiany stan wyjœcia LO


Jako odpowiedŸ odsy³ane jest echo polecenia.

2.2.3. Ramki sieci Modbus

Komunikaty zawieraj¹ce polecenia i odpowiedzi s¹ przez magistralê przesy³ane w
ramkach, których struktura zosta³a przedstawiona na rysunku 3. W protokole
Modbus przewidziano dwa tryby transmisji ramek:
- ASCII, nazywany trybem znakowym,
- RTU, nazywany trybem binarnym.
Tryb transmisji okreœla zawartoœæ poszczególnych pól ramki, typ sumy kontrolnej,
któr¹ zabezpiecza siê zawartoœæ przesy³anego komunikatu oraz format znaków.
Rysunek 3. Struktura ramki sieci Modbus

W trybie ASCII znacznikiem pocz¹tku ramki jest znak o kodzie 3AH (‘:’),
natomiast znacznik koñca stanowi sekwencja znaków o kodach 0DH oraz 0AH (CR LF).
Komunikat zabezpieczany jest jednobajtow¹ sum¹ kontroln¹ LRC (ang. Longitudinal
Redundancy Check). Dla zapewnienia tzw. przeŸroczystoœci informacyjnej protoko³u
ka¿dy bajt komunikatu oraz sumê kontroln¹ zapisuje siê w ramce za pomoc¹ dwóch
znaków. Pierwszy znak zawiera kod ASCII cyfry szesnastkowej zapisanej na bitach
b7¸b4, a drugi kod ASCII cyfry szesnastkowej zapisanej na bitach b3¸b0 bajtu.
Zakres dopuszczalnych zawartoœci znaków w tej czêœci ramki jest wiêc
nastêpuj¹cy: 30H...39H (‘0’...’9’) i 41H...46H (‘A’...’F’). Stosowane w trybie
ASCII formaty znaków to:
- 7-E/O-1 – 7 bitów informacyjnych + bit kontrolny + 1 bit stopu,
- 7-N-2 – 7 bitów informacyjnych + 2 bity stopu
Odstêp czasu miêdzy odbiorem kolejnych znaków ramki nie mo¿e przekraczaæ 1
sekundy.
W trybie RTU jako znacznik pocz¹tku i koñca ramki interpretowana jest cisza w
³¹czu (tzn. brak nadawania) przez czas równy co najmniej 3.5 * czas trwania
transmisji znaku. W praktyce znacznik koñca jednej ramki jest uznawany za
znacznik pocz¹tku nastêpnej. Komunikat zabezpieczany jest 16-bitow¹ sum¹
kontroln¹ CRC (ang. Cyclical Redundancy Check). Ka¿dy bajt komunikatu zapisuje
siê w ramce za pomoc¹ jednego znaku. Sumê kontroln¹ przesy³a siê za pomoc¹ dwóch
znaków, przy czym pierwszy zawiera mniej znacz¹cy bajt sumy. Znaki w ramce mog¹
zawieraæ wartoœci z zakresu 00H...FFH, a stosowane w tym trybie formaty znaków
s¹ nastêpuj¹ce:
- 8-E/O-1 – 8 bitów informacyjnych + bit kontrolny + 1 bit stopu,
- 8-N-2 – 8 bitów informacyjnych + 2 bity stopu.
Odstêp czasu miêdzy kolejnymi znakami ramki nie powinien przekraczaæ wartoœci
równej 1.5 * czas trwania transmisji znaku. Znaki ramki s¹ przesy³ane pocz¹wszy
od najmniej znacz¹cego bitu.
Zawartoœæ ramek w obu trybach transmisji np. dla przedstawionego wczeœniej
polecenia ustawienia pojedynczego wyjœcia cyfrowego jest nastêpuj¹ca:

tryb ASCII tryb RTU

3AHznacznik pocz¹tku 07Hadres wêz³a podrzêdnego
30H} adres wêz³a podrzêdnego 05Hkod polecenia
37H 00Hadres wyjœcia HI
30H} kod polecenia 04Hadres wyjœcia LO
35H FFHustawiany stan wyjœcia HI
30H} adres wyjœcia HI 00Hustawiany stan wyjœcia LO
30H CDHCRC LO
30H} adres wyjœcia LO 9DHCRC HI
34H
46H} ustawiany stan wyjœcia HI
46H
30H} ustawiany stan wyjœcia LO
30H
46H} suma kontrolna LRC
31H
0DH} znacznik koñca
0AH


2.2.4. Wyznaczanie sumy kontrolnej

Sumê kontroln¹ wyznacza siê dla zawartoœci przesy³anego komunikatu i umieszcza w
ramce po czêœci informacyjnej. Wêze³ odbiorczy oblicza sumê kontroln¹ dla
odebranego komunikatu i porównuje jej wartoœæ z wartoœci¹ otrzyman¹. Niezgodnoœæ
sum œwiadczy o wyst¹pieniu b³êdu.
Przy wyznaczaniu sumy kontrolnej LRC najpierw sumuje siê arytmetycznie, z
pominiêciem przeniesieñ, wszystkie bajty komunikatu, po czym tworzy siê
uzupe³nienie dwójkowe wyniku poprzez np. zanegowanie wszystkich bitów i dodanie
1 na pozycji najmniej znacz¹cego bitu.
Obliczanie sumy CRC odbywa siê wed³ug nastêpuj¹cego algorytmu:
1. nadanie CRC wartoœci pocz¹tkowej równej FFFFH,
2. pobranie bajtu komunikatu i wykonanie operacji XOR z m³odszym bajtem CRC
3. przesuniêcie CRC w prawo o jedn¹ pozycjê po³¹czone z wpisaniem 0 na bit
najbardziej znacz¹cy,
4. je¿eli wysuniêty bit by³ równy 1, wykonanie operacji XOR CRC ze sta³¹
A001H,
5. oœmiokrotne powtórzenie sekwencji kroków 3...4, co odpowiada
przetworzeniu ca³ego bajtu komunikatu,
6. powtórzenie sekwencji kroków 2...5 dla kolejnych bajtów komunikatu.
Kontynuacja tego procesu do przetworzenia ca³ego komunikatu.
Po wykonaniu wymienionych operacji CRC zawiera wymagan¹ wartoœæ.

2.2.5. Przerwanie transakcji

Dla transakcji realizowanych z pojedynczym wêz³em podrzêdnym ustala siê pewien
maksymalny czas oczekiwania na odbiór odpowiedzi. Jego przekroczenie powoduje
przerwanie transakcji. Przyczyny braku odpowiedzi mog¹ byæ nastêpuj¹ce:
- wyst¹pienie b³êdu transmisji ramki polecenia,
- zaadresowanie nieistniej¹cego wêz³a podrzêdnego.
3. Sieæ modu³ów pomiarowo-kontrolnych serii ADAM 4000

3.1. Wprowadzenie

Seria modu³ów ADAM 4000 (ADAM to akronim nazwy Advantech Data Acquisition
Module) zawiera ró¿norodne modu³y pomiarowo-kontrolne: licznikowe oraz wejœæ i
wyjœæ, zarówno analogowych jak i cyfrowych. Modu³y te s¹ przystosowane do pracy
w sieci o topologii magistrali, opartej na standardzie RS485, w której stanowi¹
wêz³y podrzêdne. Tak samo jak w omówionej wczeœniej sieci Modbus wêz³y podrzêdne
nie podejmuj¹ samodzielnie transmisji, jedynie odpowiadaj¹, z jednym wyj¹tkiem,
na zdalne polecenia wysy³ane przez wêze³ nadrzêdny, którym z regu³y jest
komputer PC.
Do komunikacji w modu³ami pomiarowo-kontrolnymi serii ADAM 4000 wykorzystywana
jest asynchroniczna transmisja znakowa okreœlona w standardzie RS232C. Prêdkoœæ
transmisji mo¿e byæ dobrana z zakresu 1200 ¸38400 b/s, format przesy³anych
znaków jest nastêpuj¹cy: 8 bitów danych, 1 bit stopu, brak bitu kontrolnego
(8N1). Do pojedynczego segmentu magistrali mo¿na przy³¹czyæ do 16 modu³ów.
Stosowany jest prosty protokó³ znakowy, który dalej dla uproszczenia bêdziemy
nazywaæ protoko³em Advantech [1].
3.2. Charakterystyka protoko³u Advantech

3.2.1. Polecenia

Polecenia s³u¿¹ do zdalnej konfiguracji oraz sterowania prac¹ modu³ów
pomiarowo-kontrolnych. Np. w module ADAM 4011, zawieraj¹cym jedno wejœcie
analogowe oraz jedno wejœcie i dwa wyjœcia cyfrowe, za pomoc¹ odpowiedniego
polecenia konfiguruj¹cego ustala siê m. in. typ mierzonego sygna³u analogowego
(pr¹dowy, napiêciowy) i zakres zmian jego wartoœci, a tak¿e postaæ odsy³anych
wyników pomiaru. Oprócz odczytu wyniku pomiaru u¿ytkownik ma jeszcze mo¿liwoœæ:
- ustawienia wartoœci progowej sygna³u analogowego: dolnej i górnej
(tzw. alarmów), których przekroczenie powoduje ustawienie odpowiedniego wyjœcia
cyfrowego,
- dowolnego ustawiania stanu wyjœæ cyfrowych, je¿eli funkcja alarmowania
nie jest wykorzystywana,
- odczytu bie¿¹cego stanu wejœcia cyfrowego oraz liczby podanych na to
wejœcie impulsów.
Trzy polecenia s¹ wykonywane przez wszystkie modu³y pomiarowo-kontrolne serii
ADAM 4000. S¹ to polecenia odczytu: nazwy modu³u, jego bie¿¹cej konfiguracji
oraz numeru wersji oprogramowania. Za pomoc¹ dwóch pierwszych poleceñ wêze³
nadrzêdny mo¿e samoczynnie okreœliæ, jakiego typu modu³y wchodz¹ w sk³ad
systemu.
Wszystkie modu³y wejœæ analogowych i cyfrowych wykonuj¹ polecenie tzw.
próbkowania synchronicznego, które powoduje zapamiêtanie bie¿¹cych wartoœci
sygna³ów wejœciowych w specjalnych rejestrach. Jest to jedyne polecenie, na
które odpowiedŸ nie jest odsy³ana. Zapamiêtane wartoœci komputer musi odczytaæ
osobno z ka¿dego modu³u.
Polecenia i odpowiedzi s¹ ci¹gami drukowalnych znaków ASCII, przy czym
wykorzystywane s¹ w nich tylko cyfry dziesiêtne, du¿e litery oraz ograniczony
zestaw znaków dodatkowych:
· $, #, % oraz @ – znaczniki pocz¹tku poleceñ,
· & gt; , ! oraz ? – znaczniki pocz¹tku odpowiedzi,
· +, - oraz . – do zapisu liczb, kropka jest separatorem czêœci
ca³kowitej i u³amkowej liczb rzeczywistych,
· * – w poleceniu synchronicznego próbkowania.
Ka¿demu z modu³ów pomiarowo-kontrolnych przypisywany jest adres z zakresu
0..255. Z wyj¹tkiem polecenia synchronicznego próbkowania wszystkie inne mog¹
byæ kierowane tylko do pojedynczych modu³ów. Polecenia te oraz wiêkszoœæ
odsy³anych odpowiedzi zawieraj¹ adres modu³u w zapisie szesnastkowym,
umieszczony zaraz za znacznikiem pocz¹tku i reprezentowany za pomoc¹ dwóch
znaków o kodach ASCII kolejno bardziej i mniej znacz¹cej cyfry adresu. W
poleceniu synchronicznego wyzwalania za znacznikiem pocz¹tku wystêpuj¹ dwa znaki
*.
Za³ó¿my, ¿e mamy modu³ ADAM 4011 o adresie 2, skonfigurowany do pomiarów napiêæ
z zakresu ±2.5V i odsy³ania wyników pomiaru w jednostkach in¿ynierskich (wynik
jest podawany w jednostkach wielkoœci mierzonej, jego tekstowa reprezentacja
zajmuje zawsze 7 znaków: znak liczby, kropka dziesiêtna, 5 cyfr, liczba cyfr po
kropce zale¿na od ustawionego zakresu pomiarowego). W celu odczytania wartoœci
podanego na wejœcie analogowe napiêcia nale¿y wys³aæ do modu³u polecenie o
nastêpuj¹cej zawartoœci:

23H30H32H
#02


Modu³ odeœle odpowiedŸ zawieraj¹c¹ wartoœæ napiêcia z dok³adnoœci¹ do 4 cyfr po
kropce dziesiêtnej (podanym przyk³adzie +1.2345V):

3EH2BH31H2EH32H33H34H35H
& gt; +1.2345


W celu ustawienia na wyjœciu cyfrowym DO1 stanu 1, a na wyjœciu DO0 stanu 0
nale¿y do modu³u wys³aæ polecenie:

40H30H32H44H4FH30H32H
@02DO02


gdzie DO jest kodem polecenia Set Digital Output. Dwa ostatnie znaki to dane dla
polecenia – jakie stany maj¹ byæ ustawione na poszczególnych wyjœciach;
dozwolone wartoœci to: 00, 01, 02 i 03. Modu³ potwierdzi przyjêcie i wykonanie
polecenia odsy³aj¹c nastêpuj¹c¹ odpowiedŸ:

21H30H32H
!02


Je¿eli modu³ otrzyma niepoprawne dane lub w³¹czona jest funkcja alarmowania,
wówczas odpowiedŸ bêdzie mieæ postaæ:

3FH30H32H
?02


3.2.2. Ramki protoko³u Advantech

Przez ³¹cze transmisyjne polecenia i odpowiedzi s¹ przesy³ane w ramkach, których
struktura jest nastêpuj¹ca:

polecenie
odpowiedŸLRCznacznik koñca


gdzie LRC to 8-bitowa suma kontrolna, przy czym jest ona opcjonalna – o tym, czy
ma wyst¹piæ w ramce decyduje konfiguracja modu³u, z którym komputer siê
komunikuje. Jej wartoœæ oblicza siê poprzez arytmetyczne zsumowanie, z
pominiêciem przeniesieñ z najstarszego bitu, kodów ASCII wszystkich znaków
polecenia lub odpowiedzi, a w ramce zapisuje siê j¹ w taki sam sposób, jak adres
modu³u. Znacznikiem koñca jest znak o kodzie 0DH, czyli znak CR (ang. Carriage
Return). Pierwszy znak polecenia lub odpowiedzi stanowi zarazem znacznik
pocz¹tku ramki. Jak wiadomo, mo¿e byæ nim tylko jeden ze znaków: $, #, % i @ w
ramkach z poleceniami oraz & gt; , ! oraz ? w ramkach z odpowiedziami.
Ramka zawieraj¹ca np. podane w poprzednim podrozdziale polecenie odczytu
wartoœci napiêcia na wejœciu analogowym bêdzie mieæ postaæ:

23H30H32H38H35H0DH
#0285CR


3.2.3. Reakcja modu³ów na b³êdy

Je¿eli w trakcie transmisji ramki wyst¹pi³y przek³amania pojedynczych znaków (z
tym, ¿e wykrywane s¹ tylko te, które spowodowa³y tzw. b³¹d ramki, ang. frame
error) lub, jeœli stosowane jest zabezpieczenie za pomoc¹ LRC, wyst¹pi³a
niezgodnoœæ sum: obliczonej i zawartej w odebranej ramce, wówczas ramka taka
jest odrzucana. Odrzucane s¹ równie¿ ramki bez poprawnego znacznika koñca.
Modu³ bêd¹cy odbiorc¹ polecenia sprawdza najpierw poprawnoœæ jego sk³adni, a
nastêpnie poprawnoœæ ewentualnych argumentów. Wszystkie polecenia maj¹ œciœle
okreœlon¹ d³ugoœæ, przy czym dla poleceñ zaczynaj¹cych siê od znaku $ lub @
wyznacza siê j¹ na podstawie kodu, podanego bezpoœrednio po adresie modu³u.
Polecenia o nieznanym kodzie lub nieprawid³owej d³ugoœci s¹ odrzucane, a modu³
nie odsy³a odpowiedzi. Odrzucane s¹ równie¿ polecenia zawieraj¹ce argumenty o
nieprawid³owej wartoœci, z tym ¿e modu³ odsy³a wtedy odpowiedŸ negatywn¹ o
postaci ?AA, gdzie AA jest adresem modu³u.

Literatura

1. Advantech Co., Ltd: „ADAM 4000 Series Data Acquisition Modules User’s
Manual”, http://support.elmark.com.pl/advantech/ia/ADAM4000/MANUAL/
2. Mielczarek W.: „Szeregowe interfejsy cyfrowe”, Helion, Gliwice 1993.
3. Modicon, Inc.: „Modicon Modbus Protocol Reference Guide. PI-MBUS-300
Rev. J”, 1999. http://www.modicon.com/


MODBUS_materiały.rar > Sieci przemysłowe.htm

Sieci przemys³owe








A:visited {
TEXT-DECORATION: none
}
A:link {
TEXT-DECORATION: none
}
















ASTOR & gt; GE Fanuc & gt; Sieci
przemys³owe








Astor


GE Fanuc


Wonderware


Satel


Applicom


Fanuc Robotics







Biuletyn Automatyki


Referencje


Promocje


Szukaj




& nbsp;











Nowoœci


GE Fanuc


PACSystems


Sterowniki PLC


Systemy DCS


Uk³ady I/O


Uk³ady rezerwacji


Panele operatorskie


CIMPLICITY Machine Edition


CIMPLICITY Plant Edition


Szkolenia


Certyfikaty


Katalog sterowników


Strona serwisowa








Referencje


Karta Finansowania


Karta Teleserwisowa


Kontakt







& nbsp;

Sieci przemys³owe
Du¿a ró¿norodnoœæ rozwi¹zañ
komunikacyjnych dostêpnych na rynku sprawia, i¿ wybór typu
sieci dla konkretnej aplikacji bywa utrudniony, a przecie¿
stanowi to czêsto kluczowe zagadnienie w trakcie budowy
systemu automatyki. Artyku³ niniejszy przedstawia przegl¹d
systemów komunikacji, dostêpnych dla sterowników GE Fanuc.
Omówiono tu wszystkie najwa¿niejsze rozwi¹zania sieciowe,
pocz¹wszy od prostych sieci szeregowych, a skoñczywszy na tych
najbardziej zaawansowanych i wydajnych. W czêœci pierwszej
prezentujemy dwie sieci - Modbus i Genius.
Modbus
Jest to sieæ wprowadzona przez firmê Modicon w 1980 roku,
przyjêta jako standard przez wiêkszoœæ producentów sterowników
przemys³owych dla komunikacji asynchronicznej. Protokó³ sieci
jest bardzo prosty, a ramka danych krótka, dlatego sieci
Modbus mog¹ byæ ³atwo implementowane w dowolnym niemal
urz¹dzeniu.
Modbus jest to sieæ typu Master - Slave. Stacja Master
(pojedyncza) zarz¹dza kilkoma stacjami Slave, odpytuj¹c je
cyklicznie zgodnie z list¹ abonentów sieci umieszczon¹ w
stacji nadrzêdnej. Typowa prêdkoœæ transmisji danych wynosi
9.6Kb/s lub 19.2Kb/s. Wykorzystywane s¹ szeregowe ³¹cza
komunikacyjne RS-232, RS-422, RS-485, a tak¿e po³¹czenia
modemowe.
Protokó³ Modbus posiada dwa tryby transmisji: ASCII i RTU,
ró¿ni¹ce siê miedzy sob¹ formatem ramki komunikacyjnej.
Okreœlony format ramki pozwala urz¹dzeniu odbieraj¹cemu na
odrzucenie ramek niekompletnych i sygnalizacjê zwi¹zanych z
tym b³êdów, dziêki czemu transmisja jest dobrze zabezpieczona
przed nieprawid³owoœciami.
Modbus wykorzystywany jest w ma³ych i œrednich systemach
dzia³aj¹cych na jednej jednostce g³ównej (zarz¹dzaj¹cej),
gdzie konieczne jest zbieranie i przesy³anie informacji od
urz¹dzeñ peryferyjnych, takich jak czujniki, regulatory,
mierniki, itd., do stacji g³ównej. Bardzo dobrze sprawdza siê
w sterowaniu obiektami o rozproszonej strukturze, szczególnie
jeœli nie mo¿na zainstalowaæ po³¹czenia przewodowego -
wykorzystuje siê wtedy transmisjê bezprzewodow¹ z
wykorzystaniem radiomodemów.
Sieæ Modbus a sterowniki GE Fanuc
Sterowniki serii VersaMax Micro/Nano mog¹ pracowaæ w
sieci szeregowej Modbus RTU wy³¹cznie jako urz¹dzenia Slave.
Dotyczy to zarówno najmniejszych modeli wyposa¿onych w jeden
port szeregowy RS232 (VersaMax Nano oraz Micro tzw.
8-punktowe), jak równie¿ wiêkszych modeli wyposa¿onych w dwa
porty. W tym drugim przypadku protokó³ Modbus RTU dostêpny
jest na porcie drugim (RS422/485). Dla zwiêkszenia
elastycznoœci dostêpna jest gama konwerterów, umo¿liwiaj¹cych
zmianê standardu z RS-232 na RS-422 lub odwrotnie.
W sieci Modbus mog¹ tak¿e pracowaæ sterowniki
VersaMax , zarówno jako urz¹dzenia Master, jak
i & nbsp;Slave. Protokó³ ten jest dostêpny na obu portach ka¿dej
z & nbsp;jednostek centralnych (CPU) tego sterownika – w
przypadku obs³ugi trybu Master konieczne jest uaktualnienie
wewnêtrznego oprogramowania (firmware) jednostki do najnowszej
wersji (przynajmniej 2.31 - dostêpna nieodp³atnie w firmie
ASTOR).
Sterowniki serii OCS , w tym tak¿e jednostki
RCS oraz MiniOCS , s¹ najbardziej elastyczne,
je¿eli chodzi o transmisjê danych w protokole Modbus. W
zasadzie w sterownikach tych wszystko jest programowalne: tryb
pracy urz¹dzenia (Master lub Slave), typ protoko³u Modbus (RTU
lub ASCII) oraz oczywiœcie parametry portu szeregowego.
Dotyczy to zarówno jednostek posiadaj¹cych jeden port
komunikacyjny RS-232, jak i modeli dwuportowych (RS-232 i
RS-485).
W rodzinie sterowników serii 90-30 dostêpnych jest
kilka modu³ów i jednostek centralnych obs³uguj¹cych protokó³
Modbus. Najwiêksze mo¿liwoœci daje zastosowanie jednostki
CPU363, wyposa¿onej ³¹cznie w trzy porty szeregowe, z czego
jeden jest fizycznie umieszczony w zasilaczu, natomiast
pozosta³e dwa w obudowie modu³u. W³aœnie te dwa porty mog¹
zostaæ skonfigurowane do pracy w protokole Modbus, zarówno
Master, jak i Slave, z tym ¿e w przypadku obs³ugi trybu Master
konieczne jest uaktualnienie wewnêtrznego oprogramowania
(firmware) jednostki do najnowszej wersji (przynajmniej 10.70
- dostêpna nieodp³atnie w firmie ASTOR).
W przypadku innych jednostek centralnych konieczne jest
stosowanie dodatkowych modu³ów komunikacyjnych. Je¿eli
sterownik ma pracowaæ w sieci jako urz¹dzenie Slave, to
u¿ytkownik ma do wyboru jeden z dwóch modu³ów: RTU900 lub
CMM311, przy czym nale¿y pamiêtaæ, ¿e drugi z tych modu³ów nie
wspó³pracuje z jednostkami centralnymi zintegrowanymi z p³yt¹
bazow¹ (a wiêc CPU311/313/323). Modu³ RTU900 wyposa¿ony jest w
jeden port (w standardzie RS-232 lub 422), który obs³uguje
protokó³ Modbus Slave zarówno w odmianie ASCII, jak i RTU. Z
kolei modu³ CMM311 posiada dwa porty komunikacyjne: jeden
RS-232 i jeden konfigurowalny RS-232/422/485, oba te porty
obs³uguj¹ protokó³ Modbus RTU Slave.
Dla sterownika serii 90-30 dostêpny jest tak¿e modu³ RTM705
obs³uguj¹cy protokó³ Modbus Master. Modu³ ten jest wyposa¿ony
- podobnie jak CMM311 - w dwa porty szeregowe: jeden RS-232 i
jeden konfigurowalny RS-232/422/485, na obu tych portach
dostêpny jest protokó³ Modbus Master w odmianie RTU lub ASCII.
W tym przypadku równie¿ nale¿y pamiêtaæ, ¿e modu³ RTM705
wymaga przynajmniej jednostki centralnej CPU331 (nie pracuje z
CPU311/313/323).
Genius
Genius to wydajny i elastyczny system rozwi¹zañ firmy GE
Fanuc, przeznaczony dla uk³adów sterowania, którym stawiane s¹
wysokie wymagania niezawodnoœci i szybkoœci dzia³ania. System
ten sk³ada siê z trzech g³ównych elementów: uk³adów
wejœæ/wyjœæ rozproszonych (bloki Genius, modu³y VersaMax I/O),
wspó³pracuj¹cych z systemami sterowania opartymi na
sterownikach serii 90-70 lub 90-30, oraz magistrali Genius,
³¹cz¹cej te elementy. System Genius pozwala na budowanie
rozmaitych wyrafinowanych systemów z redundancj¹ jednostek
centralnych, magistral komunikacyjnych oraz uk³adów
wejϾ/wyjϾ.
Sieæ Genius, stanowi¹ca szkielet systemu Genius, zosta³a
zaprezentowana przez firmê General Electric w 1986 r. Jest to
sieæ typu “token-ring” - tzw. token (znacznik), przekazywany
miedzy stacjami sieci, uprawnia stacjê do nadawania danych. W
konsekwencji, Genius jest sieci¹ o zdeterminowanym czasie
dostêpu do magistrali, czas nadawania przez ka¿d¹ stacjê jest
bowiem ograniczony (parametryzowany) - informacje s¹
przesy³ane w sta³ym cyklu (Bus Scan Time), zale¿nym od liczby
i rodzaju urz¹dzeñ na magistrali, szybkoœci transmisji i
iloœci danych oraz rodzaju systemu (zwyk³y lub z redundancj¹).
Najczêœciej czas trwania jednego cyklu wynosi od 20 do 200 ms.
Sieæ Genius zapewnia maksymaln¹ realn¹ szybkoœæ transmisji
danych 153 Kb/s i umo¿liwia pod³¹czenie do 32 urz¹dzeñ w
jednej ga³êzi sieci. D³ugoœæ magistrali w ramach jednej ga³êzi
mo¿e siêgaæ nawet do 2200 m, przy prêdkoœci transmisji danych
zmniejszonej do 38 Kb/s, oraz do 600 m przy prêdkoœci
maksymalnej.
Sieæ Genius stosuje siê w aplikacjach wymagaj¹cych szybkich
transferów danych pomiêdzy rozproszonymi modu³ami wejœæ/wyjœæ.
Sieæ warto stosowaæ wszêdzie tam, gdzie stopieñ rozproszenia
uk³adów I/O jest du¿y, a iloœæ sygna³ów do przes³ania jest
znaczna, jak równie¿ w tych aplikacjach, w których wymagana
jest redundancja jednostek centralnych i/lub magistral
komunikacyjnych (praca systemów ESD firmy GE Fanuc,
posiadaj¹cych certyfikat TÜV, oparta jest w znacznej mierze na
sieci Genius).
Sieæ Genius a sterowniki GE Fanuc
Aby sterownik serii 90-30 móg³ komunikowaæ siê z otoczeniem
za poœrednictwem sieci Genius, konieczne jest zastosowanie
odpowiedniego modu³u komunikacyjnego. Podstawowym takim
modu³em jest CMM302. Pozwala on na komunikowanie siê z 31
innymi urz¹dzeniami, umo¿liwia odczyt danych z oddalonych
modu³ów wejœæ/wyjœæ (nie mo¿e jednak wysy³aæ do nich danych).
Pozwala adresowaæ wszelkie typy danych (np. %G, %M, %R, %AI,
%AQ). Drugim ograniczeniem jest mo¿liwoœæ wysy³ania w ka¿dym
cyklu do 64 wartoœci analogowych lub do 1024 wartoœci
cyfrowych. Modu³ dobrze nadaje siê do szybkiej wymiany danych
pomiêdzy kilkoma sterownikami, nie wymaga programowania -
wystarczy bardzo prosta konfiguracja komunikacji. Do jednego
sterownika 90-30 mo¿na pod³¹czaæ wiêksz¹ liczbê modu³ów
CMM302, co pozwala na dogodne koncentrowanie danych nawet z
bardzo rozleg³ych instalacji.
Drugim modu³em dostêpnym dla sterownika 90-30 jest
kontroler magistrali BEM331. Modu³ ten posiada znacznie
rozszerzony zakres funkcji i nie ma ograniczeñ
charakterystycznych dla modu³u CMM302. Realizuje on
asynchroniczn¹ obs³ugê komunikacji w postaci danych globalnych
i datagramów pomiêdzy jednostk¹ centraln¹ sterownika a
urz¹dzeniami pod³¹czonymi do magistrali komunikacyjnej Genius
(oddalone modu³y wejœæ/wyjœæ systemu Genius, oddalone
wejœcia/wyjœcia VersaMax, sterowniki, komputery PC z kart¹
komunikacyjn¹ Genius, rêczny programator Hand Held Monitor do
konfigurowania modu³ów - maksymalnie 31 urz¹dzeñ na jednej
magistrali). W systemie 90-30 mo¿na zainstalowaæ do oœmiu
modu³ów Genius Bus Controller, ka¿dy wspó³pracuje z oddzieln¹
magistral¹ Genius. Za pomoc¹ modu³u BEM331 mo¿na skonfigurowaæ
system z redundancj¹ jednostek centralnych sterownika 90-30.
System taki sk³ada siê z dwóch lub trzech jednostek
centralnych, z której druga oraz trzecia pe³ni¹ rolê
zapasowych i kolejno przejmuj¹ sterowanie w przypadku awarii
pierwszej lub drugiej jednostki.
Poza wy¿ej wymienionymi dostêpny jest tak¿e modu³
kontrolera magistrali Genius BEM731 - odpowiednik BEM331
przeznaczony dla sterowników serii 90-70, a tak¿e karty
komunikacyjne Genius PCIM dla komputerów PC.
Arkadiusz Mystkowski (Politechnika
Bia³ostocka) Mateusz Pierzcha³a (ASTOR Sp. z
o.o.)

& nbsp;



& nbsp;