meta data for this page
This is an old revision of the document!
LamaPLC: Arduino code collection
Modbus
Convert 2 registers to float
call: [float] = modbus_2regs_2_float([1.register], [2.register])
float modbus_2regs_2_float(uint16_t a, uint16_t b) { uint32_t combined = ((uint32_t)a << 16) | b; float f; memcpy(&f, &combined, sizeof f); return f; }
Convert float 2 registers
def: int16_t regs[2];
call: modbus_set_float([float], regs);
back: register1: regs[1], register2: [regs[2]
void modbus_set_float(float f, uint16_t *dest) { uint32_t i = 0; memcpy(&i, &f, sizeof(uint32_t)); dest[0] = (uint16_t)i; dest[1] = (uint16_t)(i >> 16); }
Float to / from one register
Note: The maximum value of the int16 type is 32767, so in this format only the value range 0 .. 327.67 can be stored with 2 decimal places!
// float 2 reg holdingRegs[REG_HUM] = (int16_t)(Humidity * 100); // back one reg to float float Humidity = holdingRegs[REG_HUM] / 100.0;
Modbus messages
bool getResultMsg(uint8_t result) { String tmpstr2; switch (result) { case node.ku8MBSuccess: return true; break; case node.ku8MBIllegalFunction: tmpstr2 = "Illegal Function"; break; case node.ku8MBIllegalDataAddress: tmpstr2 = "Illegal Data Address"; break; case node.ku8MBIllegalDataValue: tmpstr2 = "Illegal Data Value"; break; case node.ku8MBSlaveDeviceFailure: tmpstr2 = "Slave Device Failure"; break; case node.ku8MBInvalidSlaveID: tmpstr2 = "Invalid Slave ID"; break; case node.ku8MBInvalidFunction: tmpstr2 = "Invalid Function"; break; case node.ku8MBResponseTimedOut: tmpstr2 = "Response Timed Out"; break; case node.ku8MBInvalidCRC: tmpstr2 = "Invalid CRC"; break; default: tmpstr2 = "Unknown error: " + String(result); break; } Serial.println(tmpstr2); return false; }