Abstract ❝
This article builds upon the previous one by adding the functionality to read and write int and float data, as well as byte order reading and writing functions (ABCD, BADC, CDAB, DCBA)【Project address at the end of the article】.
Introduction
Today, we will discuss how to add new features to the previous article “C# Implementing Modbus TCP Communication” case, without further ado, the main addition is the byte order reading functionality for int and float data.What is byte order? It refers to the order of bytes, represented literally as ABCD.Each letter represents a byte (A = most significant byte, D = least significant byte), for example: big-endian(0x12345678 stored as 12 34 56 78), little-endian(0x12345678 stored as 78 56 34 12).
The sorting methods are as follows:
ABCD [A, B, C, D] Big-endian
DCBA [D, C, B, A] Little-endian
BADC [B, A, D, C]
CDAB [C, D, A, B]
The basic Modbus TCP reading of coils and registers generally uses bool and ushort types, occupying only one register. If you want to return int or float data, it requires occupying 2 registers, which means reading and writing two registers, and then converting according to different byte orders and data types.
Operating Environment
Operating System:Windows 11
Programming Software:Visual Studio 2022
.Net Version:.Net Framework 4.8.0
1. Preview
(1) Interface and Running Effect The initial byte order is ABCD. Data reading can be done by clicking the read int or float button, requiring the setting of the starting address and length for reading. Data writing is done based on the starting address and the content to be sent.For example, input: 12 Click the write button (int or float) to achieve single write. Input[12,34,0,0,0] click the button to write multiple data.
2. Code
(1) MainForm Code Added buttons to read and write int and float, used to trigger the read and write functionality. Added byte order change functionality.
#region Write Button Event
private void btn_WriteInt_Click(object sender, EventArgs e) {
try {
int[] register = ParseArray<int>(rtbx_SendData.Text);
if (register != null && register.Length == 1) {
modbusTcp.WriteInt(modbusTcp.DataModel.ReadStartAddress, register[0]);
MessageUpdate($