Short answer: the function code tells the device what to do. The common ones are 3 (read holding registers), 4 (read input registers), 6 (write one register) and 16 (write many registers). If something is wrong, the device replies with the same function code plus 0x80 and a one-byte exception code.
Common function codes
| Code | Name | Use |
|---|---|---|
| 01 | Read coils | Read on/off outputs |
| 02 | Read discrete inputs | Read on/off inputs |
| 03 | Read holding registers | Read settings and values (most common) |
| 04 | Read input registers | Read measured, read-only values |
| 05 | Write single coil | Switch one output |
| 06 | Write single register | Change one setting |
| 15 (0x0F) | Write multiple coils | Switch many outputs |
| 16 (0x10) | Write multiple registers | Change many settings |
Many inverters and meters put live measurements in input registers (function 4) and settings in holding registers (function 3). Your manual says which.
Exception responses
If a request fails, the reply is: address, function code with the high bit set (for example 0x83 for a failed function 3), an exception code, then the CRC. It is always 5 bytes.
| Code | Meaning | Usual cause |
|---|---|---|
| 01 | Illegal function | Device does not support that function |
| 02 | Illegal data address | Register address does not exist, or an off-by-one |
| 03 | Illegal data value | Bad count or a value outside the allowed range |
| 04 | Server (slave) device failure | Device could not complete the request |
Detecting an exception in Kotlin
sealed interface ModbusResult {
data class Ok(val registers: List<Int>) : ModbusResult
data class Error(val function: Int, val code: Int) : ModbusResult
}
fun parseResponse(resp: ByteArray): ModbusResult {
val function = resp[1].toInt() and 0xFF
if (function and 0x80 != 0) {
return ModbusResult.Error(function and 0x7F, resp[2].toInt() and 0xFF)
}
val n = resp[2].toInt() and 0xFF
val regs = (0 until n / 2).map { i ->
((resp[3 + i * 2].toInt() and 0xFF) shl 8) or (resp[4 + i * 2].toInt() and 0xFF)
}
return ModbusResult.Ok(regs)
}
Check the CRC first, as shown in our Modbus RTU basics post, then check the function byte.
Tips
- Exception 02 is often an off-by-one: some manuals number registers from 1, the protocol address starts at 0.
- Do not write to a holding register unless you know what it does; some settings affect the hardware.
FAQ
What is the difference between holding and input registers?
Holding registers can be read and written. Input registers are read-only, usually measurements.
What does 0x83 mean?
It is a failed function 3 request (0x03 plus 0x80); the next byte is the exception code.
Register maps differ by manufacturer. Always confirm addresses, scaling and word order in your device manual.