我想實現的datarecieved基於事件的處理程序,我想我能夠從端口接收數據,但其執行情況的困難。我曾經嘗試都的ReadLine和ReadExisting ..可以請你對我的代碼評論..謝謝,DataReceived事件檢索處理程序的串行C#
private void Form1_Load(object sender, EventArgs e)
{
// graphing stuff
portname = "COM1";
parity = Parity.None;
BaudRate = 115200;
stopbits = StopBits.One;
databits = 8;
port = new System.IO.Ports.SerialPort(portname);
port.Parity = parity;
port.BaudRate = BaudRate;
port.StopBits = stopbits;
port.DataBits = databits;
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
port.Open();
count = 0;
}
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
line = port.ReadLine();
count++;
this.BeginInvoke(new LineReceivedEvent(LineReceived),line);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private delegate void LineReceivedEvent(string text);
private void LineReceived(string text)
{
if (zedGraphControl1.GraphPane.CurveList.Count <= 0)
return;
LineItem curve = zedGraphControl1.GraphPane.CurveList[0] as LineItem;
if (curve == null)
return;
IPointListEdit list = curve.Points as IPointListEdit;
double value = double.Parse(text);
list.Add(count, value);
// graphing stuff
}
// graphing stuff
}
保持波特率低。您一次只能調用一個數字,這可能導致UI線程停止繪製。您的用戶每秒只能看到約20次更新,然後纔會變爲模糊狀態。緩衝區來解決問題。 – 2011-03-21 17:47:30