What Is Modbus Function Code: Simple Explanation and Example
Modbus function code is a number that tells a Modbus device what action to perform, like reading or writing data. It acts like a command in a conversation between devices in a SCADA system to control or monitor equipment.How It Works
Think of a Modbus function code as a simple instruction in a conversation between two devices. One device asks the other to do something specific, like "read the temperature" or "turn on a motor." The function code is the number that represents this instruction.
When a Modbus master device sends a request, it includes a function code to tell the slave device what to do. The slave then performs the action and sends back the result. This system is like ordering food at a restaurant: the function code is the menu item number you say to the waiter, who then brings you the dish.
Example
This example shows how to use a Modbus function code to read holding registers from a device using Python and the pymodbus library.
from pymodbus.client.sync import ModbusTcpClient client = ModbusTcpClient('192.168.1.10', port=502) client.connect() # Function code 3: Read Holding Registers result = client.read_holding_registers(address=0, count=2, unit=1) if not result.isError(): print('Register values:', result.registers) else: print('Error reading registers') client.close()
When to Use
Use Modbus function codes whenever you need to communicate with industrial devices like sensors, meters, or controllers in a SCADA system. They let you read data (like temperature or pressure), write settings (like turning a valve on or off), or check device status.
For example, a factory might use function codes to monitor machine health or control motors remotely. This makes automation and monitoring simple and reliable.
Key Points
- Function codes are numeric commands in Modbus communication.
- Each code corresponds to a specific action like reading or writing data.
- They enable clear, simple instructions between master and slave devices.
- Common codes include 1 (read coils), 3 (read holding registers), and 6 (write single register).