Click here to Skip to main content
15,889,853 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
I have written a code in c# for receiving data through serial communication and display it in a text box. I am able to do that. But I am receiving data in following format, e.g.

1234 2345 3456 5667
or

1234 3245 5678
But I want that every incoming byte should overwrite the previous byte and in the text box we should see just 1 byte and then another byte overwriting the previous one.

Please suggest how to do that?

My code for ser comm is as follows :

C#
private void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) 
{ 
    RxString = SerialPort.ReadExisting(); 
    this.Invoke(new EventHandler(DisplayText)); }

private void DisplayText(object sender, EventArgs e)
{
    txtIncomingData.AppendText(RxString);
}
Posted
Updated 2-Mar-15 17:25pm
v2

You misunderstood Control.Invoke. This is not event invocation, so your object sender and EventArgs arguments are superfluous. Having this made-up artificial limitation, you have done bad thing: passing the text through the outer context relative to your method. Instead, you should use the event delegate with any signature you need:
C#
string newData = SerialPort.ReadExisting(); // local variable to be used in next line
this.Invoke(new System.Action<string>((data) => {
   txtIncomingData.AppendText(data);
}), newData);

If you need to override the character, not append, assuming txtIncomingData is you text box, replace
C#
txtIncomingData.AppendText(data);

with
C#
txtIncomingData.Text = data;


—SA
 
Share this answer
 
v2
The solution below works, but it gives blank bytes in between data.

C#
    SerialPort serialPort;

    private delegate void SetTextDeleg(string text);

    private void Form1_Load(object sender, EventArgs e)
    {
          serialPort= new SerialPort("COM6", 4800, Parity.None, 8, StopBits.One);
          serialPort.Handshake = Handshake.None;
          serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
          serialPort.ReadTimeout = 500;
          serialPort.WriteTimeout = 500;
          serialPort.Open();
}

private void btnStart_Click(object sender, EventArgs e)
{
      try
      {
           if(!serialPort.IsOpen)
                serialPort.Open();
      }
      catch (Exception ex)
      {
           MessageBox.Show("Could not open Serial Port");
      }
}

void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
     Thread.Sleep(500);
     string data = serialPort.ReadLine();
     this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
}

private void si_DataReceived(string data)
{
      txtIncomingData.Text = data.Trim();
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900