串行端口通信中的数据重复与条形码 [英] Data Duplicacy in Serial Port Communication with barcode

查看:128
本文介绍了串行端口通信中的数据重复与条形码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Windows应用程序。我正在使用串行端口(条形码)。我正在调用串行端口数据接收事件

I am working in windows Application. I am using Serial Port (Barcode). I am calling serial Port Data receive event as

_SerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler2);



And每次扫描都会引起火灾。问题是,当我扫描卡片中断5秒时,它给我数据正确,但是当我在5秒钟之前扫描时,我得到了重复数据(旧扫描数据)。当我在互联网上搜索时,我找到了DiscardBufferOut,我实现了它,但结果仍然相同。



代码: -


And In every scan it got fire. The problem is when I scan card for break of 5 seconds its give me data correct, but when I scan before 5 seconds I got duplicate data (old scan data). As I search in internet I found DiscardBufferOut and I implemented it but still the same result.

Code :-

SerialPort _SerialPort1 = new SerialPort();

_SerialPort1.BaudRate = 9600;
_SerialPort1.DataBits = 8;
_SerialPort1.Parity = Parity.None;
_SerialPort1.StopBits = StopBits.One;
_SerialPort1.PortName = "COM3";
_SerialPort1.Handshake = Handshake.None;

_SerialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler1);

_SerialPort1.Open();





活动实施



Event Implementation

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

如果我在5秒前扫描卡片,我会得到重复数据(旧扫描数据),但如果我在5秒或6秒后扫描,我会得到新数据。

如果您有任何解决方案,请告诉我。





[Agent_Spock]

- 添加代码括号

- 更改问题的标题

If I scan Card before 5 seconds I get duplicate Data(old scanned data),but If I scan after 5 seconds or 6 seconds I get new data.
If you have any solutions please let me know.


[Agent_Spock]
- Added Code brackets
- Changed Heading of the question

推荐答案

ReadLine是阻塞方法:在从串口收到换行代码之前它没有返回。

但是......每次收到任何数据时都会发生DataRecieved事件 - 所以你会得到一堆他们排队所有尝试从同一端口读取相同的数据。由于DataRecieved是在与UI线程不同的线程上引发的,因此您很可能会多次使用该方法,所有这些都试图检索相同的数据行。讨厌。



不要那样做:相反,获取DataRecieved事件中的所有可用数据,并在传递完成的数据之前将其处理成行(或其他命令格式)继续进行命令处理。
ReadLine is a blocking method: it does not return before a newline code is received from the serial port.
But... The DataRecieved event happens every time that any data is received - so you will get a bunch of them "queued up" all trying to read the same data from the same port. And since DataRecieved is raised on a different thread to the UI thread, it is quite possible that you are sitting in that method many times, all trying to retrieve the same line of data. Nasty.

Don't do that: instead, get all available data in the DataRecieved event, and process it into lines (or other command forms) before passing completed data onward for command processing.


这篇关于串行端口通信中的数据重复与条形码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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