简体   繁体   中英

How to read continuously from the SerialPort

I need to read continuously the bytestream from my Arduino board. For this, I've created a method that is reading the Serialport in a loop and expose the ByteStream to the other classes:

public async void ReadSerialPort 
   {
     dataReader = new DataReader(SerialPort.InputStream)
     while (true) {
      uint ReadBufferLength = 16;

      Task < UInt32 > loadAsyncTask;


      loadAsyncTask = dataReader.LoadAsync(ReadBufferLength).AsTask();

      UInt32 rxbytes = await loadAsyncTask;

      RxBytes = new byte[rxbytes];
      if (rxbytes > 0) {
       datareader.ReadBytes(ByteStream);

      }
     }
    }

But I think this is not the most efficient method for reading the serialport continuously as this method needs a couple of milliseconds to get the bytestream. Is there an alternative for reading the bytestream?

Use event to read data from SerialPort:

static void Main(string[] args)
{
    SerialPort sp=  new SerialPort();
    sp.DataReceived += Sp_DataReceived;
}

private static void Sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    throw new NotImplementedException();
}

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