C# read only Serial port when data comes
c#, interrupt, serial-port
Solution
You will have to add an eventHandler to the DataReceived event.
Below is an example from msdn.microsoft.com, with some edits: see comments!:
public static void Main()
{
SerialPort mySerialPort = new SerialPort("COM1");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
mySerialPort.Close();
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Debug.Print("Data Received:");
Debug.Print(indata);
}
Everytime data comes in, the DataReceivedHandler will trigger and prints your data to the console. I think you should be able to do this in your code.
Problem
I want read my serial port but only when data comes(I want not polling). This is how I do it. ``` Schnittstelle = new SerialPort("COM3"); Schnittstelle.BaudRate = 115200; Schnittstelle.DataBits = 8; Schnittstelle.StopBits = StopBits.Two; .... ``` And then I start a thread ``` beginn = new Thread(readCom); beginn.Start(); ``` and in my readCom I'm reading continuous (polling :( ) ``` private void readCom() { try { while (Schnittstelle.IsOpen) { Dispatcher.BeginInvoke(new Action(() => { ComWindow.txtbCom.Text = ComWindow.txtbCom.Text + Environment.NewLine + Schnittstelle.ReadExisting(); ComWindow.txtbCom.ScrollToEnd(); })); beginn.Join(10); } } catch (ThreadAbortException) { } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } ``` I want yout read when a Interrupt is coming. But how can I do that ?