Home > Article > Backend Development > How to write Modbus TCP communication code using PHP
How to use PHP to write Modbus TCP communication code
Modbus is a communication protocol used in the field of industrial automation and is widely used for data transmission between PLC (programmable logic controller) and other automation equipment . Modbus TCP is a variant of the Modbus protocol that uses the TCP/IP protocol stack as the transport layer to allow remote communication over the network.
This article will introduce how to use PHP to write Modbus TCP communication code and provide some code examples.
<?php // 创建Modbus TCP连接 $modbus = modbus_new_tcp("192.168.1.1", 502); if(!$modbus) { die("无法创建Modbus TCP连接"); } ?>
In the above code, we use the modbus_new_tcp function to create a Modbus TCP connection, and the parameters include the IP address and port number of the remote device. If the connection creation fails, we use the die function to output an error message and terminate the program.
<?php // 读取Modbus寄存器 $address = 0; // 起始寄存器的地址 $count = 10; // 要读取的寄存器数量 $data = modbus_read_registers($modbus, $address, $count); if(!$data) { die("无法读取Modbus寄存器"); } ?>
In the above code, we use the modbus_read_registers function to read the specified number of registers starting from the specified address. If the read fails, we use the die function to output an error message and terminate the program.
<?php // 写入Modbus寄存器 $address = 0; // 要写入寄存器的地址 $value = 100; // 要写入的值 $result = modbus_write_register($modbus, $address, $value); if(!$result) { die("无法写入Modbus寄存器"); } ?>
In the above code, we use the modbus_write_register function to write the specified value to the specified register. If the write fails, we use the die function to output an error message and terminate the program.
<?php // 关闭Modbus TCP连接 modbus_close($modbus); ?>
In the above code, we use the modbus_close function to close the Modbus TCP connection created earlier.
Summary
This article introduces how to use PHP to write Modbus TCP communication code. First, we need to install the PHP extension that supports Modbus TCP. We then create a Modbus TCP connection and perform data transfer by reading and writing registers. Finally, we close the Modbus TCP connection to release resources. I hope these code examples can help you implement Modbus TCP communication in PHP and find application in the field of industrial automation.
The above is the detailed content of How to write Modbus TCP communication code using PHP. For more information, please follow other related articles on the PHP Chinese website!