How do I read values spanning multiple registers over the Modbus protocol?

I am using the Industrial Communication Toolbox to communicate with external hardware. I want to read a 32-bit floating point number, but this value is spread across two (not necessarily adjacent) 16-bit registers. How do I achieve this?

 채택된 답변

There are two possible approaches for reading values which span multiple registers. These examples both specifically read 32-bit floats from 16-bit registers, but this is just for illustration and the process works with any register/value types.
Approach 1:
If the two 16-bit registers are on consecutive addresses, then the standard "read" function will combine their values automatically when reading a 32-bit value from the lower register's address.
For example, this will read a 32-bit floating point number by combining the 16-bit registers at addresses 2000 and 2001:
floatValue = read(m,'holdingregs',2000,1,'single');
More information on the "read" function can be found here:
https://www.mathworks.com/help/releases/R2023a/icomm/ug/modbus.read.html
Approach 2:
If Approach 1 does not work (for example, if the registers are not at two consecutive addresses), then each register can be read independently with "read" and then combined into a 32-bit value with the "typecast" function.
For example, this will read a 32-bit floating point number by combining the 16-bit registers at addresses 2000 and 3000:
reg1 = read(modbus, 2000, 1, 'uint16');
reg2 = read(modbus, 3000, 1, 'uint16');
floatValue = typecast([reg1 reg2], 'single');
More information about the "typecast" function can be found here:
https://www.mathworks.com/help/releases/R2023a/matlab/ref/typecast.html

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Modbus Communication에 대해 자세히 알아보기

제품

릴리스

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by