C# - 从串口缓冲区读取

时间:2009-09-04 12:51:15

标签: c# serial-port buffering

我正在尝试从RS-232端口读取数据。有没有人有一个如何从端口/缓冲区获取数据的例子,并确保我拥有所有数据,因为它可以是多行数据。

我只是按如下方式阅读?

string Rxstring = port.ReadLine();
Console.WriteLine(Rxstring);

2 个答案:

答案 0 :(得分:4)

试试这个:

using System.IO.Ports;
...

private SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);

Console.WriteLine(port.ReadExisting());

详情请见Coad's Code

答案 1 :(得分:3)

问:如何从端口/缓冲区获取日期,或从连接的设备输入数据。并确保您拥有所有数据。

答:我已经广泛使用.net串口类驱动程序,我的任务是创建可靠,健壮的代码。这意味着被测连接的设备必须运行并且不会在很长一段时间内失败。串口可以AND确实丢失数据!别忘了。

//from top of the head;

using System.Port.IO;
using System.Port;

private class mywindowsForm: Form
{
      StringBuilder sbReceived = new StringBuilder();
      string Received = string.Empty;
      int byteCOUNT = 0;

      System.Windows.Timers.Timer serialTimer;

      //Default constructor 
      myWindowsForm()
      {
         //assume that you clicked and dragged serial port in
          serialPort1 = new SerialPort();//create new serial port instance 
          serialPort1.Baud = 9600;
          serialPort1.DataReceived+=<Tab><Enter>
          //serial port timer 
          serialTimer = new System.Windows.Timers.Timer(500);//set to 500ms time delay
          serialTimer.Elapsed+=<TAB><ENTER>
      }

      void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
      {
           //serial port has detected input data
           //however, we only want to get serial data so,
           if(e.EventType !=SerialData.Chars) return;
           //good design practice dictates that we have an event handler that we invoke
            this.BeginInvoke(new eventhandler(AddReceive));//beginInvoke is designed to deal with asynchronous processes like serial port data. 
      }

      private void AddReceive(object s, EventArg e)
      {
            byteCOUNT=serialPort1.BytesToRead;//count the number of bytes in RX buffer
            if(byteCOUNT > 0) 
             {
                 string ST = serialPort1.ReadTo("\n");//lets get one line at a time 
                 sbReceived.Append(ST);//add whatever has been RX'd to our container. 
                 serialPort1.Interval =100;
                 serialPort1.Start();//to be sure we have all data, check to see for stragglers.
              }
      }

       void serialTimer(object Sender, TimerElapsedEventArgs e)
       {
            serialTimer.Stop();
            this.BeginInvoke(new EventHandler(ReadData));
        }

       void ReadData(object Sender, EventArgs e)
       {
            //parse output for required data and output to terminal display (build one using rich text box)
             Received = sbReceived.ToString();
             //and if we have ANY MORE incoming data left over in serial buffer
              if(Received.Length > 0)
              {
                  //your data 
              }
       }
}

这应该足以让你入门。这是多年在c#中创建自定义终端仿真器的结果。还有其他事情可以做,特别是如果您需要大量的i / o数据来设置与设备的握手。你必须让设备以设备满意的速度处理。在需要传输较大数据的情况下,考虑设置一个简单的数据包传递协议和命令信号量构造 - 或者使用控制器/设备设计用于的定义的协议。