Getting correct value in Debug mode, wrong in Release mode with Serial Programing

StackOverflow https://stackoverflow.com/questions/23397002

  •  13-07-2023
  •  | 
  •  

Frage

I have created a piece of software which reads a value from a RFID tag and is connected to a computer through a serial port. When I run the program in debug mode, the correct value is received, but when I run it in release mode a different value is shown.

The value that RFID sends in debug mode is\n00200054476720D\r\n, but when I run in release mode it shows the value in small chunks or sometimes an empty value followed by that code.

Here is my code:

    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);
    }
War es hilfreich?

Lösung

The release mode code is running "too fast" - it was unfortunate that it was working in debug mode, because the behavior was not well defined: ReadExisting doesn't mean ReadEverythingEverToBeWritten.

[ReadExisting reads] all immediately available bytes, based on the encoding, in both the stream and the input buffer of the SerialPort object.

Consider ReadLine/ReadTo instead, which block until the correct termination sequence is read.

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

Andere Tipps

The serial port will report data received as it receives bytes of data. You can't be sure that it will send you a "complete" value in one event (how would it know the message is complete? Remember, serial data is a stream of bytes).

You need to buffer the data that you're receiving and determine when you have a complete message.

FYI - This may be working in debug mode because you're slowing the application down in that mode.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top