简体   繁体   English

C#串口以符号形式接收数据

[英]C# Serial Port Receiving Data in the form of Symbols

i am having a arduino RFID enter code here reader which send me the data through serail port but i我有一个 arduino RFID enter code here阅读器,它通过串行端口向我发送数据,但我

do not receive data in the correct form like 0001685839 025,47439不要以正确的形式接收数据,如 0001685839 025,47439

please help my code is this请帮助我的代码是这样的

using System;
using System.IO.Ports;

class PortDataReceived
{
    public static void Main()
    {
        SerialPort mySerialPort = new SerialPort("COM3");

        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;
        mySerialPort.RtsEnable = true;

        mySerialPort.DataReceived += new     SerialDataReceivedEventHandler(DataReceivedHandler);

        mySerialPort.Open();
        Console.WriteLine();
        Console.ReadKey();
        mySerialPort.Close();
    }

    private static void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        Console.Write(indata);
    }
}

What data do you receive?你收到什么数据? There is a notion of buffer for com port. com 端口有一个缓冲区的概念。 You can end up with two read events in case when data does not fit port buffer.如果数据不适合端口缓冲区,您可以结束两个读取事件。

You can try something like this:你可以尝试这样的事情:

int bytesToRead = sp.BytesToRead;
var bytes = new byte[bytesToRead];

sp.Read(bytes, 0, bytesToRead);
var indata = Encoding.ASCII.GetString(bytes)

sp.DiscardInBuffer();
sp.DiscardOutBuffer();

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

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