I'm currently write a method that read data consecutively from serial port in C# winform for .NET framework.
I write an event handler for it, but since its static, i cannot call variable from outside. Now i'm thinking of how to getting data from the static method to outside. Like share data between static method and normal method.
Ofc this won't work correctly. I want sp
variable go into mySerialPort
but i don't know how.
private void GetComPortData()
{
SerialPort mySerialPort = new SerialPort("COM5");
mySerialPort.BaudRate = 115200;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.RtsEnable = true; //change to false if not need rts
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort.Open();
//how to make mySerialPort = sp?
//string dataComPort = mySerialPort.ReadExisting();
var data = dataComPort.Split(new[] { '/' },4);
/*Do some work to show data in datagridview*/
mySerialPort.Close();
}
//handle comport data
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
}
I also tried to change static
to other reference type, but it doesn't work. Any help is much appreciated.
DataReceivedHandler
doesn't need to bestatic
. I'm sure you have a good reason for making it that way, but please explain your thinking.DataReceivedHandler
. And of course you are not allowed to callmySerialPort.Close();
insideGetComPortData
, because this will happen immediately after opening the port and not wait for data to be received.DataReceivedHandler
will most likely receive the data afterGetComPortData
has returned.