首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >读取浮动值Modbus/TCP ESP8266

读取浮动值Modbus/TCP ESP8266
EN

Stack Overflow用户
提问于 2022-06-24 15:03:01
回答 1查看 697关注 0票数 0

我目前正在使用ESP8266作为主程序,可以从EEM-MA370中读取数据,EEM-MA370已经配置了网关。

假设我想读取U12的值。

代码语言:javascript
运行
复制
ModbusIP mb; //ModbusIP object
IPAddress remote(10, 30 ,21 ,75);  // Address of Modbus Slave device
const int REG = 32768; //Dec value of U12

void loop(void){
  if (mb.isConnected(remote)) {   // Check if connection to Modbus Slave is established
        mb.readHreg(remote, REG, &res);  // Initiate Read Coil from Modbus Slave
        } else {
        mb.connect(remote);   
        Serial.print("Trying");
                // Try to connect if no connection
    }

当我运行代码时,它会显示值为60664等。我知道Modbus只支持16位,所以我找到了一个转换为32位的代码。但我不明白它是怎么工作的。我如何手动知道var1和var2的值?

代码语言:javascript
运行
复制
#include <stdint.h>
#include <inttypes.h>
#include <stdio.h>

int main()
{
    uint16_t var1 = 255; // 0000 0000 1111 1111
    uint16_t var2 = 255; // 0000 0000 1111 1111

    uint32_t var3 = (var1 << 16) +  var2;

    printf("%#"PRIx32"\n", var3);
}

我想知道,我如何读取浮点值。

非常感谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-27 01:26:43

如果Modbus设备用浮点数据发送响应,则需要从寄存器读取2个字(即4个字节)数据,返回数据将是遵循IEEE-754浮点格式的4字节数据。

Modbus的另一个特点是它使用大端,而您的Arduino (和几乎所有现代计算机体系结构)都使用小Endian,因此也需要将其从大端转换为小Endian。

下面是一个关于如何获取Modbus发送的浮点值的示例(在C++中)。

代码语言:javascript
运行
复制
// This is a valid modbus response return 4-bytes of data in floating format that representing a voltage value
uint8_t response[] = {0x01, 0x04, 0x04, 0x43, 0x6B, 0x58, 0x0E, 0x25, 0xD8};

float getFloat() {

    float fv = 0.0;

    ((uint8_t*)&fv)[3]= response[3];
    ((uint8_t*)&fv)[2]= response[4];
    ((uint8_t*)&fv)[1]= response[5];
    ((uint8_t*)&fv)[0]= response[6];

    return fv;
}

void setup() {
    Serial.begin(115200);
    
    float voltage = getFloat();
    Serial.println(voltage);
}

这将将值0x430x6B0x580x0E转换为浮点数,并打印如下:

代码语言:javascript
运行
复制
235.34
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72746008

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档