2012-07-24 125 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輸出。