Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello ,
i am using Qt for making some interface of Modbus Master , while reading variables from the device , all positve variables are true , but the negative variables are worong .
for example : when i send -1 from the Device , i recieve a big number , like 6582.
how can i receive the correct negative numbers?

What I have tried:

if (reply->error() == QModbusDevice::NoError) {
       const QModbusDataUnit unit = reply->result();
          // here is  variables reading
           const QString entry_hs_in_temp = QString::number(unit.value(0));
           const QString entry_hs_out_temp = QString::number(unit.value(1));
Posted
Updated 4-Sep-18 23:52pm

1 solution

Data are binary and such is transferred on the bus. How to interpret these data and what they represent depends on specifications. For signed values for example it is common to use the Two's complement - Wikipedia[^].

The QModbusDataUnit::value() function returns an quint16. That is a 16 bit unsigned binary value containing the content of the requested register. How to interpret that content depends on the device.

If that uses two's complement for signed 16 bit values, it will send 0xFFFF for -1. Converting that to a string using QString::number() results in 65535. To get it as negative number you have to cast the value to qint16 first so that the function knows that you have a signed value:
C++
const QString entry_hs_in_temp = QString::number(static_cast<qint16>(unit.value(0)));

That should work in most cases. But if the device is using a different method to represent signed values, you have to use the corresponding reverse procedure to convert the received binary data to a basic signed integer type.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900