C# Errors with SerialPort WriteLine commands

青春壹個敷衍的年華 提交于 2020-02-06 08:09:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!