views:

135

answers:

2

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);
        }
    }
}
+1  A: 

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

viky
+1  A: 

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

mtrw