I'm on my laptop and unable to check this right now, I'm wondering if I open a COM2 connection, and add a receive event for COM2 port, then close the COM2 connection via "serial.Close()" in the program, will I still be able to receive a receive event on COM2 port? Let say if it can still receive, I think I will open the COM2 port connection at the receive event and read the data, can it be done this way?
SerialPort serial = new SerialPort()
{
PortName = "com2",
BaudRate = 9600,
Handshake = System.IO.Ports.Handshake.None,
Parity = Parity.None,
DataBits = 8,
StopBits = StopBits.One,
ReadTimeout = 400,
WriteTimeout = 200,
};
serial.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Receive);
private void Receive(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
using (SerialPort serialPort = serial)
{
if (serialPort.IsOpen)
serialPort.Close();
try
{
serialPort.Open();
received_data = serialPort.ReadExisting();
Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(WriteMyData), received_data);
}
catch (Exception ex)
{
}
finally
{
if (serialPort != null)
{
if (serialPort.IsOpen)
{
serialPort.Close();
}
Thread.Sleep(5);
//serialPort.Dispose();
}
Thread.Sleep(5);
}
}
}
public void SerialCmdSendByte(byte[] hexstring)
{
using (SerialPort serialPort = serial)
{
if (serialPort.IsOpen)
serialPort.Close();
try
{
serialPort.Open();
foreach (byte hexval in hexstring)
{
byte[] _hexval = new byte[] { hexval };
serialPort.Write(_hexval, 0, 1);
Thread.Sleep(3);
}
}
catch (IOException ex)
{
}
finally
{
if (serialPort != null)
{
if (serialPort.IsOpen)
{
serialPort.Close();
}
Thread.Sleep(5);
//serialPort.Dispose();
}
Thread.Sleep(5);
}
}
}
The idea is to only open a connection when I want to send from C# program and close it straight-away, but the same COM port is actually need to listen for communication from PIC-based microcontroller. Currently we are having issue where previously the program never try to close connection (unlike above code), but sometimes the receiving part from PIC-based microcontroller works but the sending part from program doesnt work. This only happens sometime, as normally the program work just fine...
Restarting the system seem to reset this OK. So I was thinking making the code like above will help in my situation(to be able to send, and listen on same COM port)?