2016-09-06 128 views
0

跟進Serial Port Communication solution我實現了下面的設計。我的代碼使用com8Serial Port Utility Application是在同一臺機器內的com9傾聽溝通,然後再送回來(手動我鍵入消息,並按下一個按鈕)串口通信拋出TimeoutException

在我主我這樣做:

MyClass MyObj = new MyClass(); 
var message = MyObj.SendThenRecieveDataViaSerialPort("Test"); 

然後在我的課我有這樣的:

private static SerialPort MainSerialPort { get; set; } = new SerialPort(); 
private static string _ReceivedMessage; 
private Thread readThread = new Thread(() => ReadSerialPort(ref _ReceivedMessage)); 

public string SendThenRecieveDataViaSerialPort(string _Message) 
{ 
    MainSerialPort = new SerialPort("com8", 9600); 
    MainSerialPort.ReadTimeout = 5000; 
    MainSerialPort.WriteTimeout = 5000; 
    MainSerialPort.Open(); 
    readThread.Start(); // 1 

    try 
    { // 2 
     MainSerialPort.WriteLine(_Message); // 3 
     readThread.Join(); // 6 - Console pops and waits 
    } 
    catch (TimeoutException ex) 
    { 
     Console.WriteLine("Exception in SendThenreceive"); 
    } 

    return _ReceivedMessage; 
} 

private static void ReadSerialPort(ref string _message) 
{ 
    try 
    { // 4 
     _message= MainSerialPort.ReadLine(); // 5 
    } 
    catch (TimeoutException ex) 
    { 
     // 7 - when time outs 
    } 
} 

然而,在步驟7說法拋出一個錯誤:

{ 「操作超時。」}

的InnerException:空

你能告訴我在哪裏,我錯了?請和謝謝。

+0

我們不是已經經歷過這個了嗎?您*必須*設置握手屬性,它不是可選的。如果使用Handshake.None,則必須將DtrEnable和RtsEnable屬性設置爲true。您使用的實用程序僅用於與設備對話,而不是您的程序。本地環回將PC發送回PC的數據需要一根空調制解調器電纜,用於將com8連接到com9。你的線程被破壞,它只能讀取一次。不要使用線程。 –

+0

嗨Hans \ o /再一次:)。我仍然在努力:(我有一個從com8到com9的硬件電纜!我不能重現上次的問題,所以我使用這個多線程。我正在嘗試'MyPort.Handshake = SetPortHandshake(MyPort.Handshake );'作爲[MSDN](https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readline(v = vs.110).aspx)now !! –

+0

Mr @HansPassant原來是轉儲錯誤,我發送'back'而不是'back \ n'。上面的代碼一旦我用''line'鍵發送'back \ n',我就添加了這些代碼:'' MainSerialPort.RtsEnable = true;'爲了保持安全,看起來我需要'Read()'而不是'ReadLine()',然後 –

回答

1

ReadLine會等待,直到它看到SerialPort.NewLine字符串。如果這沒有在SerialPort.ReadTimeout內出現,則引發TimeoutException。所以不要錯過發送NewLine!

這是一個沒有NewLine的替代版本。

byte[] data = new byte[1024]; 
int bytesRead = MainSerialPort.Read(data, 0, data.Length); 
_message = Encoding.ASCII.GetString(data, 0, bytesRead); 
+0

嗨,傑夫,我有5秒鐘的時間輸入'back',然後按下一個按鈕,我非常確定不會錯過發送NewLine。 –

+0

嘗試閱讀而不是ReadLine。 – JeffRSon

+0

閱讀不接受0參數 –