Modbus Write Coil
DodaTech
1 min read
In this tutorial, you'll learn about Modbus Write Single Coil Not Working. We cover key concepts, practical examples, and best practices.
The Problem
Modbus master writes to a coil but the slave does not change state.
Quick Fix
Wrong
modbus_write_bit(ctx, 0, 1); # Write coil 0 to ON
Coil stays OFF despite successful write response.
Right
#include <modbus/modbus.h>
int write_coil(modbus_t *ctx, int addr, int state) {
// state: 0 = OFF (0x0000), 1 = ON (0xFF00)
int rc = modbus_write_bit(ctx, addr, state);
if (rc == -1) {
printf('Write coil %d failed: %s\n',
addr, modbus_strerror(errno));
return -1;
}
// Verify by reading back
uint8_t readback;
modbus_read_bits(ctx, addr, 1, &readback);
printf('Coil %d = %s (after write %d)\n',
addr, readback ? 'ON' : 'OFF', state);
return 0;
}
// Write multiple coils at once
int write_multiple_coils(modbus_t *ctx, int addr,
const uint8_t *states, int count) {
return modbus_write_bits(ctx, addr, count, states);
}
Coil 0 = ON (after write 1). Read-back confirms the value.
Prevention
Modbus protocol: coil ON = 0xFF00, coil OFF = 0x0000. Passing 1/0 is handled by libmodbus. Function code: 0x05 (Write Single Coil), 0x0F (Write Multiple Coils). Coils are non-volatile (persist after power cycle) if the slave implements them that way. Verify RS-485 wiring if writes fail.
DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro