我正在嘗試創建一個小應用程序來收集從連接到COM10的外部傳感器收到的數據。我已經成功地創建了一個小型C#控制檯對象和應用程序,它使用for循環打開端口並將數據流傳輸到文件一段固定的時間。如何在C#中使用串口端口對象的dataReceived事件?
我想將此應用程序轉換爲使用dataReceived事件進行流式傳輸。看完Top 5 SerialPort Tips後,我仍然無法工作,也不知道自己錯過了什麼。我重寫了控制檯應用程序,以便所有代碼都在Main中並粘貼在下面。有人可以幫助啓發我,爲什麼事件處理程序port_OnReceiveDatazz沒有被調用,即使我知道有數據被硬件發送到端口?
感謝
阿齊姆
PS:感謝@Gabe,@Jason Down,並且@abatishchev的所有建議。我很難過,似乎無法讓事件處理程序正常工作。也許它與設備有關。我只能在一個線程中讀取端口並將數據直接傳輸到文件中。
代碼
namespace serialPortCollection
{ class Program
{
static void Main(string[] args)
{
const int bufSize = 2048;
Byte[] buf = new Byte[bufSize]; //To store the received data.
SerialPort sp = new SerialPort("COM10", 115200);
sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler
sp.Open();
sp.WriteLine("$"); //Command to start Data Stream
// Wait for data or user input to continue.
Console.ReadLine();
sp.WriteLine("!"); //Stop Data Stream Command
sp.Close();
}
// My Event Handler Method
private static void port_OnReceiveDatazz(object sender,
SerialDataReceivedEventArgs e)
{
SerialPort spL = (SerialPort) sender;
const int bufSize = 12;
Byte[] buf = new Byte[bufSize];
Console.WriteLine("DATA RECEIVED!");
Console.WriteLine(spL.Read(buf, 0, bufSize));
}
}
}
什麼不工作? – 2009-01-21 18:53:14
@Jon B:即使正在接收數據,事件處理程序也不會被調用。 – Azim 2009-01-21 19:05:38