我读了很多的问题,在这里了解如何读取使用.NET SerialPort类串行端口的数据,但没有建议报告的方法已被证明对我来说完全有效。
下面是我使用现在的代码:
SerialPort port = new SerialPort("COM1");
port.DataReceived += new SerialDataReceivedEventHandler(MyDataReceivedHandler);
而事件处理程序:
void MyDataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
int count = port.BytesToRead;
byte[] ByteArray = new byte[count];
port.Read(ByteArray, 0, count);
}
但我仍然有时会丢失一些数据。 我试过的事件处理程序,但没有运气读取数据不同的方式。
随着.NET 4.5带来了新的可能性做一些异步任务,如与ReadAsync ,这似乎是对的SerialPort流可用的方法,我很好奇,看看会有什么推荐的方法来处理这些情况。
你可以尝试这样的事情,例如我想你是想利用的是port.ReadExisting()方法
using System;
using System.IO.Ports;
class SerialPortProgram
{
// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);
[STAThread]
static void Main(string[] args)
{
// Instatiate this
SerialPortProgram();
}
private static void SerialPortProgram()
{
Console.WriteLine("Incoming Data:");
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
// Enter an application loop to keep this thread alive
Console.ReadLine();
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
或者是你要根据你试图做做到这一点,你可以试试这个
public class MySerialReader : IDisposable
{
private SerialPort serialPort;
private Queue<byte> recievedData = new Queue<byte>();
public MySerialReader()
{
serialPort = new SerialPort();
serialPort.Open();
serialPort.DataReceived += serialPort_DataReceived;
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
data.ToList().ForEach(b => recievedData.Enqueue(b));
processData();
}
void processData()
{
// Determine if we have a "packet" in the queue
if (recievedData.Count > 50)
{
var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
}
}
public void Dispose()
{
if (serialPort != null)
{
serialPort.Dispose();
}
}
我用类似的代码@MethodMan,但我必须保持串口进行发送数据的跟踪和寻找终止字符知道串口已完成发送数据时。
private string buffer { get; set; }
private SerialPort _port { get; set; }
public Port()
{
_port = new SerialPort();
_port.DataReceived += new SerialDataReceivedEventHandler(dataReceived);
buffer = string.Empty;
}
private void dataReceived(object sender, SerialDataReceivedEventArgs e)
{
buffer += _port.ReadExisting();
//test for termination character in buffer
if (buffer.Contains("\r\n"))
{
//run code on data received from serial port
}
}