简体   繁体   中英

Async read data from Arduino over serial C#

im very new to C# and is working on a personal project to send a message from Arduino when a button is pressed to my C# code listening on the serial port and writing the message in the console.

This is so far I've gotten:

using System;
using System.IO.Ports;
using System.Threading;
namespace ConsoleApp1
{
    class Program
    {
        static SerialPort _serialPort;
        public static void Main()
        {
            _serialPort = new SerialPort();
            _serialPort.PortName = "COM4";//Set your board COM
            _serialPort.BaudRate = 9600;
            _serialPort.Open();
            while (true)
            {
                string a = _serialPort.ReadExisting();
                Console.WriteLine(a);
                Thread.Sleep(200);
            }
        }
    }
}

In my console application I would also like to do other things not just wait on incoming data so i guess my option here is to use async?

I tried this: C# Async Serial Port Read But could not get it to work.

Does anyone have any recommendation on where to start, and sorry for this noobish question i have approx 10 hours of c# experiance:).

Here are some options you can use:

  1. Create a thread with loop calling Read() and call the event when data is received.
  2. Use event DataReceived (but it's not recommended, here's why: long article about SerialPort in C#
  3. Just check the stream if there any data with BytesToRead. If BytesToRead > 0, then call Read.
  4. Use BaseStream property with BeginRead and async callback

Accoring to the article mentioned above the only reliable way is to use Read OR use BaseStream with BeginRead (async option)

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