c# – 同一台Windows机器上的串行端口通信无法正常工作
对不起,快问:
我有这个硬件设置:
我按照MSDN SerialPort Class和MSDN SerialPort.ReadLine()来构建这个例程: SerialPort SendSerialPort = new SerialPort("Com3",9600); SerialPort ReceiveSerialPort = new SerialPort("Com4",9600); SendSerialPort.Open(); ReceiveSerialPort.Open(); SendSerialPort.WriteLine("Test"); var message = ReceiveSerialPort.ReadLine(); // control stops here SendSerialPort.Close(); ReceiveSerialPort.Close(); Console.WriteLine(message); 但是,当我倾向于ReadLine()时,我的控件会停止并等待.我没想到的是. 我期待收到字符串Test并将其分配给我的var消息.你能告诉我这里我做错了什么吗? 编辑: 我使用Serial Port Utility Application和it worked just fine测试了我的硬件. 解决方法
我改变了
from the example you linked:
要实际让两个端口都运行来回读写,你实际上需要为两者实现读写的线程. 使用计时器是个好主意. public static void Main() { SerialPort SendSerialPort = new SerialPort("Com3",9600); SerialPort ReceiveSerialPort = new SerialPort("Com4",9600); StringComparer stringComparer = StringComparer.OrdinalIgnoreCase; Thread readThread = new Thread(Read); // Set the read/write timeouts _serialPort.ReadTimeout = 500; _serialPort.WriteTimeout = 500; SendSerialPort.Open(); ReceiveSerialPort.Open(); bool _continue = true; readThread.Start(); Console.Write("Name: "); name = Console.ReadLine(); Console.WriteLine("Type QUIT to exit"); while (_continue) { message = Console.ReadLine(); if (stringComparer.Equals("quit",message)) _continue = false; else SendSerialPort.WriteLine(String.Format("<{0}>: {1}",name,message)); } readThread.Join(); SendSerialPort.Close(); } public static void Read() { while (_continue) { try { string message = ReceiveSerialPort.ReadLine(); Console.WriteLine(message); } catch (TimeoutException) { } } } 通常,在写入的数据中会有一个开始和结束值,告诉另一个端口消息已完成,并且端口也要验证它们是否正在读取它们应该读取的数据,通常使用有关该数据的命令. (超出此问题的范围). 缺乏和重要的是您的端口的初始化. 我更喜欢使用默认构造函数(仅限首选项) SerialPort Constructor () 然后设置任何值,如下所示: _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate); _serialPort.Parity = SetPortParity(_serialPort.Parity); _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits); _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits); _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake); 所有构造函数都将给出以下值:
即使握手也有默认值.如果你look at the source code. private const Handshake defaultHandshake = Handshake.None; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |