串口数据

时间:2015-12-31 05:22:22

标签: c# serial-port

我遇到串口数据问题。我设计了一个表单,我使用了一个datareceived处理程序事件,整个数据需要打印在表单中的RichTextBox中。问题是我只接收RichTextBox上的最后几位数据,而随代码提供的MessageBox部分地运行整个数据。请告诉我哪里出错了。谢谢。

public partial class Form1 : Form
    {
        char po='\0';
        string indata,pi;
        string[] buffer;
        public Form1()
        {
            InitializeComponent();
            System.ComponentModel.IContainer components = new System.ComponentModel.Container();
            serialPort1 = new System.IO.Ports.SerialPort(components);
            serialPort1.PortName = "COM1";
            serialPort1.BaudRate = 9600;
            serialPort1.DtrEnable = true;

            serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
            serialPort1.Open();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            po = Convert.ToChar(serialPort1.BytesToRead);


           indata = sp.ReadExisting();
           //return (indata);
                //for (int p = 0; p <= 256; p++) ;
                //MessageBox.Show(buffer[0]);



            //MessageBox.Show(indata);
            //richTextBox1.Text += indata;
            //richTextBox1.Text = indata;
        }

        private void button1_Click(object sender, EventArgs e)
        {

            richTextBox1.WordWrap = true;
            richTextBox1.Text = indata;
        }


    }

2 个答案:

答案 0 :(得分:1)

看起来每次通过串口接收数据时都应附加数据,所以也许你应该改变

indata = sp.ReadExisting();

为:

indata += sp.ReadExisting();

保存序列数据的所有内容,包括先前发送的历史数据。

希望这有帮助!

答案 1 :(得分:0)

尝试此代码....

private string StrValue = "";
private void Port_DataReceived(object sender, 
System.IO.Ports.SerialDataReceivedEventArgs e)
{
    double DouRWeight = 0;    
    try
    {
        DouRWeight = Val.ToDouble(Port.ReadLine());
        if (DouRWeight != 0)
        {
             this.Invoke((System.Windows.Forms.MethodInvoker)delegate()
             {
                 StrValue   = Val.Format(DouRWeight.ToString(), "####0.000");
             }
        }
    }
}
private void button1_Click(object sender, EventArgs e)
{
        richTextBox1.WordWrap = true;
        richTextBox1.Text = StrValue ;
}

完全奏效......