2014-03-30 113 views
0

我對C#編程頗爲陌生,對串行端口知之甚少。我正在關注微軟提供的this method,以不斷讀取進入多個串行端口的信息。總的來說,我的應用程序是從多個COM端口提取數據,並對結果數據執行計算任務。在Main中使用從多個串行端口讀取數據()

1)我想使用多個串行端口。不幸的是,我目前沒有足夠的USB-RS232適配器來測試多個端口。我不確定創建第二個DataReceivedHandler方法是否是正確的方法。這是我目前有:

// Receive data on COM Port A 
private static void DataReceivedHandlerA(object sender, SerialDataReceivedEventArgs e) 
{ 
    SerialPort sp = (SerialPort)sender; 
    string inDataA = sp.ReadExisting(); 
} 

// Receive data on COM Port B 
private static void DataReceivedHandlerB(object sender, SerialDataReceivedEventArgs e) 
{ 
    SerialPort spB = (SerialPort)sender; 
    string inDataB = spB.ReadExisting(); 
} 

2)在Main()循環的其他地方DataReceivedHandler方法中使用接收到的數據。由於該方法是私有的,因此我無法在Main()循環中使用inDataA。每當我公開這種方法時,它似乎都失敗了。我想能夠返回字符串inDataB。這是可能的,還是有另一種更好的方式來做到這一點。

回答

0

任何你不能將這兩個變量作爲全局變量的原因,所以它們可用於所有功能?

Static String inDataA, inDataB; 

// Receive data on COM Port A 
private static void DataReceivedHandlerA(object sender, SerialDataReceivedEventArgs e) 
{ 
    SerialPort sp = (SerialPort)sender; 
    inDataA = sp.ReadExisting(); 
    Console.Write(inDataA); 
} 

// Receive data on COM Port B 
private static void DataReceivedHandlerB(object sender, SerialDataReceivedEventArgs e) 
{ 
    SerialPort spB = (SerialPort)sender; 
    inDataB = spB.ReadExisting(); 
    Console.Write(inDataB); 
} 


//use those variables here as well in some other functions 
+0

我試過了,但在DataReceivedHandlerA方法中,接收到錯誤「inDataA中的名稱'在當前上下文中不存在」inDataA旁邊。我相信它不喜歡該方法是靜態的,如果我使它非靜態,該方法會失敗。 – baconcow

+0

在新的更新版本中使它們像上面那樣是靜態的 – SirH

+0

這樣可以在調試期間停止所有錯誤。但是,在Main()循環中運行以下內容不會導致任何內容寫入控制檯:'code' Console.Write(inDataA); 'code' – baconcow

0

當您從main調用Console.Write(inDataxx)時,inDataxx爲空或空,因爲事件處理程序很可能尚未觸發。由於您尚未創建通知事件或輪詢循環,因此此打印命令僅執行一次。

在您提供的示例的主循環中有三個部分。 COM端口設置,控制檯設置和COM拆卸。這些都是按順序執行的,沒有邏輯繼續打印公共(現在是靜態變量)。此示例旨在直接從事件處理程序中打印。爲了讓您的設計正常工作,您需要修改主循環以輪詢或使用事件來打印數據。嘗試一下這樣的投票:

int keyIn = 0; 
do 
{ 
    // Check if any key pressed, read it into while-controlling variable 
    if (Console.KeyAvailable) 
     keyIn = Console.Read(); 
    // Poll our channel A data 
    if (!string.IsNullOrEmpty(inDataA)) 
    { 
     Console.WriteLine(String.Format("Received data {0} on channel A", inDataA)); 
     inDataA = ""; 
    } 
    // Poll our channel B data 
    if (!string.IsNullOrEmpty(inDataB)) 
    { 
     Console.WriteLine(String.Format("Received data {0} on channel B", inDataB)); 
     inDataB = ""; 
    } 
    // Stop looping when keyIn is no longer 0 
}while (keyIn == 0); 

請注意,如果你打算使用這個是生產代碼不使用輪詢。輪詢非常低效。

+0

我有一個更大的應用程序,我正在使用它。我希望能夠在我的應用程序的其他部分(計算等)中使用inDataA中的數據。即使它是一個流,我已經開發了緩衝和解析它的方法。有沒有有效的方法來做到這一點?我會嘗試你的方法。 – baconcow

+0

這是所有的控制檯基礎還是有用戶界面?如果您在別處使用數據,請考慮構建一個描述此數據的對象。這可以包含您的所有方法,並可通過對其進行有效的引用隨時用於任何計算。例如MyDataA.parse()DoMaths(); https://gist.github.com/corytodd/9876275#file-serial-polling –

+0

這將是一個控制檯(現在),因爲我沒有形式編程能力。如何開發一個可以使用inDataA變量的類對象?對不起,這些可能是基本問題,對於C#來說很新。 – baconcow