2011-07-18 21 views
1

我正嘗試使用Linux中的ttyS0通信端口COM0與嵌入式系統進行通信。我在Windows上嘗試了另一種軟件,它似乎能夠與端口正確通信。我嘗試過使用這段代碼,但是在第一行時出現錯誤。使用Device :: SerialPorts在Linux下編程串行端口

use strict; 
use warnings; 
use Device::SerialPort; 


die "Cannot Open Serial Port\n" unless my $PortObj = new Device::SerialPort ("/dev/ttyS0"); 

還有另一種更容易的方式與串口進行通信。

+0

你得到了什麼錯誤? –

回答

1

它看起來像你需要的代碼看起來像這樣:

use strict; 
use warnings; 
use Device::SerialPort; 

die "Cannot Open Serial Port\n" 
    unless my $PortObj = Device::SerialPort->new(
     $^O eq "MSWin32" ? "com1" : "/dev/ttyS0" 
    ); 

注意,我不知道是否com1是你的代碼對應的串口,但我認爲你需要類似的東西。如果你有更多的平臺,你需要處理散列可能是更好的選擇:

use strict; 
use warnings; 
use Device::SerialPort; 

my %port_name = (
    MSWin32 => "com1", 
    linux => "/dev/ttyS0", 
); 

die "I don't know what serial port to use on $^O\n" 
    unless exists $port_name{$^O};  

die "Cannot Open Serial Port\n" 
    unless my $PortObj = Device::SerialPort->new($port_name{$^O}); 
+0

哦,沒關係,那有效。主要問題是另一個應用程序佔用了串口,因此無法連接。 – Anonymous