简体   繁体   中英

Read char data from Arduino in C#

So I am developing a code where I am able to read data coming from an arduino through SerialPort . I already defined what characters I want to read from the Arduino and depending on what to receive I will send something to the Arduino.

What I will receive is based on three characters: @, r and \\r.

string arroba = "@" + "r" + "\r";
byte[] asciiBytes = Encoding.ASCII.GetBytes(arroba);

I've mande this code but I don't know if this is actually gonna work.

When the arduino sent this to me I want to read it like :

comport.ReadByte(asciiBytes); 

Could you help be figure out how I can read the data coming from the arduino like this?

First, you should listen to incoming data by adding an event handler to your ComPort:

comport.DataReceived += Received;

Inside this handler, you can read the received bytes. Check this bytes if a specific sequence (@, r, \\r) is in the received data:

private void Received(object sender, SerialDataReceivedEventArgs e)
{
    int bytes = comport.BytesToRead;
    byte[] buffer = new byte[bytes];
    comport.Read(buffer, 0, bytes);
    if (buffer.Except(Encoding.ASCII.GetBytes("@r\r")).Any() == true)
    {
        //Your sequence was received
    }
}

Since Except is LINQ, don't forget to add

using System.Linq;

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