简体   繁体   English

在C#中从Arduino读取char数据

[英]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 . 所以我正在开发一个代码,使我能够通过SerialPort读取来自arduino的数据。 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. 我已经定义了我想从Arduino读取的字符,根据接收的内容,我将向Arduino发送一些东西。

What I will receive is based on three characters: @, r and \\r. 我将收到的内容基于三个字符:@,r和\\ 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 : 当arduino发送给我时,我想像这样阅读:

comport.ReadByte(asciiBytes); 

Could you help be figure out how I can read the data coming from the arduino like this? 您能帮我弄清楚我如何读取来自arduino的数据吗?

First, you should listen to incoming data by adding an event handler to your ComPort: 首先,您应该通过将事件处理程序添加到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: 如果接收到的数据中包含特定序列(@,r,\\ r),请检查以下字节:

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 由于Except是LINQ,所以请不要忘记添加

using System.Linq;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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