在调试模式下获取正确值,在串行编程的发布模式下获取错误值

本文关键字:获取 模式 布模式 取错误 调试 编程 | 更新日期: 2023-09-27 18:00:55

我创建了一个软件,它从RFID标签中读取值,并通过串行端口连接到计算机。当我在调试模式下运行程序时,会收到正确的值,但当我在发布模式下运行时,会显示不同的值。

RFID在调试模式下发送的值是'n00200054476720D'r'n,但当我在发布模式下运行时,它会以小块的形式显示值,有时还会显示后面跟着该代码的空值。

这是我的代码:

    try
    {
         _port2.PortName = "COM" + doorport_txt.Text;
         _port2.BaudRate = 9600;
         _port2.Parity = Parity.None;
         _port2.DataBits = 8;
         _port2.StopBits = StopBits.One;
         _port2.DataReceived += DoorPortDataReceivedHandler;
         _port2.ReadTimeout = 2000;
         if (!_port2.IsOpen)
    {
         _port2.Open();
    }
    MessageBox.Show(@"Door Port is Ready", @"Information", MessageBoxButtons.OK, 
MessageBoxIcon.Information);
    }
        catch (Exception ex)
        {
        MessageBox.Show(ex.Message, @"Error", MessageBoxButtons.OK,
     MessageBoxIcon.Error);
        }
    private void DoorPortDataReceivedHandler(object sender, 
SerialDataReceivedEventArgs e)
    {
        var sp = (SerialPort) sender;
        string indata = sp.ReadExisting();
        CheckTheft(indata);
    }

在调试模式下获取正确值,在串行编程的发布模式下获取错误值

发布模式代码运行"太快"-很遗憾它在调试模式下工作,因为行为没有得到很好的定义:ReadExisting并不意味着ReadEverythingEverToBeWritten。

[ReadExisting读取SerialPort对象的流和输入缓冲区中基于编码的所有立即可用的字节。

请考虑ReadLine/ReadTo,直到读取到正确的终止序列为止。

string indata = sp.ReadTo("'r'n");

串行端口将在接收字节数据时报告接收到的数据。你不能确定它会在一个事件中向你发送一个"完整"值(它怎么知道消息是完整的?记住,串行数据是一个字节流(。

您需要缓冲正在接收的数据,并确定何时收到完整的消息。

仅供参考-这可能在调试模式下工作,因为您在该模式下会减慢应用程序的速度。