I'm new to serial communication and was trying to write a simple piece of code that writes and reads from a COM port. I have a wpf window that triggers the Connect and Disconnect functions, and when I start Connect the reader thread keeps timing out and doesn't get any data from the writer thread. Could anyone help me point out what's missing?
public void Connect()
{
port = new SerialPort("COM1", 115200);
port.ReadTimeout = 500;
port.WriteTimeout = 500;
port.Handshake = Handshake.None;
port.Open();
readThread = new Thread(Read);
readRunning = true;
readThread.Start();
writeThread = new Thread(Write);
writeRunning = true;
writeThread.Start();
System.Diagnostics.Debug.Print("connected");
}
public void Disconnect()
{
if (!readRunning && !writeRunning)
{
port.Close();
}
else
{
readRunning = false;
writeRunning = false;
readThread.Join();
writeThread.Join();
port.Close();
}
System.Diagnostics.Debug.Print("disconnected");
}
public void Read()
{
while (readRunning)
{
if (port.IsOpen)
{
try
{
int byteData = port.ReadByte();
System.Diagnostics.Debug.Print("message: " + byteData.ToString());
}
catch (TimeoutException)
{
}
}
}
}
public void Write()
{
byte[] byteData = {1,2,3};
while (writeRunning)
{
if (port.IsOpen)
{
try
{
port.Write(byteData, 0, 3);
}
catch (TimeoutException)
{
}
}
}
}