多次读取SerialDataPort

时间:2017-04-18 08:05:33

标签: c# serial-port

我的代码存在问题,我想通过DataReceivedHandler阅读serialport,但我只工作一次。此串行端口是一个EnOcean USB密钥,当我按下电子卡上的按钮时,它会从电子卡接收数据。发送的数据是24个字节。我第一次按下按钮它工作得很好,我收到了数据,但如果我第二次按下,没有任何反应,DataReceivedHandler看不到任何东西,也没有发送给我数据。

    public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        //init serialport comport
        SerialPort comport = (SerialPort)sender;

        // Shortened and error checking removed for brevity...
        int bytes = comport.BytesToRead;
        string indata = comport.ReadExisting();
        byte[] buffer = new byte[bytes];
        comport.Read(buffer, 0, bytes);
        HandleSerialData(buffer, comport);

    }

HandleSerialData有效,在我的问题中无关紧要,我认为,我只是在代码中使用代码。

    public void HandleSerialData(byte[] respBuffer, SerialPort comport)
    {
        /*StringBuilder hex = new StringBuilder(respBuffer.Length * 2);
        foreach (byte b in respBuffer)
            hex.AppendFormat("{0:x2}", b);*/

        string hex = "";
        int n = 0;
        byte[] ID_TIC;
        ID_TIC = new byte[8];

        for (int i = 12 ; i < 15; i++)
        {
            ID_TIC[n] = respBuffer[i];
                n = n++;
        }

        hex = hex + BitConverter.ToString(ID_TIC).Replace("-",string.Empty);

        string hex2 = hex.ToString();
        Dispatcher.BeginInvoke((Action)(() => { EnOcean_Label.Content = ID_TIC; }));
        Dispatcher.BeginInvoke((Action)(() => { EnOcean2_Label.Content = ID_TIC; }));

        List<User> users = new List<User>();
        users.Add(new User() { NumeroTIC = hex2, NumeroCNT1 = hex2, Date = DateTime.Now });

        Dispatcher.BeginInvoke((Action)(() => { dgSimple.ItemsSource = users; }));

        WriteTest(ID_TIC);


    }

2 个答案:

答案 0 :(得分:0)

发送字节后你没有打开serialport(你需要这样做):

//Last line of code that sends the hex-code
System.Threading.Thread.Sleep(500) //Assuming you're starting with an open port

...等待回复

或者:

//Last line of code that sends the hex-code
comPortReadFunction()

您的读取功能不应包含任何参数。在收听COM端口时,您不需要拥有参数

答案 1 :(得分:-2)

嗯,我知道为什么我的问题,我的serialport没有被定义为静态,垃圾收集器每次都被杀死它被称为