为什么从串行端口Null接收数据?

时间:2012-10-07 09:18:12

标签: c# visual-studio-2010 event-handling serial-port grasshopper

下面的代码构建没有错误,虽然我没有从设备获得任何反馈,但与设备的连接似乎也有效。

在V.S.上,我在第myReceivedLines = sp.ReadExisting();行放置了一个断点,变量myReceivedLines返回null。

在连接到同一设备的另一个类似程序中,会出现几行反馈(见下文),为什么这个变量在我的情况下为空?

其他计划上显示的行:

Connecting...
start
Printer is now online.
echo:Marlin: 1.0.0 RC2
echo: Last Updated: 2012-05-22-1 | Author: eMAKER
...etc...

代码:

 //Fields
    string myReceivedLines;

    //subscriber method for the port.DataReceived Event
    private void DataReceivedHandler(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        myReceivedLines = sp.ReadExisting();
    }


       protected override void SolveInstance(IGH_DataAccess DA)
      {

        List<string> gcode = new List<string>();
        DA.GetDataList(0, gcode);
        string selectedportname = default(string);
        DA.GetData(1, ref selectedportname);
        int selectedbaudrate = default(int);
        DA.GetData(2, ref selectedbaudrate);
        bool connecttodevice=default(bool);
        DA.GetData(3, ref connecttodevice);
        bool sendtoprint= default(bool);
        DA.GetData(4, ref sendtoprint);

        if (!DA.GetDataList(0, gcode)) return;
        if (!DA.GetData(1, ref selectedportname)) return;
        if (!DA.GetData(2, ref selectedbaudrate)) return;
        if (!DA.GetData(3, ref connecttodevice)) return;
        if (!DA.GetData(4, ref sendtoprint)) return;


        SerialPort port = new SerialPort(selectedportname, selectedbaudrate, Parity.None, 8, StopBits.One); //Create the serial port
        port.DtrEnable = true;   //enables the Data Terminal Ready (DTR) signal during serial communication (Handshaking)
        port.Open();             //Open the port
        port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);


        if (gcode == null)
        {
            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specify a valid GCode");
            return;
        }

        if (connecttodevice == true)
        {
            DA.SetDataList(0, myReceivedLines);
        }
        else
        {
            port.Close();
        }

            if (sendtoprint == true)
            {
                foreach (String s in gcode)
                {
                    port.WriteLine(s);
                }
            }

                  }

1 个答案:

答案 0 :(得分:2)

    if (connecttodevice == true)
    {
        DA.SetDataList(0, myReceivedLines);
    }

SerialPort.ReadExisting()不能返回null,最坏的情况下你会得到一个空字符串。简单的解释是,在收到任何数据之前,您正在使用 myReceivedLines 。在这种情况下可能非常,您在打开端口后立即使用它。在您使用 myReceivedLines 之前,DataReceived将触发的几率正在消失。代码非常难以理解,您需要对其进行大幅修改。请记住,串口将在完全不可预测的时刻接收数据。您需要让DataReceived事件处理程序推进进度。