Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading data from serial port

Status
Not open for further replies.

ndevriendt

Programmer
Jan 8, 2002
74
BE
Hello,

I've a barcode scanner where I can communicate in a two way direction.

I'm listening on a serial port to know if an user have scanned a barcode. When data is entered in the serial port by scanning a code, I send a message back to the serial port that will be displayed at the barcode scanner.

My problem is that the event DataReceived is triggerd when I sent data to the serial port (by using a write command) and I get at the command readline() again the data from de barcode that the user has scanned.

Is there a way to clear everything in de serial port ?
I have already tried to use DiscardInBuffer but this is not helping.

See here some code:
_sp = new SerialPort(port);
_sp.DataReceived += new SerialDataReceivedEventHandler(BarCodeScanner_DataReceived);
_sp.Open();

void BarCodeScanner_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
barCode = _sp.ReadLine();
_sp.DiscardInBuffer();
// do some actions with the barcode
....
// Send a message
if (!(_sp.IsOpen)) _sp.Open();
_sp.Write(myMessage);
// After this write I comming back in this method and
// at ReadLine I'm getting back the barcode that the
// user has read. I'm looping...
}


I hope you can understand my problem.

Thans for your time and answer.

Devriendt Nico
 
I've never worked with the SerialPort component before, but just a suggestion, try using the WriteLine() instead. Somehow the datapacket must be terminated by one or more series of bytes when reading/writing from/to the port. I am only assuming that since you used ReadLine to read the data, then the data mustbe CRLF terminated.

Just my 2cents [wink]
 
Hello,

Thanks for your answer but this is giving the same result as with the write command

Nico
 
Do you need to keep the port open all the time? If not then close the port when you finish writing to the scanner, (you're doing a check anyway) and clear the barcode variable too ...

Patrick
 
Hello Patrick

Thanks for your answer.
My port need to be opened all the time.

I've done a close after the write like you said and then reopend my com port and this seems to work.

Many Thanks.

Devriendt Nico
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top