简体   繁体   中英

C# - readin from serial port buffer

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);

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM