php从linux上的串行端口读取数据


php read data from serial port on linux

我尝试使用PHP读取Linux平台上的串行端口
但是我看不懂任何数据。当我尝试使用.net阅读时,这次我可以阅读了。

我使用"php_serial.class.php"类进行串行端口操作。您可以从以下链接阅读此类:
此处

我的代码是这样的:

<?php  
 include "php_serial.class.php";  
// Let's start the class
$serial = new phpSerial;
// First we must specify the device. This works on both linux and windows (if
// your linux serial device is /dev/ttyS0 for COM1, etc)
$serial->deviceSet("/dev/ttyS1");
// We can change the baud rate, parity, length, stop bits, flow control
$serial->confBaudRate(19200);
$serial->confParity("none");
$serial->confCharacterLength(8);
$serial->confStopBits(1);
$serial->confFlowControl("none");
// Then we need to open it
$serial->deviceOpen();  
// read from serial port
$read = $serial->readPort();
//Determine if a variable is set and is not NULL
if(isset($read)){
   while(1){
       $read = $serial->readPort();
       print_r(" (size ".strlen($read). " ) ");
       for($i = 0; $i < strlen($read); $i++)
       {
          echo ord($read[$i])." ";
       }
       print_r("'n");
       sleep(1);
  }// end while
}// end if  

// If you want to change the configuration, the device must be closed
$serial->deviceClose();
// We can change the baud rate
$serial->confBaudRate(19200);  
?>  

行"print_r("(size".strlen($read).");总是返回零。我无法从串行端口读取数据的原因是什么?

我相信你现在已经解决了这个问题,但这是我的2c价值。

您读取了两次串行端口。一次检查是否有数据,然后在有数据时再次检查。根据我的经验,读取一次会清除缓冲区,因此再次读取会产生空结果。

只是不要第二次读取

也有同样的问题。我需要使用stty -isig -icanon设置两个选项,一旦设置好,脚本读取就没有问题。

你好,这真的很旧了,但我目前(仍然)在做这件事,我已经正确地取回了字节(remove ord()读取为字符串btw)。

它为零的原因是因为无限循环,即使你发送了一些东西,也不会返回任何东西(看起来是这样)尽管使用你的代码,我还是设法将东西作为字符串返回。

实际上,我在设备端将数据输入了控制台。。。然后,它将我输入设备的内容返回给我,看来你需要分叉流程才能100%按照你的方式完成。它有时起作用的原因是,如果您输入一个返回几行的命令,它很可能会得到其中的一些行。

使用屏幕连接到设备,然后只需键入随机内容并点击回车。。。您将看到它出现在php输出中。