Short answer: a Modbus RTU request is the device address, a function code, the data, and a 2-byte CRC16 with the low byte first. To read registers you send function code 3 with a start address and a register count.
Why this matters for Android
Solar inverters, energy meters and many data loggers speak Modbus. An Android app often talks to them through a Bluetooth, Wi-Fi or serial bridge that passes Modbus frames through, so you build and parse frames yourself.
Read holding registers (function 3)
Example request: read 2 registers starting at address 0 from device 1.
01 03 00 00 00 02 C4 0B
| | |---| |---| |---|
| | start count CRC (low, high)
| function 3
device address 1
The reply has the same address and function, a byte count, the register bytes (each register is 16 bits, high byte first), then a CRC.
CRC16 in Kotlin
Modbus CRC uses polynomial 0xA001 (reflected), initial value 0xFFFF.
fun crc16(data: ByteArray): Int {
var crc = 0xFFFF
for (b in data) {
crc = crc xor (b.toInt() and 0xFF)
repeat(8) {
crc = if (crc and 1 != 0) (crc shr 1) xor 0xA001 else crc shr 1
}
}
return crc and 0xFFFF
}
fun readRegisters(id: Int, start: Int, count: Int): ByteArray {
val body = byteArrayOf(
id.toByte(), 0x03,
(start shr 8).toByte(), start.toByte(),
(count shr 8).toByte(), count.toByte()
)
val crc = crc16(body)
return body + byteArrayOf(crc.toByte(), (crc shr 8).toByte()) // low byte first
}
Calling readRegisters(1, 0, 2) gives the bytes in the example above, ending in C4 0B.
Parse the response
fun parse(resp: ByteArray): List<Int> {
val body = resp.copyOfRange(0, resp.size - 2)
val rx = (resp[resp.size - 1].toInt() and 0xFF shl 8) or (resp[resp.size - 2].toInt() and 0xFF)
require(crc16(body) == rx) { "CRC mismatch" }
val n = resp[2].toInt() and 0xFF
return (0 until n / 2).map { i ->
((resp[3 + i * 2].toInt() and 0xFF) shl 8) or (resp[4 + i * 2].toInt() and 0xFF)
}
}
Tips
- Check your device manual for register addresses, scaling and signed values; many devices use a factor such as 0.1.
- Some manuals count addresses from 1, so you may need to subtract 1.
- Validate the CRC and the length before trusting data, and handle exception responses (function code with the high bit set).
- If the link is BLE, send frames in chunks as described in our chunking guide.
FAQ
Why is the CRC low byte first?
Modbus RTU transmits the CRC with the low byte before the high byte, unlike the register data.
Is Modbus RTU the same as Modbus TCP?
No. TCP has no CRC and uses a different header, but the function codes and data are the same.