've made a GUI in WPF to read data via RS232 and.The only problem is I have to keep pressing a button to send a 'Receive data' command to my controller via RS232 so it sends the data back. I want to implement this in continuously/real time so I don't have to keep pressing a button to communicate with my device. I've written while loops and that just freezes my program, i've also tried a checkbox so if it's checked it gets data and that also freezes the GUI.using backGroundWorker i want to do or Threads, below is my code please, TextBox1 is Receiving Data,TextBox2 is Sending data, am binding Receiving data to textbox1 string"Message", see code as attachemnt
thanks
Loading
Glenn PattonPosted Mar 26, 2012, 4:17 AM
Sorry still a little new to this forum didn't see your post until now!
If you are using .NET2 Serial Port class you use an event handler delegate (called belive it or not name_of_port.DataReceived += SerialDataEventHandlerNAME have a look on google also www.lvr.com for examples. My example is pasted below
myComPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
--------
private void port_DataReceived_1(object sender,SerialDataReceivedEventArgs e)
{
InputData = myComPort.ReadExisting();
if (InputData != String.Empty)
{
this.BeginInvoke(new SetTextCallback(SetText), new object[]{ InputData});
// label1.Text = label1.Text + "I got some data";
}
}
private void SetText(string text)
{
this.rtbIncoming.Text += text;
}
There is a way to poll the read function with a timer, though this can get a bit erratic in large programs
private void tmrPollForRecievedData_Tick(object sender, EventArgs e)
{
string charToRead;
while (myComPort.BytesToRead > 0)
{
charToRead = (myComPort.ReadExisting());
rtbIncoming.Text = rtbIncoming.Text + (charToRead);//+ System.Convert.ToString(charToRead);
}
tmrPollForRecievedData.Enabled = false;
}
The down side with this is the timer component is maskable by the processor so this simple method can lead to some data going missing using DataRecieved Event gets around this.
Also to avoid locking the form use the non blocking method ReadExisting() which will return data that has been read.
Glenn PattonPosted Mar 29, 2012, 8:10 AM
Glenn PattonPosted Mar 29, 2012, 7:03 AM
Glenn PattonPosted Mar 29, 2012, 7:03 AM
gagan kumarPosted Mar 29, 2012, 7:02 AM
gagan kumarPosted Mar 23, 2012, 11:34 AM
Suthish NairPosted Mar 23, 2012, 11:00 AM