簡體   English   中英

如何將來自串行端口的傳入數據保存到文本文件

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

我的窗戶上有兩個按鈕。

  1. 通過單擊開始按鈕,我想打開端口並在文本框中查看數據,同時我想將此數據逐行保存在另一個空文本文件中。
  2. 通過單擊“停止”按鈕,程序將停止保存數據,但仍會在文本框中顯示來自串行端口的傳入數據。 有人可以幫忙嗎? 我的“開始”和“停止”按鈕的代碼如下:

     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)您需要注冊到串行端口的DataRecieved事件,以接收來自串行端口實例的響應。

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

然后,在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)如果SerialPort實例的讀取緩沖區中仍然有數據,您將接收到數據。 關閉端口后,您需要從DataReceived事件中注銷。

sp -= sp_DataRecieved;

更新

您可以使用此方法附加到文件

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