2

以下のコードはエラーなしでビルドされます。デバイスからのフィードバックはありませんが、デバイスへの接続も機能しているようです。

VSでは、行にブレークポイントを配置しましたがmyReceivedLines = sp.ReadExisting();、変数myReceivedLinesはnullに戻ります。

同じデバイスに接続している別の同様のプログラムで、フィードバックの数行が表示されます(以下を参照)。私の場合、この変数が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);
                }
            }

                  }
4

1 に答える 1

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

SerialPort.ReadExisting() は null を返すことはできません。最悪の場合、空の文字列が返されます。簡単な説明は、データが受信される前にmyReceivedLinesを使用していることです。この場合、ポートを開いた直後に使用している可能性が非常に高いです。myReceivedLines を使用する前に DataReceived が発生する可能性はほとんどありません。コードは非常に不可解であり、大幅に修正する必要があります。シリアル ポートはまったく予測できない瞬間にデータを受信することに注意してください。DataReceived イベント ハンドラーに進行状況をプッシュさせる必要があります。

于 2012-10-07T14:00:01.387 に答える