2013-04-13 56 views
0

我有一個項目已經用PHP編寫。我需要從串口讀取數據。我希望保持以與項目其餘部分相同的語言從串口讀取數據的能力。串口讀取PHP奇怪

我發現一個很多人似乎遇到問題的課程。 php_serial.class.php基於這個例子,我寫它作爲一個測試。使用RFID讀卡器作爲串行輸入。

#!/usr/bin/php 
<?php 

// Include the class to read the serial line. 
include ("php_serial.class.php"); 

// Let's start the class 
$serial = new phpSerial; 

$serial->deviceSet("/dev/ttyAMA0"); 
$serial->confBaudRate(9600); 
$serial->confParity("none"); 
$serial->confCharacterLength(8); 
$serial->confStopBits(1); 
// We can change the baud rate, parity, length, stop bits, flow control 
#$serial->confFlowControl("none"); 

// Check if we can open the serial line. Otherwise die. 
if(!$serial->deviceOpen()) die("unable to open device"); 

stream_set_timeout($serial->_dHandle, 10); 

$rfid_key = FALSE; 

// Start the loop to keep checking the 
while(!$rfid_key) 
{ 
    $read = $serial->readPort(); 

    // Array to store eachvalue of the RFID tag 
    $ascii_read = array(); 

    for($i = 0; $i < strlen($read); $i++) 
    { 
     $ascii_read[] = ord($read[$i]); 
     if(count($ascii_read) == 14 && $ascii_read[0] == 2 && $ascii_read[13] == 3) 
     { 
      $rfid_key = implode("", $ascii_read); 
      break; 
     } 
    } 

    // If the key is empty then sleep for 1 second. 
    if(!$rfid_key) 
    { 
     sleep(1); 
    } 
} 

print_r($rfid_key); 
print "\n\n"; 

如果我運行該腳本,它將等待輸入,如果我在天線上閃爍RFID標籤,它會失敗。

然後我決定看看它是不是php,所以我寫了一個python腳本。

import serial 
serialport = serial.Serial("/dev/ttyAMA0", 9600, timeout=0.5) 
response = serialport.readlines(None) 
print response 

如果我把天線上的標籤,並運行該腳本,然後拉掉標籤,我得到它在時間跨度讀取標籤的情況下的任何數字。告訴我,RFID閱讀器與RaspberryPi配合使用。

現在這裏是非常奇怪的部分。如果我在執行python代碼後返回並執行php代碼,那麼它可以工作。這導致我相信它與在Python中完成的串行端口實例化有關,該代碼在執行後會繼續執行。然後剝離python代碼來實例化串口並退出,並按照預期的那樣執行php代碼。

所以,我的問題是。跆拳道是python這樣做的代碼是不是?我不是串行總線的專家,我很困惑。

回答

2

好的,我找到了解決方案。問題不在於php腳本,而是爲/ dev/ttyAMA010設置的選項經過大量研究後,我發現運行命令/bin/stty -F /dev/ttyAMA010向我顯示了串行線路的當前狀態。在新啓動後運行,將其作爲輸出。

speed 9600 baud; line = 0; 
-brkint -imaxbel 

然後運行python腳本查看差異是什麼。

speed 9600 baud; line = 0; 
min = 0; time = 0; 
-brkint -icrnl -imaxbel 
-opost 
-isig -icanon -iexten -echo -echoe -echok -echoctl -echoke 

然後我係統地包含每個配置選項並刷新我的頁面直到它工作。最後我發現我需要2個選項才能讓php串行腳本工作。

stty -F /dev/ttyAMA0 -isig 
stty -F /dev/ttyAMA0 -icanon