我目前正在使用ESP8266作为主程序,可以从EEM-MA370中读取数据,EEM-MA370已经配置了网关。
假设我想读取U12的值。
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的值?
#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);
}
我想知道,我如何读取浮点值。
非常感谢
发布于 2022-06-27 01:26:43
如果Modbus设备用浮点数据发送响应,则需要从寄存器读取2个字(即4个字节)数据,返回数据将是遵循IEEE-754浮点格式的4字节数据。
Modbus的另一个特点是它使用大端,而您的Arduino (和几乎所有现代计算机体系结构)都使用小Endian,因此也需要将其从大端转换为小Endian。
下面是一个关于如何获取Modbus发送的浮点值的示例(在C++中)。
// 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);
}
这将将值0x43
、0x6B
、0x58
和0x0E
转换为浮点数,并打印如下:
235.34
https://stackoverflow.com/questions/72746008
复制相似问题