How to clear the serial port buffer in visual studio

  • Thread starter Thread starter Mehdi25800
  • Start date Start date
M

Mehdi25800

Guest
Hi gays,

I've written a program in visual studio as below. all things are OK in first run, but second or and third run are incorrect and the characters are repeated again and are not cleared in each run. please help me. I've tried DiscardIn/Out buffer and so on, but I had no luck.

thanks.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using System.IO.Ports;

using System.Threading;

using System.IO;

using Excel = Microsoft.Office.Interop.Excel;

using Microsoft.Office.Interop.Excel;

using System.Configuration;



namespace mehdimashayekhi2

{

public partial class Form1 : Form

{

string Strbaud;


public Form1()

{


InitializeComponent();


}

private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)

{

Strbaud = comboBox1.Text;

serialPort1.Close();

try

{

serialPort1.DataBits = 8;

serialPort1.Parity = System.IO.Ports.Parity.None;

serialPort1.StopBits = System.IO.Ports.StopBits.One;

serialPort1.BaudRate = 9600;

serialPort1.PortName = comboBox1.Text;

serialPort1.Open();

serialPort1.DiscardInBuffer();

label6.BackColor = System.Drawing.Color.Green;

label6.ForeColor = System.Drawing.Color.White;

label6.Text = "(" + comboBox1.Text + ")" + "connected";



}

catch

{

label6.Text = "disconected";

label6.BackColor = System.Drawing.Color.Red;

label6.ForeColor = System.Drawing.Color.White;

MessageBox.Show("No available" + "(" + comboBox1.Text + ")", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

}

}


char[] charArray = new char[12];

private void DisplayText(object sender, EventArgs e)

{

int i = 0;

for (i = 1; i < 5; i++)

{

textBox1.AppendText(charArray.ToString());

}

string s;

s = textBox1.Text;

int n;

int.TryParse(s, out n);

if (n >= 3000)

{

textBox7.BackColor = System.Drawing.Color.White;

textBox7.ForeColor = System.Drawing.Color.Green;

textBox7.Text = "Passed";

}

else

{

textBox7.BackColor = System.Drawing.Color.White;

textBox7.ForeColor = System.Drawing.Color.Red;

textBox7.Text = "failed";

}

for (i = 7; i < 11; i++)

{

textBox2.AppendText(charArray.ToString());

}

dataGridView1.Rows.Add("", "", textBox4.Text, textBox5.Text, textBox6.Text, n, textBox2.Text);

}



private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)

{

dataGridView1.Rows[e.RowIndex].Cells[0].Value = e.RowIndex + 1;

dataGridView1.Rows[e.RowIndex].Cells[1].Value = "" + textBox3.Text + "-" + (e.RowIndex + 1);

}



private void serialPort1_DataReceived(object sender,

System.IO.Ports.SerialDataReceivedEventArgs e)

{


serialPort1.Read(charArray, 0, 12);

this.Invoke(new EventHandler(DisplayText));

}



Continue reading...
 
Back
Top