2015-07-22 74 views
2

我在使用串行數據接收事件處理程序時遇到問題。一半的時間數據顯示在文本框中,一半時間不顯示。它應該是跨線程操作的問題。顯示來自串行端口的接收數據

這是我的Arduino代碼:

int Loop = 1; 

void setup() { 
    Serial.begin(9600); 
} 

void loop() { 
    Serial.println(Loop); 
    Loop++; 

    delay(1000); 
} 

這裏是我的C#代碼:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.IO.Ports; 

namespace arduino_test 
{ 
public partial class Form1 : Form 
{ 
    SerialPort sPort; 

    public Form1() 
    { 
     InitializeComponent(); 

     initialiseArduino(); 
    } 

    public void initialiseArduino() 
    { 
     sPort = new SerialPort(); 
     sPort.BaudRate = 9600; 
     sPort.PortName = "COM16"; 
     sPort.Open(); 

     //sPort.DataReceived += new SerialDataReceivedEventHandler(sPort_DataReceived); 
    } 

    void sPort_DataReceived(object sender, SerialDataReceivedEventArgs e) 
    { 
     SerialPort sp = (SerialPort)sender; 
     string data = sp.ReadExisting(); 
     displayMessage(data); 
    } 

    public void displayMessage(string data) 
    { 
     if (InvokeRequired) 
     { 
      this.Invoke(new Action<string>(displayMessage), new object[] { data }); 
      return; 
     } 
     textBox1.Text = data; 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     while (true) 
     { 
      string data = sPort.ReadLine(); 
      textBox1.Text = data; 
     } 
    } 
} 
} 

當我使用接收到的事件處理程序的串行數據,它給了我這個問題,甚至調用後。

所以我試着通過點擊一個按鈕來運行一個相同的線程操作,它工作得很好。

任何人都可以告訴我我做錯了什麼?

回答

3

問題的明顯區別和原因是你做這件事的兩種不同方式。您在您的DataReceived事件處理程序中使用ReadExisting(),但在Click事件處理程序中使用ReadLine()

ReadExisting()只是不做你希望的事情,你只能得到1或2個字符。無論是「現有」,從DataReceived事件迅速發生並且現代臺式計算機速度非常快以來,從來沒有多少。然後事件再次發生,你讀了另外1或2個字符。你的文本框只顯示最後的內容。

改爲使用ReadLine()。

0

你可能想用

public void displayMessage(string data) 
{ 
    if (InvokeRequired) 
    { 
     this.Invoke(new Action<string>(displayMessage), new object[] { data }); 
     return; 
    } 
    **textBox1.Text = textBox1.Text + data;** 
} 

更新displayMessage方法這樣,你永遠也不會清除textBox1的內容,你就會有所有值。

請注意(取決於您的數據)您的傳入數據可能包含控制字符或其他無法在文本框控件中很好地顯示的內容。

+0

好的!謝謝你的提示 :-) –

相關問題