[英]Is there any way to directly save serial port incoming data into file?
[英]How to save incoming data from serial port to a text file
我的窗户上有两个按钮。
通过单击“停止”按钮,程序将停止保存数据,但仍会在文本框中显示来自串行端口的传入数据。 有人可以帮忙吗? 我的“开始”和“停止”按钮的代码如下:
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.