What is the correct way to read a serial port using .NET framework?

后端 未结 3 1380
故里飘歌
故里飘歌 2020-11-27 03:12

I\'ve read a lot of questions here about how to read data from serial ports using the .NET SerialPort class but none of the recommanded approaches have proven completely eff

相关标签:
3条回答
  • 2020-11-27 03:44

    Could you try something like this for example I think what you are wanting to utilize is the port.ReadExisting() Method

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

    Or is you want to do it based on what you were trying to do , you can try this

    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();
            }
      }
    
    0 讨论(0)
  • 2020-11-27 03:44
        using System;
        using System.IO.Ports;
        using System.Threading;
    
        namespace SerialReadTest
        {
            class SerialRead
            {
                static void Main(string[] args)
                {
            Console.WriteLine("Serial read init");
            SerialPort port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
            port.Open();
            while(true){
              Console.WriteLine(port.ReadLine());
            }
    
        }
    }
    }
    
    0 讨论(0)
  • 2020-11-27 03:49

    I used similar code to @MethodMan but I had to keep track of the data the serial port was sending and look for a terminating character to know when the serial port was done sending data.

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题