Содержание
- Write error modbus poll
- How to fix Modbus Poll Write Error Break Condition —> Error?
- Contents
- What is Modbus Poll Write Error Break Condition error?
- What causes Modbus Poll Write Error Break Condition error?
- How to easily fix Modbus Poll Write Error Break Condition error?
Write error modbus poll
Automation (formerly known as OLE Automation) makes it possible for one application to manipulate objects implemented in another application.
An Automation client is an application that can manipulate exposed objects belonging to another application. This is also called an Automation controller.
An Automation server is an application that exposes programmable objects to other applications. Modbus Poll is an automation server.
That means you can use any program that supports VBA (Visual Basic for Applications) such as Visual Basic, Excel etc. to interpret and show the modbus data according to your specific requirements.
12.1. Excel example
You should display the Developer tab or run in developer mode when you want to write macros.
12.1.1. Excel 2007
- Click the Microsoft office button and then click Excel options.
- Click popular and then select the show Developers tab in the ribbon check box.
Note the ribbon is part of the Microsoft fluent user interface.
12.1.2. Excel 2010
- Click on the file tab.
- Click options. Excel Options window will open.
- On the left pane click Customize Ribbon.
- On the right pane, under Main Tabs, check the Developer check box.
- Click OK. The Developer tab should now show in the ribbon (right most tab).
12.1.3. Excel sample code
This example opens two windows. One reading registers and another reading Coils.
Modbus Poll is hidden but you can show it by uncomment the «ShowWindow» line. This will show one of the windows.
An example is also included with the Modbus Poll installation.
Start → All Programs → Modbus Poll → Excel Example
Excel VBA Example
Public doc1 As Object
Public doc2 As Object
Public app As Object
Dim res As Integer
Dim n As Integer
Private Sub StartModbusPoll_Click ()
Set app = CreateObject ( «Mbpoll.Application» )
Set doc1 = CreateObject ( «Mbpoll.Document» )
Set doc2 = CreateObject ( «Mbpoll.Document» )
‘ Read 10 Holding Registers every 1000ms
res = doc1.ReadHoldingRegisters ( 1 , 0 , 10 , 1000 )
‘ Read 10 Coil Status every 1000ms
res = doc2.ReadCoils ( 1 , 0 , 10 , 1000 )
app.Connection = 1 ‘ Modbus TCP/IP
app.IPAddress = «127.0.0.1» ‘ local host
Private Sub Read_Click ()
Cells ( 5 , 7 ) = doc1.ReadResult () ‘Show results for the requests
Cells ( 6 , 7 ) = doc2.ReadResult ()
Cells ( 5 + n , 2 ) = doc1.SRegisters ( n )
Cells ( 18 + n , 2 ) = doc2.Coils ( n )
12.2. Connection Functions/Properties
The following properties and functions do the same as you setup in the connection dialog (F3).
Connection selects the desired connection. A serial port or one of the Ethernet connections can be selected.
Property Connection as Integer
0 = Serial port
1 = Modbus TCP/IP
2 = Modbus UDP/IP
3 = Modbus ASCII/RTU over TCP/IP
4 = Modbus ASCII/RTU over UDP/IP
Applicable only for Connection = 0
Property BaudRate as Long
Applicable only for Connection = 0
Property DataBits as Integer
Applicable only for Connection = 0
Property Parity as Integer
0 = None
1 = Odd
2 = Even (Default)+
Applicable only for Connection = 0
Property StopBits as Integer
Applicable only for Connection = 0
Property SerialPort as Integer
Default value = 1
The ResponseTimeout specifies the length of time in ms that Modbus Poll should wait for a response from a slave device before giving up.
Property ResponseTimeout as Integer
Default value = 1000
Applicable only for Connection = 1…4
Property ServerPort as Long
Default value = 502
The ConnectTimeout specifies the length of time that Modbus Poll should wait for a TCP/IP connection to succeed.
Applicable only for Connection = 1…4
Property ConnectTimeout as Integer
Default value = 1000ms
Applicable only for Connection = 1…4
Property IPVersion as Integer
4 = IP Version 4 (Default)
6 = IP Version 6
Opens the connection selected with the Connection property.
Function OpenConnection () As Integer
For error 3-5: Please check if you have the latest serial port driver.
0 = SUCCESS
1 = Serial Port not available
3 = Serial port. Not possible to get current settings from port driver.
4 = Serial port. Serial port driver did not accept port settings.
5 = Serial port. Serial port driver did not accept timeout settings.
12 = TCP/UDP Connection failed. WSA start up
13 = TCP/UDP Connection failed. Connect error
14 = TCP/UDP Connection failed. Timeout
15 = TCP/UDP Connection failed. IOCTL
17 = TCP/UDP Connection failed. Socket error
21 = TCP/UDP Connection failed. Address information
Example how to open a Modbus TCP/IP connection
Public app As Object
Dim res As Integer
‘ Create an object to Modbus Poll
Set app = CreateObject(«Mbpoll.Application»)
app.Connection = 1 ‘ Select Modbus TCP/IP
Example how to setup a serial connection
Public app As Object
Dim status As Integer
‘ Create an object to Modbus Poll
Set app = CreateObject(«Mbpoll.Application»)
app.Connection = 0 ‘ Mode is serial port
app.SerialPort = 1 ‘ Com port 1
app.BaudRate = 9600 ‘ 9600 baud
app.Parity = 0 ‘ None parity
app.Mode = 0 ‘ RTU mode
app.ResponseTimeout = 1000 ‘ Wait 1000ms until give up
Function CloseConnection () As Integer
Zero if success. Nonzero value if failed.
12.3. Read Functions
The following functions do the same as you setup in the read/write definition dialog (F8). Read functions are associated with a Modbus Poll document. (The window with data)
.Example
‘ First a Modbus Poll document is needed.
Public doc As Object
Set doc = CreateObject(«Mbpoll.Document»)
res = doc.ReadCoils(1, 0, 100, 1000) ‘ Read 100 coils every 1000ms
You must create a Read before you can use properties to get data.
Function ReadCoils (SlaveID As Integer, Address As Long, Quantity As Integer, ScanRate As Long) As Integer
True if success. False if not success
SlaveID: The slave address 1 to 255
Address: The data address (Base 0)
Quantity: The number of data. 1 to 2000
ScanRate: 0 to 3600000ms
Function ReadDiscreteInputs (SlaveID As Integer, Address As Long, Quantity As Integer, ScanRate As Long) As Integer
True if success. False if not success
SlaveID: The slave address 1 to 255
Address: The data address (Base 0)
Quantity: The number of data. 1 to 2000
ScanRate: 0 to 3600000ms
Function ReadHoldingRegisters (SlaveID As Integer, Address As Long, Quantity As Integer, ScanRate As Long) As Integer
True if success. False if not success
SlaveID: The slave address 1 to 255
Address: The data address (Base 0)
Quantity: The number of data. 1 to 125
ScanRate: 0 to 3600000ms
Function ReadInputRegisters (SlaveID As Integer, Address As Long, Quantity As Integer, ScanRate As Long) As Integer
True if success. False if not success
SlaveID: The slave address 1 to 255
Address: The data address (Base 0)
Quantity: The number of data. 1 to 125
ScanRate: 0 to 3600000ms
ShowWindow()
As default Modbus document windows are hidden. The ShowWindow function makes Modbus Poll visible and show the document with data content.
Property ByteOrder As Integer
Sets the byte order used by Longs, Floats and Doubles properties.
0 = Big-endian (Default)
1 = Little-endian
2 = Big-endian byte swap
3 = Little-endian byte swap
Example for Longs:
Byte Order: Big-endian
The decimal number 123456789 or in hexadecimal 07 5B CD 15
Order as they come over the wire in a Modbus message: 07 5B CD 15
Use this property to check if communication established with Read is running successful.
Property ReadResult As Integer
Return Value:
0 = SUCCESS
1 = TIMEOUT ERROR
2 = CRC ERROR
3 = RESPONSE ERROR (The response was not the expected slave id, function or address)
4 = WRITE ERROR
5 = READ ERROR
6 = PORTNOTOPEN ERROR
10 = DATA UNINITIALIZED
11 = INSUFFICIENT BYTES RECEIVED
16 = BYTE COUNT ERROR
19 = TRANSACTION ID ERROR
81h = ILLEGAL FUNCTION
82h = ILLEGAL DATA ADDRESS
83h = ILLEGAL DATA VALUE
84h = FAILURE IN ASSOCIATED DEVICE
85h = ACKNOWLEDGE
86h = BUSY, REJECTED MESSAGE
87h = NAK-NEGATIVE ACKNOWLEDGMENT
Return a write result as an integer.
Use this function to check if a write was successful. The value is DATA_UNINITIALIZED until the result from the slave is available. See ReadResult for a list of possible values.
Property WriteResult As Integer
12.4. Automation data properties
The below properties are used to set or get values in the internal write/read arrays in Modbus Poll. The Index used is not a Modbus Address. The Index always counts from 0 no matter of the address used. The data properties are associated with a Modbus Poll document. (The window with data)
‘ doc is assumed created first. See Excel example.
‘ Write 3 registers stored in Modbus Poll internal array
‘ to Modbus address 100 (40101)
res = doc.WriteMultipleRegisters(1, 100, 3)
Example 2 with floating point values:
res = doc. WriteMultipleRegisters(1, 0, 6) «Write the 6 register stored in Modbus Poll
‘ 6 Registers are written as float is 32 bit wide.
Property Coils (Index As Integer) As Integer
Sets a coil in the write array structure or return a coil from the read array.
Coils (Index) [=newvalue]
Property SRegisters (Index As Integer) As Integer
Sets a register in the write array structure or return a register from the read array.
SRegisters (Index) [=newvalue]
Property URegisters (Index As Integer) As Long
Sets a register in the write array structure or return a register from the read array.
Object. URegisters (Index) [=newvalue]
Property Ints_32 (Index As Integer) As Double
Sets a 32 Bit integer in the write array structure or return an integer from the read array.
Ints_32 (Index) [=newvalue]
Property UInts_32 (Index As Integer) As Double
Sets a 32 Bit unsigned integer in the write array structure or return an unsigned integer from the read array.
UInts_32 (Index) [=newvalue]
Property Ints_64 (Index As Integer) As Double
Sets a 64 Bit integer in the write array structure or return an integer from the read array.
Ints_64 (Index) [=newvalue]
Property UInts_64 (Index As Integer) As Double
Sets a 64 Bit unsigned integer in the write array structure or return an unsigned integer from the read array.
UInts_64 (Index) [=newvalue]
Property Floats (Index As Integer) As Single
Sets a float in the write array structure or return a float from the read array.
Floats* (Index) [=newvalue]
Property Doubles (Index As Integer) As Double
Sets a double in the write array structure or return a double from the read array.
Doubles* (Index) [=newvalue]
12.5. Automation Write Functions
The write functions write the values stored in the array filled by the properties. The functions are associated with a Modbus Poll document. (The window with data)
Function WriteSingleCoil (SlaveID As Integer, Address As Long) As Integer
True if write array is ready and the data are sent. False if array empty or error in parameters.
The controlling application is responsible for verifying the write operation by reading back the value written.
SlaveID: The slave address 0 to 255
Address: The data address (Base 0)
Writes the first coil stored in the write array.
Function 05 is used.
Function WriteSingleRegister (SlaveID As Integer, Address As Long) As Integer
True if write array is ready and the data are sent. False if array empty or error in parameters.
The controlling application is responsible for verifying the write operation by reading back the value written.
SlaveID: The slave address 0 to 255
Address: The data address (Base 0)
Writes the first register stored in the write array.
Function 06 is used.
Function WriteMultipleCoils (SlaveID As Integer, Address As Long, Quantity As Integer) As Integer
True if write array is ready and the data are sent. False if array empty or error in parameters.
The controlling application is responsible for verifying the write operation by reading back the values written.
SlaveID: The slave address 0 to 255
Address: The data address (Base 0)
Quantity The number of data. 1 to 1968
Write the coils stored in the write array.
Function 15 is used.
Function WriteMultipleRegisters (SlaveID As Integer, Address As Long, Quantity As Integer) As Integer
True if write array is ready and the data are sent. False if array empty or error in parameters.
The controlling application is responsible for verifying the write operation by reading back the value written.
SlaveID: The slave address 0 to 255
Address: The data address (Base 0)
Quantity: The number of data. 1 to 123
Write the registers stored in the write array.
Function 16 is used.
Источник
How to fix Modbus Poll Write Error Break Condition —> Error?
Click here follow the steps to fix Modbus Poll Write Error Break Condition and related errors.
To Fix (Modbus Poll Write Error Break Condition) error you need to follow the steps below:
Click ‘Fix All‘ and you’re done! |
Compatibility : Windows 7, 8, Vista, XP Limitations: This download is a free evaluation version. To unlock all features and tools, a purchase is required. Modbus Poll Write Error Break Condition Error Codes are caused in one way or another by misconfigured system files in your windows operating system. If you have Modbus Poll Write Error Break Condition errors then we strongly recommend that you Download (Modbus Poll Write Error Break Condition) Repair Tool . This article contains information that shows you how to fix Modbus Poll Write Error Break Condition both (manually) and (automatically) , In addition, this article will help you troubleshoot some common error messages related to Modbus Poll Write Error Break Condition error code that you may receive. Note: This article was updated on 2023-01-10 and previously published under WIKI_Q210794 ContentsWhat is Modbus Poll Write Error Break Condition error?The Modbus Poll Write Error Break Condition error is the Hexadecimal format of the error caused. This is common error code format used by windows and other windows compatible software and driver vendors. This code is used by the vendor to identify the error caused. This Modbus Poll Write Error Break Condition error code has a numeric error number and a technical description. In some cases the error may have more parameters in Modbus Poll Write Error Break Condition format .This additional hexadecimal code are the address of the memory locations where the instruction(s) was loaded at the time of the error. What causes Modbus Poll Write Error Break Condition error?The Modbus Poll Write Error Break Condition error may be caused by windows system files damage. The corrupted system files entries can be a real threat to the well being of your computer. There can be many events which may have resulted in the system files errors. An incomplete installation, an incomplete uninstall, improper deletion of applications or hardware. It can also be caused if your computer is recovered from a virus or adware/spyware attack or by an improper shutdown of the computer. All the above actives may result in the deletion or corruption of the entries in the windows system files. This corrupted system file will lead to the missing and wrongly linked information and files needed for the proper working of the application. How to easily fix Modbus Poll Write Error Break Condition error?There are two (2) ways to fix Modbus Poll Write Error Break Condition Error: Advanced Computer User Solution (manual update): 1) Start your computer and log on as an administrator. 2) Click the Start button then select All Programs, Accessories, System Tools, and then click System Restore. 3) In the new window, select «Restore my computer to an earlier time» option and then click Next. 4) Select the most recent system restore point from the «On this list, click a restore point» list, and then click Next. 5) Click Next on the confirmation window. 6) Restarts the computer when the restoration is finished. Novice Computer User Solution (completely automated): 2) Install program and click Scan button. 3) Click the Fix Errors button when scan is completed. 4) Restart your computer. How does it work? This tool will scan and diagnose, then repairs, your PC with patent pending technology that fix your windows operating system registry structure. Источник Adblock |
---|
Instructions
12. OLE/Automation
Automation (formerly known as OLE Automation) makes it possible for one application to manipulate objects implemented in another application.
An Automation client is an application that can manipulate exposed objects belonging to another application. This is also called an Automation controller.
An Automation server is an application that exposes programmable objects to other applications. Modbus Poll is an automation server.
That means you can use any program that supports VBA (Visual Basic for Applications) such as Visual Basic, Excel etc. to interpret and show the modbus data according to your specific requirements.
12.1. Excel example
You should display the Developer tab or run in developer mode when you want to write macros.
12.1.1. Excel 2007
- Click the Microsoft office button and then click Excel options.
- Click popular and then select the show Developers tab in the ribbon check box.
Note the ribbon is part of the Microsoft fluent user interface.
12.1.2. Excel 2010
- Click on the file tab.
- Click options. Excel Options window will open.
- On the left pane click Customize Ribbon.
- On the right pane, under Main Tabs, check the Developer check box.
- Click OK. The Developer tab should now show in the ribbon (right most tab).
12.1.3. Excel sample code
This example opens two windows. One reading registers and another reading Coils.
Modbus Poll is hidden but you can show it by uncomment the «ShowWindow» line. This will show one of the windows.
An example is also included with the Modbus Poll installation.
Start → All Programs → Modbus Poll → Excel Example
Excel VBA Example
Public doc1 As Object
Public doc2 As Object
Public app As Object
Dim res As Integer
Dim n As Integer
Private Sub StartModbusPoll_Click()
Set app = CreateObject(«Mbpoll.Application»)
Set doc1 = CreateObject(«Mbpoll.Document»)
Set doc2 = CreateObject(«Mbpoll.Document»)
‘ Read 10 Holding Registers every 1000ms
res = doc1.ReadHoldingRegisters(1, 0, 10, 1000)
‘ Read 10 Coil Status every 1000ms
res = doc2.ReadCoils(1, 0, 10, 1000)
‘ doc1.ShowWindow()
app.Connection = 1 ‘ Modbus TCP/IP
app.IPAddress = «127.0.0.1» ‘ local host
app.ServerPort = 502
app.ConnectTimeout = 1000
res = app.OpenConnection()
End Sub
Private Sub Read_Click()
Cells(5, 7) = doc1.ReadResult() ‘Show results for the requests
Cells(6, 7) = doc2.ReadResult()
For n = 0 To 9
Cells(5 + n, 2) = doc1.SRegisters(n)
Next n
For n = 0 To 9
Cells(18 + n, 2) = doc2.Coils(n)
Next n
End Sub
12.2. Connection Functions/Properties
The following properties and functions do the same as you setup in the connection dialog (F3).
12.2.1. Connection
Connection selects the desired connection. A serial port or one of the Ethernet connections can be selected.
Property Connection as Integer
Valid values
0 = Serial port
1 = Modbus TCP/IP
2 = Modbus UDP/IP
3 = Modbus ASCII/RTU over TCP/IP
4 = Modbus ASCII/RTU over UDP/IP
12.2.2. BaudRate
Applicable only for Connection = 0
Property BaudRate as Long
Valid values
300
600
1200
2400
4800
9600 (Default)
14400
19200
38400
56000
57600
115200
128000
256000
460800
921600
Example
BaudRate = 9600
12.2.3. DataBits
Applicable only for Connection = 0
Property DataBits as Integer
Valid values
7
8 (Default)
Example
DataBits = 8
12.2.4. Parity
Applicable only for Connection = 0
Property Parity as Integer
Valid values
0 = None
1 = Odd
2 = Even (Default)+
Example
Parity = 2
12.2.5. StopBits
Applicable only for Connection = 0
Property StopBits as Integer
Valid values
1 (Default)+ 2
Example
StopBits = 1
12.2.6. SerialPort
Applicable only for Connection = 0
Property SerialPort as Integer
Valid values
1…255
Default value = 1
Example
SerialPort = 1
12.2.7. ResponseTimeout
The ResponseTimeout specifies the length of time in ms that Modbus Poll should wait for a response from a slave device before giving up.
Property ResponseTimeout as Integer
Valid values
50…100000
Default value = 1000
Example:
ResponseTimeout = 1000
12.2.8. ServerPort
Applicable only for Connection = 1…4
Property ServerPort as Long
Valid values
0…65535
Default value = 502
Example
ServerPort = 502
12.2.9. ConnectTimeout
The ConnectTimeout specifies the length of time that Modbus Poll should wait for a TCP/IP connection to succeed.
Applicable only for Connection = 1…4
Property ConnectTimeout as Integer
Valid values
100…30000ms
Default value = 1000ms
Example
ConnectTimeout = 1000
12.2.10. IPVersion
Applicable only for Connection = 1…4
Property IPVersion as Integer
Valid values
4 = IP Version 4 (Default)
6 = IP Version 6
Example
IPVersion = 4
12.2.11. OpenConnection
Opens the connection selected with the Connection property.
Function OpenConnection() As Integer
Return Value:
For error 3-5: Please check if you have the latest serial port driver.
0 = SUCCESS
1 = Serial Port not available
3 = Serial port. Not possible to get current settings from port driver.
4 = Serial port. Serial port driver did not accept port settings.
5 = Serial port. Serial port driver did not accept timeout settings.
12 = TCP/UDP Connection failed. WSA start up
13 = TCP/UDP Connection failed. Connect error
14 = TCP/UDP Connection failed. Timeout
15 = TCP/UDP Connection failed. IOCTL
17 = TCP/UDP Connection failed. Socket error
21 = TCP/UDP Connection failed. Address information
Example how to open a Modbus TCP/IP connection
Public app As Object
Dim res As Integer
‘ Create an object to Modbus Poll
Set app = CreateObject(«Mbpoll.Application»)
app.Connection = 1 ‘ Select Modbus TCP/IP
app.IPVersion = 4
app.IPAddress = «192.168.1.27»
app.ServerPort = 502
app.ConnectTimeout = 1000
app.ResponseTimeout = 1000
res = OpenConnection()
Example how to setup a serial connection
Public app As Object
Dim status As Integer
‘ Create an object to Modbus Poll
Set app = CreateObject(«Mbpoll.Application»)
app.Connection = 0 ‘ Mode is serial port
app.SerialPort = 1 ‘ Com port 1
app.BaudRate = 9600 ‘ 9600 baud
app.Parity = 0 ‘ None parity
app.Mode = 0 ‘ RTU mode
app.ResponseTimeout = 1000 ‘ Wait 1000ms until give up
status = app.OpenConnection()
12.2.12. CloseConnection
Function CloseConnection() As Integer
Return Value
Zero if success. Nonzero value if failed.
12.3. Read Functions
The following functions do the same as you setup in the read/write definition dialog (F8). Read functions are associated with a Modbus Poll document. (The window with data)
.Example
‘ First a Modbus Poll document is needed.
Public doc As Object
Set doc = CreateObject(«Mbpoll.Document»)
res = doc.ReadCoils(1, 0, 100, 1000) ‘ Read 100 coils every 1000ms
You must create a Read before you can use properties to get data. |
12.3.1. ReadCoils
Function ReadCoils(SlaveID As Integer, Address As Long, Quantity As Integer, ScanRate As Long) As Integer
Return Value
True if success. False if not success
Parameters
SlaveID: The slave address 1 to 255
Address: The data address (Base 0)
Quantity: The number of data. 1 to 2000
ScanRate: 0 to 3600000ms
12.3.2. ReadDiscreteInputs
Function ReadDiscreteInputs(SlaveID As Integer, Address As Long, Quantity As Integer, ScanRate As Long) As Integer
Return Value
True if success. False if not success
Parameters
SlaveID: The slave address 1 to 255
Address: The data address (Base 0)
Quantity: The number of data. 1 to 2000
ScanRate: 0 to 3600000ms
12.3.3. ReadHoldingRegisters
Function ReadHoldingRegisters(SlaveID As Integer, Address As Long, Quantity As Integer, ScanRate As Long) As Integer
Return Value
True if success. False if not success
Parameters
SlaveID: The slave address 1 to 255
Address: The data address (Base 0)
Quantity: The number of data. 1 to 125
ScanRate: 0 to 3600000ms
12.3.4. ReadInputRegisters
Function ReadInputRegisters(SlaveID As Integer, Address As Long, Quantity As Integer, ScanRate As Long) As Integer
Return Value
True if success. False if not success
Parameters
SlaveID: The slave address 1 to 255
Address: The data address (Base 0)
Quantity: The number of data. 1 to 125
ScanRate: 0 to 3600000ms
12.3.5. ShowWindow
ShowWindow()
As default Modbus document windows are hidden. The ShowWindow function makes Modbus Poll visible and show the document with data content.
12.3.6. ByteOrder
Property ByteOrder As Integer
Description
Sets the byte order used by Longs, Floats and Doubles properties.
0 = Big-endian (Default)
1 = Little-endian
2 = Big-endian byte swap
3 = Little-endian byte swap
Example for Longs:
Byte Order: Big-endian
The decimal number 123456789 or in hexadecimal 07 5B CD 15
Order as they come over the wire in a Modbus message: 07 5B CD 15
Syntax
ByteOrder [=newvalue]
12.3.7. ReadResult
Use this property to check if communication established with Read is running successful.
Property ReadResult As Integer
Return Value:
0 = SUCCESS
1 = TIMEOUT ERROR
2 = CRC ERROR
3 = RESPONSE ERROR (The response was not the expected slave id, function or address)
4 = WRITE ERROR
5 = READ ERROR
6 = PORTNOTOPEN ERROR
10 = DATA UNINITIALIZED
11 = INSUFFICIENT BYTES RECEIVED
16 = BYTE COUNT ERROR
19 = TRANSACTION ID ERROR
81h = ILLEGAL FUNCTION
82h = ILLEGAL DATA ADDRESS
83h = ILLEGAL DATA VALUE
84h = FAILURE IN ASSOCIATED DEVICE
85h = ACKNOWLEDGE
86h = BUSY, REJECTED MESSAGE
87h = NAK-NEGATIVE ACKNOWLEDGMENT
12.3.8. WriteResult
Return a write result as an integer.
Use this function to check if a write was successful. The value is DATA_UNINITIALIZED until the result from the slave is available. See ReadResult for a list of possible values.
Property WriteResult As Integer
12.4. Automation data properties
The below properties are used to set or get values in the internal write/read arrays in Modbus Poll. The Index used is not a Modbus Address. The Index always counts from 0 no matter of the address used. The data properties are associated with a Modbus Poll document. (The window with data)
Example 1:
‘ doc is assumed created first. See Excel example.
doc.SRegisters(0) = 1
doc.SRegisters(1) = 10
doc.SRegisters(2) = 1234
‘ Write 3 registers stored in Modbus Poll internal array
‘ to Modbus address 100 (40101)
res = doc.WriteMultipleRegisters(1, 100, 3)
Example 2 with floating point values:
doc.Floats(0) = 1.3
doc.Floats(2) = 10.5
doc.Floats(4) = 1234.12
res = doc. WriteMultipleRegisters(1, 0, 6) «Write the 6 register stored in Modbus Poll
‘ 6 Registers are written as float is 32 bit wide.
12.4.1. Coils
Property Coils(Index As Integer) As Integer
Description
Sets a coil in the write array structure or return a coil from the read array.
Syntax
Coils(Index) [=newvalue]
12.4.2. SRegisters
Property SRegisters(Index As Integer) As Integer
Description
Sets a register in the write array structure or return a register from the read array.
Syntax
SRegisters (Index) [=newvalue]
12.4.3. URegisters
Property URegisters(Index As Integer) As Long
Description
Sets a register in the write array structure or return a register from the read array.
Syntax
Object. URegisters (Index) [=newvalue]
12.4.4. Ints_32
Property Ints_32(Index As Integer) As Double
Description
Sets a 32 Bit integer in the write array structure or return an integer from the read array.
Syntax
Ints_32 (Index) [=newvalue]
12.4.5. UInts_32
Property UInts_32(Index As Integer) As Double
Description
Sets a 32 Bit unsigned integer in the write array structure or return an unsigned integer from the read array.
Syntax
UInts_32 (Index) [=newvalue]
12.4.6. Ints_64
Property Ints_64(Index As Integer) As Double
Description
Sets a 64 Bit integer in the write array structure or return an integer from the read array.
Syntax
Ints_64 (Index) [=newvalue]
12.4.7. UInts_64
Property UInts_64(Index As Integer) As Double
Description
Sets a 64 Bit unsigned integer in the write array structure or return an unsigned integer from the read array.
Syntax
UInts_64 (Index) [=newvalue]
12.4.8. Floats
Property Floats(Index As Integer) As Single
Description
Sets a float in the write array structure or return a float from the read array.
Syntax
Floats* (Index) [=newvalue]
12.4.9. Doubles
Property Doubles(Index As Integer) As Double
Description
Sets a double in the write array structure or return a double from the read array.
Syntax
Doubles* (Index) [=newvalue]
12.5. Automation Write Functions
The write functions write the values stored in the array filled by the properties. The functions are associated with a Modbus Poll document. (The window with data)
12.5.1. WriteSingleCoil
Function WriteSingleCoil(SlaveID As Integer, Address As Long) As Integer
Return Value
True if write array is ready and the data are sent. False if array empty or error in parameters.
The controlling application is responsible for verifying the write operation by reading back the value written.
Parameters
SlaveID: The slave address 0 to 255
Address: The data address (Base 0)
Description
Writes the first coil stored in the write array.
Function 05 is used.
12.5.2. WriteSingleRegister
Function WriteSingleRegister (SlaveID As Integer, Address As Long) As Integer
Return Value
True if write array is ready and the data are sent. False if array empty or error in parameters.
The controlling application is responsible for verifying the write operation by reading back the value written.
Parameters
SlaveID: The slave address 0 to 255
Address: The data address (Base 0)
Description
Writes the first register stored in the write array.
Function 06 is used.
12.5.3. WriteMultipleCoils
Function WriteMultipleCoils(SlaveID As Integer, Address As Long, Quantity As Integer) As Integer
Return Value
True if write array is ready and the data are sent. False if array empty or error in parameters.
The controlling application is responsible for verifying the write operation by reading back the values written.
Parameters
SlaveID: The slave address 0 to 255
Address: The data address (Base 0)
Quantity The number of data. 1 to 1968
Description
Write the coils stored in the write array.
Function 15 is used.
12.5.4. WriteMultipleRegisters
Function WriteMultipleRegisters(SlaveID As Integer, Address As Long, Quantity As Integer) As Integer
Return Value
True if write array is ready and the data are sent. False if array empty or error in parameters.
The controlling application is responsible for verifying the write operation by reading back the value written.
Parameters
SlaveID: The slave address 0 to 255
Address: The data address (Base 0)
Quantity: The number of data. 1 to 123
Description
Write the registers stored in the write array.
Function 16 is used.
-
razorqhex
Modbus RTU поверх TCP (в режиме Slave)
Здравствуйте!
Помогите пожалуйста настроить сервер Lectus Modbus OPC в режиме Slave по протоколу Modbus RTU поверх TCP
Документацию и FAQ читал, но что-то совсем не могу
Использую Modbus Poll в качестве Master, ног он ругается ошибками типа Timeout Error, Read Error, Write Error иногда бывает ошибка Bytes Missing Error
Буду очень благодарен
-
admin
- Администратор
- Сообщения: 578
- Зарегистрирован: 05 сен 2010, 00:51
Re: Modbus RTU поверх TCP (в режиме Slave)
Сообщение
admin » 02 авг 2019, 21:00
1) В основных настройках Modbus узла установите тип подключения «Нет».
2) В дополнительных настройках Modbus узла установите тип Slave подключения «TCP подключения».
3) В настройках Slave подключения выберите «Modbus через TCP”.
4) Добавьте типизированные Modbus переменные в Modbus узел
-
razorqhex
Re: Modbus RTU поверх TCP (в режиме Slave)
Сообщение
razorqhex » 02 авг 2019, 21:56
Вроде всё хорошо, только теперь OPC не отвечает ответным пакетом и теперь в Modbus Poll ошибка только Timeout Error, что может значить, что попросту нету ответа с сервера. Это может быть с разными таймера опроса и ответа сервера и Modbus Poll
-
admin
- Администратор
- Сообщения: 578
- Зарегистрирован: 05 сен 2010, 00:51
Re: Modbus RTU поверх TCP (в режиме Slave)
Сообщение
admin » 03 авг 2019, 09:24
1) Опрашиваемые адреса определяются списком добавленных Modbus переменных. Для них задается начальный Modbus адрес.
2) Соединение рвётся со стороны опрашивающей программы. Ничего не могу сказать
-
razorqhex
Re: Modbus RTU поверх TCP (в режиме Slave)
Сообщение
razorqhex » 03 авг 2019, 09:35
admin писал(а): ↑03 авг 2019, 09:24
1) Опрашиваемые адреса определяются списком добавленных Modbus переменных. Для них задается начальный Modbus адрес.
В том-то и дело, что адрес выставлен 0 и Modbus Poll начинает опрос с нулевого регистра. И в итоге получается ошибка Timeout Error, но если начать опрос с первого регистра, то тут же всё в порядке и всё четко опрашивается.
Как использовать инструменты тестирования Modbus ModbusPoll и Modbus Slave
1. Введение
Modbus Poll: имитатор главного устройства Modbus, используемый для тестирования и отладки подчиненных устройств Modbus. Программа поддерживает ModbusRTU, ASCII, TCP / IP. Используется для помощи разработчикам в тестировании ведомых устройств Modbus или для тестирования и моделирования других протоколов Modbus. Он поддерживает несколько интерфейсов документов, то есть можно одновременно отслеживать несколько подчиненных устройств / полей данных. Каждое окно просто устанавливает идентификатор подчиненного устройства, функцию, адрес, размер и интервал опроса. Вы можете читать и писать регистры и катушки из любого окна. Если вы хотите изменить один регистр, просто дважды щелкните значение. Или вы можете изменить несколько значений регистров / катушек. Предоставляет несколько форматов данных, таких как числа с плавающей запятой, двойной точности, длинное целое число (можно обмениваться последовательностями байтов).
Modbus Slave: имитатор подчиненного устройства Modbus, который может имитировать 32 подчиненных устройства / поля адреса. Каждый интерфейс обеспечивает поддержку автоматизации OLE для отчетов EXCEL. В основном используется для имитации ведомых устройств Modbus, получения пакетов команд от главной станции и отправки пакетов данных обратно. Помогите разработчикам коммуникационного оборудования Modbus смоделировать и протестировать протокол связи Modbus для моделирования, тестирования и отладки коммуникационного оборудования Modbus. В 32 окнах можно моделировать до 32 подустройств Modbus. Пользовательский интерфейс такой же, как Modbus Poll, поддерживает функции 01, 02, 03, 04, 05, 06, 15, 16, 22 и 23, отслеживая последовательные данные.
Два, использование опроса Modbus
1), установка и регистрация:
После завершения установки вы увидите ярлык ModbusPoll на рабочем столе, дважды щелкните ярлык, чтобы открыть программное обеспечение, и интерфейс после открытия будет таким, как показано на рисунке ниже.
Нажмите «Соединение» -> «Подключиться», появится окно регистрации; откройте файл readme после распаковки сжатого пакета, скопируйте серийный номер ModbusPoll 5A5742575C5D10 и вставьте его в столбец регистрации окна регистрации, как показано на рисунке ниже. Щелкните ОК, чтобы завершить регистрацию.
Введение в главное окно программы Modbus Poll 4.3.4
где: Tx = 4 означает количество кадров данных, отправленных на главную станцию, 4 раза на рисунке; Error = 0 означает количество ошибок связи, 0 раз на рисунке; ID = 1 означает аналоговый Адрес субустройства Modbus, адрес на рисунке 1; F = 03 означает используемый код функции Modbus, а цифра — код функции 03; SR = 1000 мс означает цикл сканирования. Красная часть указывает на текущее состояние ошибки, а «Нет соединения» указывает на неподключенное состояние.
3), настройки параметров:
Нажмите [Чтение / запись определения… F8] в меню [Настройка], чтобы установить параметры, и появится диалоговое окно настройки параметров.
Среди них: A. Slave — это адрес подчиненного устройства Modbus (подчиненного устройства), к которому необходимо получить доступ, соответствующий значению идентификатора в главном окне (главном экране), по умолчанию — 1. B. Функция — это выбор кодов функций регистра. Всего существует четыре типа, и соответствующие отношения следующие:
Код Название Регистр Адрес ПЛК Битовая операция / Словарная операция Количество операций
01 Состояние бита чтения / записи 00001-09999 бит, один или несколько
02 Чтение (ввод) бита 10001–19999 бит, один или несколько
03 Чтение / запись (сохранение) слова 40001–49999 слов, одно или несколько слов
04 Чтение (ввод) слов 30001–39999 слов, написанных одно или несколько
05 Запись одиночной катушки 00001-09999 бит одиночной
06 Запись одного регистра временного хранения 40001–49999 слово, слово, одно слово
15 Запись нескольких катушек 00001-09999 бит, кратный
16 Запись нескольких регистров хранения 40001–49999 слов, несколько слов
C. Адрес — это начальный адрес регистра, по умолчанию он начинается с 0.
D. Длина — это количество последовательных регистров, значение по умолчанию — 10, что соответствует количеству каналов программы настройки.
E. Скорость сканирования — это цикл чтения данных в миллисекундах, по умолчанию — 1000 мс.
После настройки нажмите кнопку ОК, и в окне моделирования отобразится определенный список регистров.
4), настройки отображения:
Настройка режима отображения данных:
По умолчанию режим отображения данных регистра — Подписанный (двоичный код с шестнадцатеричным знаком), а диапазон данных составляет -32768 ~ 32767. Если пользователь хочет отображать другие числовые способы, он может выбрать и установить через меню 【Display】, как показано на рисунке ниже:
Настройка формата адреса: Modbus Slave использует адрес ПЛК по умолчанию, [PLC Addresses (Base 1)] в меню [Display] выбран по умолчанию, а начальный адрес регистра по умолчанию равен 1, это Последовательный порт Modbus и драйвер пересылки данных TCP точки и конфигурационное программное обеспечение одинаковы. Если вам нужно установить начальный адрес, чтобы он начинался с 0 во время теста, вы можете выбрать [Адреса протокола (база 0)]. Как правило, достаточно адреса ПЛК по умолчанию.
Используйте кнопку «Коммуникационный трафик» на панели инструментов для отображения текущих отправленных команд и полученных данных.
5), подключение к последовательному порту:
Нажмите [Подключить … F3] в меню [Подключение], чтобы подключиться к последовательному порту, как показано ниже:
Среди них: Port3, что означает используемый последовательный порт (COM3), выбор другого последовательного порта или TCP / IP для подключения в зависимости от реальной ситуации. Режим означает режим протокола Modbus, действительный при использовании последовательного порта; при использовании TCP / IP это автоматически режим TCP. Время ожидания ответа означает время ожидания чтения.Если ведомое устройство не возвращает данные в течение времени ожидания, считается, что связь не удалась. Задержка между опросами, минимальный интервал времени для каждого сканирования, по умолчанию — 10 мс. Удаленный сервер означает сетевые настройки терминального ведомого устройства в режиме TCP / IP. IP-адрес, представляет собой IP-адрес подчиненной станции в режиме TCP / IP. Порт указывает сетевой порт подчиненной станции в режиме TCP. Пользователь может установить параметры в соответствии со своими потребностями, по умолчанию: последовательный порт 1, скорость передачи 9600, бит данных 8 бит, без бита четности, 1 стоповый бит. После подтверждения настроек нажмите кнопку ОК. Если он подключен и читается правильно, в главном окне будет отображаться информация о регистре чтения.
6), изменение значения регистра:
Дважды щелкните мышью по адресу регистра в главном окне, появится диалоговое окно изменения, как показано на рисунке ниже:
Введите значение в поле ввода «Значение» для подтверждения. Диапазон значений: -32768——32767.
Среди них: Slave — это адрес подчиненного устройства Modbus, к которому необходимо получить доступ, соответствующий значению идентификатора на главном экране, значение по умолчанию — 1. Адрес — это адрес текущего реестра. На рисунке показаны операции с регистром 40001. Использовать функцию — это используемый код функции.Вы можете выбрать код функции 06 или 16. для записи.
7), проверьте фрейм данных связи:
Щелкните [Связь …] в меню [Отображение] или нажмите кнопку [101] на панели инструментов, чтобы вызвать диалоговое окно с информацией о мониторинге фрейма данных для отправки и получения данных через последовательный порт «CommunicationTraffic» для Просматривайте и анализируйте отправленные и полученные фреймы данных. Как показано ниже:
Среди них: первые 6 битов — это порядковый номер кадра данных. Rx представляет полученный кадр данных. Tx представляет отправленный фрейм данных.
8), отключите:
Нажмите [Отключить F4], чтобы отключиться и завершить тест. В это время в главном окне отображается красный значок «Нет подключения», указывающий на отключенное состояние.
Три, использование ведомого устройства Modbus
1), установка и регистрация:
Установите программное обеспечение, после завершения установки дважды щелкните, чтобы запустить ярлык ModbusSlave.
Метод регистрации: нажмите «Соединение» -> «Подключиться», появится окно регистрации; откройте файл readme после распаковки сжатого пакета, скопируйте серийный номер ModbusPoll, вставьте его в столбец регистрации в окне регистрации, нажмите «ОК», Трещина полная. Установка и взлом ModbusSlave аналогичны ModbusPoll, поэтому я не буду повторять его здесь.
2), главное окно:
Главное окно программы показано ниже:
В настоящее время он находится в неподключенном состоянии «Нет соединения». Если вы проверяете только «Регистр удержания выхода 04», вы можете щелкнуть, чтобы перейти к шагу 3. и подключиться напрямую.
3), настройки параметров:
Нажмите «Определение ведомого … F2» в меню «Настройка», чтобы установить параметры, появится следующее диалоговое окно.
Среди них: A. Slave — это адрес ведомого устройства Modbus, соответствующий значению ID на главном экране, по умолчанию — 1.
B. Функция — это выбор кодов функций регистра, всего существует четыре типа, и соответствующие отношения следующие:
Код Название на китайском языке Зарегистрировать адрес ПЛК Битовая операция / Словесная операция Количество операций
01 Чтение статуса катушки 00001-09999 Битовая операция, одиночная или множественная
02 Чтение состояния дискретного входа 10001-19999 Битовая операция Один или несколько
03 Чтение регистра временного хранения 40001-49999 Операция Word Один или несколько
04 Чтение регистра ввода 30001-39999 Операция в виде слова Один или несколько
05 Запись одиночной катушки 00001-09999 Одинарная битовая операция
06 Запись одного регистра временного хранения 40001-49999 Одинарная операция Word
15 Запись нескольких катушек 00001-09999 Несколько битовых операций
16 Запись в несколько регистров хранения 40001–49999 Операция в несколько слов
C. Адрес — это начальный адрес регистра. По умолчанию начинается с 1.
D. Длина — это количество последовательных регистров. По умолчанию — 10.
Нажмите кнопку ОК, в окне моделирования отобразится определенный список регистров:
Среди них: ID представляет адрес устройства моделируемого субустройства Modbus; F представляет код функции.
Щелкните соответствующий регистр, чтобы изменить значение или статус соответствующего регистра. Например, значение регистра 2 изменяется на 9, а значение регистра 9 изменяется на 100.
4), настройки отображения:
Настройка режима отображения данных:
По умолчанию режим отображения данных регистра — Подписанный (шестнадцатеричный беззнаковый двоичный), а диапазон данных составляет -32768——32767. Если пользователь хочет отображать другие числовые способы, он может выбрать и установить через меню «Отображение», как показано на следующем рисунке:
Настройка формата адреса:
Modbus Slave по умолчанию использует адрес ПЛК. «Адреса ПЛК (база 1)» в меню «Дисплей» — это состояние, выбранное по умолчанию. Начальный адрес регистра по умолчанию — 1, что отличается от конфигурации. Программный последовательный порт Modbus и драйвер пересылки данных TCP одинаковы. Если вам нужно установить начальный адрес на 0 во время теста, вы можете выбрать «Адреса протокола (базовый 0)». Как правило, достаточно адреса ПЛК по умолчанию.
5), соединение:
Нажмите «Подключить … F3» в меню «Подключение», чтобы подключиться. Появится диалоговое окно подключения:
Где: Port2 означает используемый последовательный порт (COM2), выберите другой последовательный порт или TCP / IP для подключения в соответствии с реальной ситуацией.
Mode, что означает режим протокола Modbus, действителен при использовании последовательного порта; автоматически в режиме TCP при использовании TCP / IP
Управление потоком, что означает управление потоком, действительное в режиме последовательного порта;
Игнорировать идентификатор устройства, что означает, что недопустимые номера групп игнорируются в режиме TCP.
Пользователи могут установить параметры последовательного порта в соответствии со своими потребностями. Значение по умолчанию: последовательный порт 1, скорость передачи 9600 бод, 8 бит данных, без бита четности и 1 стоповый бит. После подтверждения настроек нажмите кнопку «ОК». В это время красный «Нет соединения» в главном окне указывает, что информация в неподключенном состоянии исчезает, указывая, что ведомое устройство находится в нормальном состоянии соединения.
6), изменение значения регистра:
Дважды щелкните мышью по адресу регистра в главном окне, появится диалоговое окно изменения, как показано на рисунке ниже:
Введите значение в поле ввода для подтверждения. Диапазон значений: -32768——32767.
Среди них: после того, как установлен флажок «Автоинкремент», значение соответствующего регистра может увеличиваться на 1 каждую 1 секунду.
7), проверьте фрейм данных связи:
Нажмите «Связь …» в меню «Дисплей», чтобы вызвать диалоговое окно с информацией о мониторинге фреймов данных отправки и получения последовательного порта для просмотра и анализа отправленных и полученных фреймов данных. Как показано ниже:
Среди них: первые 6 битов — это порядковый номер кадра данных.
Rx: представляет получаемый фрейм данных.
Tx: означает отправку кадра данных.
8), отключите:
Нажмите «Отключить F4», чтобы отключить и завершить тест. В это время в главном окне отображается красный значок «Нет подключения», указывающий на отключенное состояние.
Четыре, программа моделирования ведущего / ведомого устройства Modbus
1) Установите инструмент виртуального последовательного порта vspd. Добавьте два порта COM2 и COM3 через инструмент.
2) Затем откройте установленное программное обеспечение Modbuspoll и Modbus Slave и нажмите «F8», чтобы настроить соответствующую конфигурацию главного и подчиненного терминалов, как показано на рисунке:
В приведенной выше конфигурации идентификатор устройства 10 ведомых счетчиков равен 1, но считываются только данные первых 6 счетчиков, которые можно настроить в соответствии с вашей ситуацией.
2. Затем нажмите «F3» для подключения, обратите внимание на изменение порта интерфейса подключения, главная и подчиненная машины соответственно выбирают наши виртуальные порты com2 и com3, потому что я использую только RTU Mode, поэтому другие параметры, такие как скорость передачи 9600, бит 8, четность 1, без эквивалента и т. Д., Могут оставаться неизменными, а затем нажмите OK для подключения. Во второй строке неподключенного окна появится подсказка.
Когда начинается связь, на стороне хоста отображается: TX = 232, Err = 0, ID = 1, F = 03, SR = 1000 мс. Это означает, что нужно отправить 232 команды, время ошибки, ID ведомого, номер функции, интервал опроса.
Используйте кнопку «Коммуникационный трафик» на панели инструментов для отображения текущих отправленных команд и полученных данных.