类型铸造操作

问题描述 投票:0回答:2

我正在使用NodeMCU和能量计。电能表是Modbus RTU设备,以32位显示参数。使用下面的代码,我可以从slave读取数据,但需要从32位浮动和显示类型转换

当我在ModScan软件中将值更改为无符号十进制时,值显示正确。但我需要以32位浮点显示值。

#include <ModbusMaster232.h>
#include <SoftwareSerial.h>
float  data[100];
ModbusMaster232 node(1);

// Define one address for reading
#define address 1
// Define the number of bits to read
#define bitQty 70

void setup()
{
  Serial.begin(9600);
  // Initialize Modbus communication baud rate
  node.begin(9600);
}

void loop()
{
  int result = node.readHoldingRegisters(address, bitQty);
  data[0] = (float)node.getResponseBuffer(0);
  data[1] = (float)node.getResponseBuffer(1);
  data[2] = (float)node.getResponseBuffer(2);
  data[3] = (float)node.getResponseBuffer(3);
  data[4] = (float)node.getResponseBuffer(4);
  data[5] = (float)node.getResponseBuffer(5);
  for (int i = 0; i < 100; i++)
  {
    //data[i] = node.getResponseBuffer(i);
    Serial.println(data[i]);
  }
  Serial.println("............");
}

我想显示带有类型转换的Modbus中显示的读数。

从药膏输出的实际Modbus设备:

Actual Modbus device output from salve

从能量计读取数据时输出Arduino:

Arduino output while read data from energy meter

arduino type-conversion modbus nodemcu
2个回答
0
投票

您正在将一个16位字转换为浮点数。检查从站文档以查找它们如何将32位浮点映射到两个Modbus寄存器。基本上你需要知道最不重要的单词在哪里(第一或第二个寄存器),将它们加载到内存中(必要时移位)并转换为浮点数。


0
投票

我正在寻找并尝试解决完全相同的问题(结果相同)。这可能有所帮助:

function read() {

client.readHoldingRegisters(0000, 12)
    .then(function(d) {
        var floatA = d.buffer.readFloatBE(0); 
    console.log("Total kWh: ", floatA); })
    .catch(function(e) {
        console.log(e.message); })
    .then(close);
}

这是NodeJS和javascript版本,有效,Arduino没有。完整的例子可以在这里找到,它适用于Raspberry Pi https://github.com/yaacov/node-modbus-serial/blob/master/examples/buffer.js

© www.soinside.com 2019 - 2024. All rights reserved.