微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 同一台Windows机器上的串行端口通信无法正常工作

对不起,快问:

我有这个硬件设置:

Same machine: “Com3” -> USB -> To Serial -> To USB -> “Com4”

我按照MSDN SerialPort ClassMSDN 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 Applicationit 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);

所有构造函数都将给出以下值:

07001 For example,the DataBits property defaults to 8,the Parity property defaults to the None enumeration value,the StopBits property defaults to 1,and a default port name of COM1.

即使握手也有认值.如果你look at the source code.

private const Handshake defaultHandshake = Handshake.None;

原文地址:https://www.jb51.cc/csharp/92842.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐