2012-07-24 128 views
1

我试着用PHP读取Linux平台上的串口。
但我不能读取任何数据。当我尝试阅读.net时,这次我可以阅读。php从linux上的串口读取数据

我使用“php_serial.class.php”类进行串口操作。您可以通过以下链接阅读这个类:
here

我的代码是这样的:

<?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(”(大小 “.strlen($读)”)“); “总是返回零。什么原因导致我无法从串口读取数据?

+0

DId您尝试运行“cat/dev/ttyS1”例如作为PHP用户(可能名为Apache或www-data)?此用户是否具有对/ dev/ttyS1的读取权限? – 2012-07-24 09:41:53

+0

是的,用户可以读取/ dev/ttyS1。我使用com2端口,我可以打开端口并将数据发送到端口。但我不能从端口读取数据。另外我尝试“cat/dev/ttyS1”,但不能读取任何内容。 – cukcuk 2012-07-24 10:31:21

+0

您是否检查过您的PHP安装配置为报告错误和警告?该班级使用警告来报告问题。尝试添加trigger_error(“logging is working”,E_USER_WARNING);在脚本的顶部 - 如果你没有在输出中看到它,那么稍后有可能会失败,并且你会压制错误消息。 – symcbean 2012-07-24 10:32:34

回答

3

我相信你现在已经发布了这个,但这里是我的2c值得。

您读取串口两次。一次检查是否有数据,然后再有数据。根据我的经验,一旦读取缓冲区并再次读取它将产生一个空的结果。

只是不读它第二次

0

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

0

你好,这是真的老了,但我目前(现在也是),这方面的工作,我得到了字节回正确(删除ORD()来读取BTW作为字符串)。

它是未来通过为零的原因是因为无限循环的,即使你送东西正在返回什么(所以它似乎)尽管使用你的代码我好不容易才得到的东西作为字符串返回。

我实际输入数据的设备侧到控制台...这再回到我,我进入设备是什么,看来你需要到餐桌的过程中,为了做到这一点100%自己的方式。它的工作原因有时是因为如果你输入一个返回几行的命令,它很可能会得到其中的一些。

使用的屏幕连接到该设备,然后只需输入随机的东西,并按下回车键...你会看到它出现在你的PHP输出。