Current Location: Home> Latest Articles> How to Implement Modbus TCP Data Monitoring and Acquisition Using PHP

How to Implement Modbus TCP Data Monitoring and Acquisition Using PHP

M66 2025-07-13

How to Implement Modbus TCP Data Monitoring and Acquisition Using PHP

With the rapid development of industrial automation, the Modbus protocol has become widely used in the industrial control field. This article will demonstrate how to use PHP to implement Modbus TCP data monitoring and acquisition, helping developers quickly get started with code examples.

Introduction to Modbus TCP

The Modbus communication protocol is a serial communication protocol, and Modbus TCP is a version that converts it to TCP/IP, enabling remote communication. As a connection-oriented, message-based protocol, Modbus TCP follows a request/response pattern, allowing the master station to send data requests to the slave station and receive responses.

Installing the PHP Modbus Library

To implement Modbus TCP communication, a third-party PHP library can be used to simplify development. Here, we choose the phpmodbus library, which can be easily installed using Composer. Create a composer.json file in the root directory of your project and add the following content:

{
  "require": {
    "mamuesp/phpmodbus": "dev-master"
  }
}

Then run the `composer install` command in the terminal to install the library.

Modbus TCP Read Operation Example

Here is an example of using the phpmodbus library to implement a Modbus TCP read operation:

require_once 'vendor/autoload.php';
$ip = '192.168.1.1'; // Modbus slave IP address
$port = 502; // Modbus slave port number
$unitId = 1; // Slave ID
use PhpmodbusPhpmodbus;
$modbus = new Phpmodbus();
$modbus->connectTcp($ip, $port);
$data = $modbus->readMultipleRegisters($unitId, 1, 1);
if($data != false) {
  echo "Read successful!";
  echo "Register value: " . implode(",", $data);
} else {
  echo "Read failed!";
}
$modbus->disconnect();

Modbus TCP Write Operation Example

Here is an example of using the phpmodbus library to implement a Modbus TCP write operation:

require_once 'vendor/autoload.php';
$ip = '192.168.1.1'; // Modbus slave IP address
$port = 502; // Modbus slave port number
$unitId = 1; // Slave ID
use PhpmodbusPhpmodbus;
$modbus = new Phpmodbus();
$modbus->connectTcp($ip, $port);
$modbus->writeSingleRegister($unitId, 1, 100);
$modbus->disconnect();

Conclusion

This article explained how to use PHP to implement Modbus TCP data monitoring and acquisition through the phpmodbus library. The detailed code examples help readers better understand how to perform Modbus TCP read and write operations. We hope this guide proves useful in your development efforts and helps in the practical application of industrial automation systems.