102425074
102425074

Reputation: 811

Why text from SerialPort will break into several parts?

I used SerialPort to receive text from Handheld Scanner.In addition,the Handheld Scanner is using usb port to connnect with computer but its drivers will make it to a virtual SerialPort.

So I use this code to receive the text:

SerialPort serialPort=new SerialPort("COM7");
serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    Console.WriteLine(serialPort.ReadExisting());
}

Well,when I ran the progam,if the barcode is "1234567890",the text what received will break into several parts without rules.

Such as:
123
45
7890


Sometimes such as:
123456
7890


Sometimes such as:
12
34
567890


What's wrong with this,why the text divide into several without rules?How can I let it combine together but not divide any more?

PS:I tried different brand Handheld Scanner,such as Datalogic QD2430/Honeywell GHD1900,but these problem still here.

Upvotes: 0

Views: 77

Answers (2)

Joe B
Joe B

Reputation: 788

Configure your scanner that after each scan it should add a carriage return and then just get the result like this

var result = serialPort.ReadLine();

Upvotes: 0

user585968
user585968

Reputation:

Serial port I/O can be thought of as a streaming interface, i.e. You might not receive all the data in a single callback.

When you see:

12
34
567890

...I suspect what is happening is that your callback is being called three times with 3 Console.WriteLine calls. Hence your output looks broken.

Typically you need to read all the bytes until some terminator is reached, which depends on the device. You will need to buffer the data received until then. Until then, depending on the nature of the app, you might not be able to process the request.

Upvotes: 3

Related Questions