Reputation: 81
I am working on a project for a physics class and would like to try and get an app together to perform the following. The test unit has a serial port on it that is outputting data at 1 Hz. I would like to have an app that will read the serial port data and save it to a file. I have created this in a Console app and it works fine. Now, I would like a GUI. On the main screen of the GUI I would like a couple of check boxes. One where the user can add a timestamp to the incoming data stream, one to output the data to a text file, and may be one to send the data to my graphite graphing server.
So, I am looking for some pointers here. Right now, I have a connect button. When pressed, it opens the serial port and performs a serial.readline() But if no data is currently being pushed across the link, the app is locked up. So I am assuming I need to use threading. Does this sound correct?
And last, how do I handle the check boxes? I would like 4 total buttons. Connect/Disconnect Record/Pause. At least these is my thoughts.
Upvotes: 0
Views: 189
Reputation: 846
Instead of creating a thread for the serial port just hook into the DataReceived event.
As for the checkboxes hook into the CheckedChanged event.
So it would look something like:
private bool paused;
private SerialPort sp;
public Form1()
{
InitializeComponent();
sp = new SerialPort();
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
}
private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (!paused)
{
string indata = sp.ReadExisting();
//Display the data
//To avoid cross thread problems do something like this
Invoke(new Action(() =>
{
textBox1.Text += indata;
}));
//Or if you are just writing to the console
Console.WriteLine(indata); //Thread safe
//Timestamp checkbox
if (checkBox3.Checked)
{
//Display timestamp using DateTime.Now
}
//Write to file checkbox
if (checkBox4.Checked)
{
using (StreamWriter file = new StreamWriter(path, true))
{
file.WriteLine(indata);
}
}
}
}
//Pause/Resume Checkbox
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
paused = checkBox1.Checked;
}
//Connect/Disconnect checkbox
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked)
{
sp.Open();
}
else
{
sp.Close();
}
}
Upvotes: 1