none
实现串口在接收到数据后如何继续发送数据 RRS feed

  • 问题

  • 工具:visual studio

    输出类型:window应用程序

    语言:c#

    问题描述:我在使用SerialPort时,接受数据后,想要继续发送数据。

    所以在发送数据的结尾加入了发送函数,但并没有接收到再次发送的数据

    想请教这个问题的原因,还有实现在串口接收到数据后程序自动继续发送数据,最好怎么弄?

    谢谢!

     //接收串口数据
            private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
            {
                byte[] ReceivedData = new byte[sp.BytesToRead];//创建接收字节数组
                sp.Read(ReceivedData, 0, ReceivedData.Length);//读取所接收到的数据
                receivedDatas.AddRange(ReceivedData);
    
                tbReceivedCount.Text = (Convert.ToInt32(tbReceivedCount.Text) + ReceivedData.Length).ToString();
    
                if (cb16Display.Checked)
                    tbReceivedData.Text = Methods.ByteTo16Str(receivedDatas.ToArray());
                else
                    tbReceivedData.Text = Encoding.Default.GetString(receivedDatas.ToArray());
                sp.DiscardInBuffer();//丢弃接收缓冲区数据
            }
            //发送串口数据
            private void DataSend()
            {
                try
                {
                    if (cb16Send.Checked)
                    {
                        byte[] hexBytes = Methods._16strToHex(tbSendData16);
                        sp.Write(hexBytes, 0, hexBytes.Length);
                        tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + hexBytes.Length).ToString();
                    }
                    else
                    {
                        sp.WriteLine(tbSendDataStr);
                        tbSendCount.Text = (Convert.ToInt32(tbSendCount.Text) + tbSendDataStr.Length).ToString();
                    }
    
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                    return;
                }
            }
    


    2018年2月27日 6:16

全部回复

  • Hi,

    欢迎在MSDN论坛发帖。

    据我所知在串口的寄存器中,应该有一项是配置缓冲区里面是不是有数据的,有数据就会发送,或者读取。如果你想程序接收数据后自动发送数据,我觉得你加一个定时器来判断是不是已经读完数据,如果是,你就可以调用发送函数。

    不用定时器你也可以用专门一个线程来检测是否有数据来了,有数据来了,就调用发送函数。

    Best Regards,

    Hart


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2018年2月28日 2:21
    版主