问题
I am using the C# SerialPort class to write to my COM port. Weird thing is that I can get data from the port just fine - it sends data that I am expecting. However, I cannot send any data to the port. Any data that I send is immediately echoed back to me as new data coming from the port. I am expecting a "Done" command but it instead gives me back the data I just sent. It works just fine from Windows HyperTerminal but this code just won't work.
I'm using 9600, 8-N-1 with no flow control.
I'm mostly using code from this article:
I instantiate my port with this
comPort.BaudRate = int.Parse(_baudRate); //BaudRate
comPort.DataBits = int.Parse(_dataBits); //DataBits
comPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), _stopBits); //StopBits
comPort.Parity = (Parity)Enum.Parse(typeof(Parity), _parity); //Parity
comPort.PortName = _portName; //PortName
comPort.Handshake = Handshake.None;
comPort.ReadTimeout = 2000;
comPort.RtsEnable = true;
//now open the port
comPort.Open();
And the write is just using comport.write(string) and I've also used comport.writeline(string) with the same result.
What is the main difference between this code and plain vanilla HyperTerminal that would cause them to act differently?
回答1:
I stumbled across this answer that is not in many code example. The bottom line is that you have to include a carriage return with each port write. I was using:
comport.write(string)
But it should have been
comport.write(string+"\r\n")
You wouldn't believe how many code examples failed to have that in the code. I came across a random snippet that included it and that was the difference.
来源:https://stackoverflow.com/questions/3928474/c-sharp-errors-with-serialport-writeline-commands