无法使用C#Mono(RaspberryPi)从串行端口读取

Ger*_*ldO 5 c# mono serial-port arduino raspberry-pi

我正在尝试编写一个C#库,它查看Raspberry Pi上所有可用的USB串行端口,以便我可以枚举,识别和通过USB集线器连接到Pi的一组Arduinos进行通信.

我能够在我的Windows机器上工作(几个Arduinos连接到我的桌面计算机),甚至能够使它在我的Pi上工作,但是,我很难理解如何推广修复.

如果我试图在Pi上自己运行程序,我可以打开串口并发送数据但是,我无法从Arduinos收到任何东西:我得到超时异常.我知道Mono的SerialPort实现是有限的,我必须使用SerialPort.ReadByte()而不是Readline()和数据接收事件(我的解决方案基于HowToSystemIOPorts的代码).我的串口枚举使用另一组交换响应概括的方法在这里.

我的超时当前设置为4秒,比我预期接收消息的时间长几个数量级.

经过大量的谷歌搜索,我发现在这里使用minicom来初始化串口,我惊讶地允许我从Arduino接收数据.最大的缺点是我需要使用minicom初始化端口,并在每次启动Pi时保持进程打开.我似乎也无法弄清楚如何使用多个Arduinos来完成这项工作.


这是我到目前为止所尝试的:

  • 将Pi固件和软件更新到最新版本
  • 试图同时使用Arduino MEGA 2560 R3和Arduino UNO
  • 将tty*端口的所有者(在本例中为ttyACM0和ttyUSB0)更改为我的用户和组
  • 通过minicom成功配置了端口,使进程保持运行并启动程序并读取/写入数据.一个手动过程,似乎一次只适用于一个Arduino
  • 在Windows中成功运行该程序没有错误
  • 验证了Arduinos被Pi运行"dmesg | grep tty"认可

这是我希望解决的问题:

  • 自动设置/初始化Arduino串行端口.是通过shell脚本在主程序之前运行还是在Mono代码中运行,以便下面的代码可以按预期运行.

这是我的连接代码:

    public bool StartArduinoComms()
    {
        string[] ports = GetPortNames();
        foreach (string port in ports)
        {
            mLogger.LogMessage(ProsthesisCore.Utility.Logger.LoggerChannels.Arduino, string.Format("Found serial port {0}", port));
        }

        bool foundCorrectArduino = false;

        var idPacket = new ArduinoMessageBase();
        idPacket.ID = ArduinoMessageValues.kIdentifyValue;

        string jsonOutput = Newtonsoft.Json.JsonConvert.SerializeObject(idPacket);

        foreach (string port in ports)
        {
            SerialPort serialPort = new SerialPort(port, kArduinoCommsBaudRate);
            serialPort.Parity = Parity.None;
            serialPort.DataBits = 8;
            serialPort.StopBits = StopBits.One;

            //Only check unopened ports
            if (!serialPort.IsOpen)
            {
                serialPort.Open();

                //Disable telemtry just incase
                var toggle = new { ID = ArduinoMessageValues.kTelemetryEnableValue, EN = false };
                string disableTelem = Newtonsoft.Json.JsonConvert.SerializeObject(toggle);
                serialPort.Write(disableTelem);

                //Discard any built up data
                serialPort.DiscardInBuffer();
                serialPort.Write(jsonOutput);
                serialPort.ReadTimeout = kIDTimeoutMilliseconds;

                string response = string.Empty;
                for (int i = 0; i < kNumRetries; ++i)
                {
                    try
                    {
                        //This is guaranteed to timeout if not configured through minicom
                        response = ReadLine(serialPort);
                        break;
                    }
                    //Catch case where the serial port is unavailable. MOve to next port
                    catch (TimeoutException)
                    {
                        continue;
                    }
                }

                if (!string.IsNullOrEmpty(response))
                {
                    //Perform response validation
                }
                else
                {
                    //Got no response
                }

                if (!foundCorrectArduino)
                {
                    serialPort.Close();
                }
            }
        }

        return foundCorrectArduino;
    }
    /// <summary>
    /// From https://stackoverflow.com/questions/434494/serial-port-rs232-in-mono-for-multiple-platforms
    /// </summary>
    /// <returns></returns>
    private static string[] GetPortNames()
    {
        int p = (int)Environment.OSVersion.Platform;
        List<string> serial_ports = new List<string>();

        // Are we on Unix?
        if (p == 4 || p == 128 || p == 6)
        {
            string[] ttys = System.IO.Directory.GetFiles("/dev/", "tty*");
            foreach (string dev in ttys)
            {
                //Arduino MEGAs show up as ttyACM due to their different USB<->RS232 chips
                if (dev.StartsWith("/dev/ttyS") || dev.StartsWith("/dev/ttyUSB") || dev.StartsWith("/dev/ttyACM"))
                {
                    serial_ports.Add(dev);
                }
            }
        }
        else
        {
            serial_ports.AddRange(SerialPort.GetPortNames());
        }

        return serial_ports.ToArray();
    }
Run Code Online (Sandbox Code Playgroud)

Tim*_*man 1

看看 stty 命令。它将让您设置/读取终端设置

http://linux.about.com/od/lna_guide/a/gdelna38t01.htm将给出其使用的概要。它比 minicom 更容易调用,并且设置保留在设备上。

  • 谢谢,这让我走上了发现问题本质的道路!事实证明,我根本不需要手动配置 TTY 端口,但是使用 stty 命令让我发现我真正的问题是打开串行端口会重置 Arduino。在尝试与 arduino 通信之前,我需要等待引导加载程序启动它。问题解决了! (2认同)