Modbus Read Coils Returns Wrong Values
DodaTech
Updated 2026-06-26
1 min read
In this tutorial, you'll learn about Modbus Read Coils Returns Wrong Values. We cover key concepts, practical examples, and best practices.
The Problem
Modbus master reads coils but receives incorrect on/off states.
Quick Fix
Wrong
uint8_t coil_status[8];
modbus_read_bits(ctx, 0, 8, coil_status); # Reads 8 coils
Coil values are unexpectedly all 0 or all 1.
Right
#include <modbus/modbus.h>
int read_coils_example(modbus_t *ctx) {
uint8_t coil_bits[32];
int start_addr = 0;
int num_coils = 16;
// Read 16 coils starting at address 0 (function code 0x01)
int rc = modbus_read_bits(ctx, start_addr, num_coils, coil_bits);
if (rc == -1) {
printf('Read coils failed: %s\n', modbus_strerror(errno));
return -1;
}
// coil_bits is an array of uint8_t values (0 or 1)
for (int i = 0; i < num_coils; i++) {
printf('Coil %d: %s\n', start_addr + i,
coil_bits[i] ? 'ON' : 'OFF');
}
return 0;
}
// Expected: Coil 0: ON, Coil 1: OFF, Coil 2: ON...
Correct coil states displayed for all 16 coils.
Prevention
Coils are 1-bit values addressed by offset (0-based). Function code: 0x01 (Read Coils). Response packs 8 coils per byte (LSB = first coil). modbus_read_bits() unpacks them into uint8_t array. Coil addresses may start at 1 in documentation — the libmodbus wrapper uses 0-based addressing.
DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.
FAQ
← Previous
Modbus Master Cannot Communicate with Slave
Next →
Modbus RTU Master No Response from Slave
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro