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 SerialDataReceivedEventHand开发者_Python百科ler(comPort_DataReceived);
}
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (comPort.IsOpen == true)
{
string msg = comPort.ReadLine();
MessageBox.Show(msg);
}
}
}
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
ReadLine
depends on having a NewLine
character. You might have better luck with the Read
method. See also the BytesToRead
property.
精彩评论