Click here to Skip to main content
15,883,883 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
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 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
Posted
Updated 30-May-14 1:16am
v2
Comments
Herman<T>.Instance 30-May-14 7:17am    
did you close and reopen the sp port after ReadLine()?
RAHUL(10217975) 30-May-14 7:24am    
No, I am opening serial port in form load and closing in window close

This is a robust approach:


C#
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);
        }
 
Share this answer
 
Use
sp.ReadExisting();

in that case you read the complete buffer in stead of 1 line
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900