C# - readin from serial port buffer

岁酱吖の 提交于 2020-01-01 06:34:09

问题


I am trying to read data from an RS-232 port. Does anyone have an example of how I get the data from the port/buffer and make sure that I have all the data as it can be multiline data.

Do I simply read it as follows ?

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

回答1:


Try this:

using System.IO.Ports;
...

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

Console.WriteLine(port.ReadExisting());

Details can be found at Coad's Code.




回答2:


Q: how to get the date from the port/buffer, or input data from your connected device. AND make sure that you have all the data.

A: i have worked extensively with .net serial port class drivers where i was tasked to create reliable, robust code. this means that a connected device under test has to run and NOT fail over a LONG period of time. Serial port can AND does lose data! don't forget that.

//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 
              }
       }
}

this should be plenty to get you started. this is result of years of creating customized terminal emulators in c#. there are other things that can be done, particularly if you have large amount of i/o data you need to set up handshaking with device. you have to let the device handle at a rate that the device is happy with. in cases where larger data has to be transferred consider setting up a simple packet passing protocol and command semaphore construct - or use a protocol as defined that the controller / device is designed to work with.



来源:https://stackoverflow.com/questions/1379044/c-sharp-readin-from-serial-port-buffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!