Home >Backend Development >PHP Tutorial >How to implement Modbus TCP data reading and writing through PHP
How to implement Modbus TCP data reading and writing through PHP
Modbus is a commonly used communication protocol used to communicate between devices in the industrial field. Modbus TCP is a variant of the Modbus protocol that uses the TCP/IP protocol to communicate on the network. In this article, we will introduce how to read and write Modbus TCP data through PHP.
require_once('modbus/ModbusMaster.php'); $modbus = new ModbusMaster("192.168.1.1", "TCP");
$startAddress = 0; $length = 10; $data = $modbus->readMultipleRegisters(1, $startAddress, $length); for ($i = 0; $i < $length; $i++) { echo "寄存器 " . ($startAddress + $i) . " 的值: " . $data[$i] . " "; }
$address = 1; $value = 123; $modbus->writeSingleRegister($address, $value); echo "写入成功 ";
if (!$modbus->writeSingleRegister($address, $value)) { echo "写入失败:" . $modbus->getError() . " "; }
To sum up, we can use PHP to read and write Modbus TCP data by using the phpmodbus extension. By establishing the ModbusMaster object and choosing the appropriate method, we can easily perform Modbus communication. Paying attention to error handling can improve the stability and reliability of the program.
Although this article only provides the basics of implementing Modbus TCP in PHP, it provides you with a good starting point so that you can further learn and develop more complex Modbus applications. I hope you can continue to explore and learn in practice and give full play to the potential of Modbus!
The above is the detailed content of How to implement Modbus TCP data reading and writing through PHP. For more information, please follow other related articles on the PHP Chinese website!