您可以使用DataReceived 事件。每次新数据到达您的端口时都会触发它。您需要像这样注册它:
SerialPort port = new SerialPort(/*your specification*/);
port.DataReceived += Port_DataReceived;
在事件处理程序中,您将读出传入的数据
private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = sender as SerialPort;
if (port != null)
{
var incoming_message = port.ReadExisting();
}
}
现在你只需要打开端口,它就会自动监听。笔记!传入的数据将到达与主线程不同的线程。因此,如果您想使用表单控件进行显示,您需要使用BeginInvoke
如果您的数据在末尾标有\n,您可以尝试使用ReadLine 方法:
var incoming_message = port.ReadLine();
或者你可以试试ReadTo
var incoming_message = port.ReadTo("\n");
编辑:
如果是这么长的时间,那么你应该分批阅读。您也可以尝试在 while 循环中处理它。
private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = sender as SerialPort;
string message = "";
if (port != null)
{
while(port.BytesToRead > 0)
{
message += port.ReadExisting();
System.Threading.Thread.Sleep(500); // give the device time to send data
}
}
}
编辑 2:
如果要存储数据,请在事件处理程序之外声明 List<string>,并在完全读取字符串时添加该字符串。
List<string> dataStorage = new List<string>();
private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = sender as SerialPort;
string message = "";
if (port != null)
{
while(port.BytesToRead > 0)
{
message += port.ReadExisting();
System.Threading.Thread.Sleep(500); // give the device time to send data
}
// add now the entire read string to the list
dataStorage(message);
}
}
由于事件处理程序不知道您是否发送了A 或B,只需将所有收到的消息收集在一个列表中。您知道您发送命令的顺序,因此稍后您可以取出相应的消息并使用Split 获取数组中的 400 个条目:
string [] A_array_data = dataStorage[0].Split(" ");