Skip to content

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.
#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

### Why does the coil value use 0xFF00 instead of 0x0001?

Modbus protocol specifies 0xFF00 = ON, 0x0000 = OFF. Any other value is illegal. libmodbus converts 1/0 to the correct wire format.

What is the response to a write coil?

The slave echoes the request (address + value) in the response. The master can verify the echo matches.

Can I write multiple coils at once?

Yes. Use modbus_write_bits() (function code 0x0F). Up to 2000 coils per request.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro