Introduction
This is a very basic testing tool that I created to test my serial port handling code. I did Google for such a basic tool which you would think would exist, but...
A Few Things You Might Need
I bought a few cheap USB to serial port cables which are helpful for testing on one machine. You can also install emulated serial ports, but I'd rather go with a more real scenario for testing.
Basic Features
- The application allows you to send / receive data over the serial port and save it.
- It allows you to configure all options of the .NET
SerialPort
class with a propertyGrid
.
- It allows you to select a directory and randomly send a file from that directory at a random interval.
- It enumerates the COM ports on your machine.
Using the Code
Almost all the functionality in the app is a one liner and completely self explanatory because .NET is such a well written high level language. The only tricky part of this app is that the serial port receives data on a separate thread. You cannot access visual controls from a separate thread, so you must invoke a delegate
that will set the text and send a copy of the memory with (new object[] { text }
).
It is important to notice that InvokeRequired
will let you know if the thread ID is different.
What will happen when we receive data is, serialPort1_DataReceived
handler will be fired when serial data is received and it will call SetText
which is just a little wrapper that will in turn invoke the SetTextCallback delegate
. The delegate
is set to call SetText
so SetText
will be invoked again, but now it is on the UI thread. At this point, this.txtData.InvokeRequired
will be false
and we can set the text like we normally would.
delegate void SetTextCallback(string text);
private void serialPort1_DataReceived
(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
SetText(this.serialPort1.ReadExisting());
}
private void SetText(string text)
{
if (this.txtData.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.txtData.Text = text;
}
}
Limitations
The serial app I am testing deals with old data matrix printer drivers and so I'm dealing with strictly text data going through the port, which is probably not what most people are looking for. I realize it would be more generically useful if it had a binary editor built in.
History
- 14th May, 2007: Initial post