Anuya
Anuya

Reputation: 8350

DataReceived Event handler not receiving messages

I'm using the below code to receive the messages using serial port event handler. But it dosent receives any.I am not getting errors. The code breaks in "string msg = comport.Readline()" Am i doing something wrong ?

public partial class SerialPortScanner : Form
{
    private SerialPort comPort = new SerialPort();

    public SerialPortScanner()
    {
        InitializeComponent();
        comPort.Open();
        comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);

    }


    void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        if (comPort.IsOpen == true)
        {
            string msg = comPort.ReadLine();
            MessageBox.Show(msg);
        }
    }
}

Upvotes: 0

Views: 930

Answers (2)

mtrw
mtrw

Reputation: 35088

ReadLine depends on having a NewLine character. You might have better luck with the Read method. See also the BytesToRead property.

Upvotes: 1

viky
viky

Reputation: 17669

The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception.

Source : Check this

Upvotes: 1

Related Questions