I have connected a sensor to serial port of PC and want to read incoming data from Serial port in C#.
Below is code snippet. I tried to iterate through all the ports and open each port to check if device is connected to any port so that i can read data from that port.
However, none of the port return any data. "sp_DataReceived" event never get fired.
//serial port def
SerialPort sp;
//delegate to write to textbox
delegate void Write2UI(string text);
private void Form1_Load(object sender, EventArgs e)
{
try
{
string[] sps = SerialPort.GetPortNames();
foreach (string pname in sps)
{
sp = new SerialPort(pname);
sp.DtrEnable = true;
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
sp.Open();
Thread.Sleep(3000);
}
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
}
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
String test = sp.ReadExisting();
this.BeginInvoke(new Write2UI(dataReceived), new object[] { test });
}
private void dataReceived(string text)
{
textBox1.Text = text.Trim();
}
any help is appreciated.