简体   繁体   English

如何将来自串行端口的传入数据保存到文本文件

[英]How to save incoming data from serial port to a text file

I have two buttons on my window. 我的窗户上有两个按钮。

  1. By clicking the start button I want to open the port and see the data in the textbox and at the same time i want to save this data in Another empty text file line by line. 通过单击开始按钮,我想打开端口并在文本框中查看数据,同时我想将此数据逐行保存在另一个空文本文件中。
  2. And by clicking the stop button the program just stops saving the data but still shows the incoming data from serial port in the textbox. 通过单击“停止”按钮,程序将停止保存数据,但仍会在文本框中显示来自串行端口的传入数据。 Can someone help? 有人可以帮忙吗? My code for start and stop button looks like: 我的“开始”和“停止”按钮的代码如下:

     private void buttonStart_Click(object sender, EventArgs e) { serialPort1.PortName = pp.get_text(); string Brate = pp.get_rate(); serialPort1.BaudRate = Convert.ToInt32(Brate); serialPort1.Open(); if (serialPort1.IsOpen) { buttonStart.Enabled = false; buttonStop.Enabled = true; textBox1.ReadOnly = false; } } private void buttonStop_Click(object sender, EventArgs e) { string Fname = pp.get_filename(); System.IO.File.WriteAllText(Fname, this.textBox1.Text); } 

1) You need to register to DataRecieved event of serial port to receive response from SerialPort instance. 1)您需要注册到串行端口的DataRecieved事件,以接收来自串行端口实例的响应。

sp = new SerialPort();
sp.DataReceived += sp_DataReceived;

Then, in sp_DataRecieved: 然后,在sp_DataRecieved中:

    void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        // this the read buffer
        byte[] buff = new byte[9600];
        int readByteCount = sp.BaseStream.Read(buff, 0, sp.BytesToRead);
        // you can specify other encodings, or use default
        string response = System.Text.Encoding.UTF8.GetString(buff);

        // you need to implement AppendToFile ;)
        AppendToFile(String.Format("response :{0}",response));

        // Or, just send sp.ReadExisting();
        AppendToFile(sp.ReadExisting());
    }

2) You will receive data if there is still data in read buffer of SerialPort instance. 2)如果SerialPort实例的读取缓冲区中仍然有数据,您将接收到数据。 After closing port, you need to deregister from DataReceived event. 关闭端口后,您需要从DataReceived事件中注销。

sp -= sp_DataRecieved;

UPDATE 更新

You can use this method to append to file 您可以使用此方法附加到文件

private void AppendToFile(string toAppend)
{
    string myFilePath = @"C:\Test.txt";
    File.AppendAllText(myFilePath, toAppend + Environment.NewLine);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM