If you don't want to put all of your code in the using
block, you can close the port explicitly at the end.
SerialPort port = new SerialPort();
port.PortName = "COM16";
port.BaudRate = 38400; // Baud rate = bits per second
port.DataBits = 8; // unnecessary as 8 is the default
port.Parity = Parity.Even; // unnecessary as Even is the default
port.StopBits = StopBits.One; // unnecessary as One is the default
If you still can't connect, try connecting with Termite, which is a serial port terminal program. If you have to choose settings like "DTR/DTS" to get it to work, then you might need settings like this:
port.DtrEnable = true;
port.RtsEnable = true;
Then open your port.
port.Open();
port.DataReceived += OnRx; // Add the event handler for receiving data
The easiest way to read asynchronously is to create an event handler and pass the data back to a variable that the method has access to.
List<string> rx = new List<string>(); // the event handler stores the received data here
// Add this method to your class to read asynchronously.
protected void OnRx(object sender, SerialDataReceivedEventArgs e) {
while (port.BytesToRead > 0) {
try {
rx.Add(port.ReadLine());
} catch (Exception) { }
}
}
Close your port
port.Close();
Also check out the SerialPort
documentation.