串口扫描后的数据 [英] Serial port Data after scanning

查看:99
本文介绍了串口扫描后的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Windows应用程序。我在我的应用程序中使用串行COM端口。我在第二次扫描后从串口获取以前的数据。第一次扫描我得到了数据,第二次收到相同的数据。我在串口的datarecievehandler事件中的代码



I am working in windows application. I am using serial COM port in my application. I am getting previous data from serial port after second scan . First time scan I got the data, second time I am recieving the same data.My code in datarecievehandler event of serial port

public static void DataReceivedHandler1(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
 
string indata = sp.ReadLine();
 
//sp.DiscardInBuffer();
//sp.DiscardOutBuffer();
 
}



indata与以前的数据相同。我试图使用discardbuffer但它没有帮助...

如果你们有任何解决方案,请告诉我


indata gets same as previous data .I tried to use discardbuffer but its not helping...
If you guys have any solutions , then please let me know

推荐答案

这是一个强有力的方法:





This is a robust approach:


private SerialPort _serialPort;
    _serialPort = new SerialPort();
    _serialPort.Open();
    _serialPort.DataReceived += dataReceivedHandler;

        private void dataReceivedHandler(object sender, SerialDataReceivedEventArgs args)
        {
            if (!_serialPort.IsOpen)
                return;

            int BytesToRead = _serialPort.BytesToRead;

            byte[] data = new byte[BytesToRead];

            int NumBytes = _serialPort.Read(data, 0, BytesToRead);

            String mystring = Encoding.ASCII.GetString(data, 0, NumBytes);
        }


使用

Use
sp.ReadExisting();



在这种情况下你读完整个缓冲区而不是1行


in that case you read the complete buffer in stead of 1 line


这篇关于串口扫描后的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆