2016-10-20 58 views
0

我正在使用Jamod從Modbus設備檢索值。它適用於正常值。當我嘗試從寄存器中檢索負值時,它會生成一些隨機值。如何使用JAMOD檢索負值

代碼:

private float getData (String address, int count) { 
float sum = 0.0f; 

request = new ReadMultipleRegistersRequest(Integer.parseInt(address), count); 
response = new ReadMultipleRegistersResponse(); 
request.setUnitID(1); 
response.setUnitID(1); 
request.setHeadless(); 

try { 

    response = (ReadMultipleRegistersResponse) execute(connection, holdingRequest); 

    for (int i=0; i<registerCount; i++) { 
      sum = sum + response.getRegisterValue(i); 
    } 
    System.out.println("Sum: " + sum); 
} catch (Exception e) { 
     e.printStackTrace(); 
} 
return sum; 
} 

private ModbusResponse execute(SerialConnection connection, ModbusRequest request) {   
    try { 
     transaction = new ModbusSerialTransaction(connection); 
     transaction.setRequest(request); 
     transaction.execute(); 
     return transaction.getResponse(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 

請幫助。在此先感謝

回答

0

在modbus設備寄存器大小主要是16位,所以當你使用jamod從寄存器獲取值時,應該注意將其存儲到適當的數據類型中。

例如。在存儲寄存器0x1000中值爲-12456,當我們閱讀它說

int value = readRegister(0x1000); 

it returns me value = 53080 

所以int是32位,通過改變INT(32位)短的(16位)的數據類型返回原始負值

short value = (short) readRegister(0x1000); 
it returns value = -12456 

希望它能解決您的問題!