Click here to Skip to main content
15,895,462 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
MIDL
//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.
Posted

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();
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 1-Feb-11 13:13pm    
You sample is correct (my 5).
OP code looks gibberish, so I think the reason of confusion not related to configuration of the port. I tried to give a hint, see my "answer" :-).
--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
 
Share this answer
 
Comments
Olivier Levrey 1-Feb-11 13:54pm    
I was confused as well, but then I understood our friend wanted to read data from the port, then write them into a file using a StreamWriter ;)
Sergey Alexandrovich Kryukov 1-Feb-11 19:52pm    
Well, that was my guess too, I just think that addressing less-trivial matter makes no sense before the trivial confusion is recognized and things are sorted out and fixed in code, which should be presented.
On that condition, we would be able to continue. The technique itself is very simple, by the way, so I don't think the problem is very deep. Would you agree?

Thank you.
--SA
Olivier Levrey 2-Feb-11 3:43am    
I do.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900