使用C ++/CLR进行串行端口通信

问题描述:

亲爱的大家,

我目前正在使用C ++/CLI与串行端口通信,但是使用此方法时会遇到一些问题.

在您完成数据读取之前,我不确定如何应用StreamWriter函数将数据从串行端口缓冲区读取到文本文件中吗?

有人可以帮助您阅读示例代码吗?

我以前写过一些代码,但是它有几个程序,我不知道为什么.

Dear guys,

I am currently using C++/CLI to communicate with serial port, but I encounter some problems when using this method.

I am not sure how to apply StreamWriter function to read data from the serial port buffer into a text file until you the data reading finish?

can anybody help to read a sample code?

I previously write some code, but it has severial programs and i donot know why.

//create a instance of streamwriter to write text into file
StreamWriter^ sw = gcnew StreamWriter("data.txt", true);

DataReceiving = gcnew System::IO::Ports::SerialPort::ReadLine();

sw->WriteLine("you can use write function !!!");

sw->Close();

Console::WriteLine("Type QUIT to exit");



非常感谢您的帮助.



many thanks for your help.

您是否正确配置了端口?
与此类似的东西应该可以工作:

Did you configure your port properly?
Somthing close to this should work:

//configure port
SerialPort^ port = gcnew SerialPort();
port->PortName = "COM1";
port->BaudRate = 9600;
port->DataBits = 8;
port->Parity = Parity::None;
port->StopBits = StopBits::One;
port->ReadTimeout = 500;
port->WriteTimeout = 500;
//don''t forget this if you want to handle characters above 0x7f
port->Encoding = System::Text::Encoding::GetEncoding("Latin1");

//read data from port
String^ txt = port->ReadExisting();

//write txt to file
StreamWriter^ sw = gcnew StreamWriter("TestFile.txt");
sw->WriteLine(txt);
//you may also call Flush if you don''t want to close the file immediately.
sw->Flush();
sw->Close();


只需正确阅读自己的文字即可看到您的困惑:

要读取的StreamWriter函数".和作家一起读书吗?好吧...

其他一切都很容易,我会保证:).

—SA
Just read properly your own words to see your confusion:

"StreamWriter function to read". Reading with the Writers? Well...

Everything else is easy, I''ll guarantee that :).

—SA