Serial Port Behaves Differently using Button

Ceramic Lambda Story 26 Reputation points

I am developing an application which uses the RS232 port. I am having a problem understanding why the following command only works when I create a dedicated button for it.

I tried to post my code but the Azure Firewall thing blocks it so please excuse my screen captures.

SerialPort1.Write("*IDN?" & vbCr)

If I create btnIDN and place this command in the sub, it works fine:

    Private Sub btnIDN_Click(sender As Object, e As EventArgs) Handles btnIDN.Click  
        'get equipment info  
        SerialPort1.Write("*IDN?" & vbCr) 'concatenate with \n  
End Sub  



Windows 10
Windows 10
A Microsoft operating system that runs on personal computers and tablets.
10,162 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Limitless Technology 39,161 Reputation points

    Hello Ceramicprofiler,

    It's surely because you have no synchronization whatsoever. .ReadExisting() does not get an entire response, it gets only what's already been received. So calling it right after .WriteLine(...)... well your data hasn't even reached the device yet, so there definitely won't be an answer ready to read.

    Since you know the length of your expected answer (or at least the prefix you're interested in), set the read timeout and then call .Read() (or better, .BaseStream.ReadAsync()) with that length.

    Even that is only going to mostly work when the port is freshly opened... for subsequent commands you risk getting data in your buffer from the tail end of a reply to an earlier command. Correct use of a serial port really requires the two ends to agree on some sort of framing, whether that is "a message contains only ASCII and ends with CR+LF" or "a message starts with the length of its payload" or some less common scheme.


    --If the reply is helpful, please Upvote and Accept as answer--

    0 comments No comments