我如何从modbus读取负变量? [英] How I can read negative variables from modbus ?

查看:1802
本文介绍了我如何从modbus读取负变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

i使用Qt制作Modbus Master的一些界面,同时从设备读取变量,所有positve变量都是真的,但负面变量是worong。

例如:当我从设备发送-1时,我收到一个很大的数字,比如6582.

我怎样才能收到正确的负数?



我尝试过:



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));

推荐答案

数据是二进制的,并且在总线上传输。如何解释这些数据及其代表的内容取决于规格。例如,对于签名值,通常使用两个补语 - 维基百科 [ ^ ]。



QModbusDataUnit :: value()函数返回 quint16 。这是一个16位无符号二进制值,包含所请求寄存器的内容。如何解释该内容取决于设备。



如果对签名的16位值使用二进制补码,它将发送0xFFFF为-1。使用 QString :: number()将其转换为字符串会产生65535.要将其作为负数,您必须将值转换为 qint16 首先让函数知道你有一个有符号的值:

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:
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.


这篇关于我如何从modbus读取负变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆