How can I flush the serial port before reading?

11,994

I believe the function you are looking for is PurgeComm, to which you pass the HANDLE you got from CreateFile() when you opened the port. I'm not sure, but I believe the serial port is also automatically flushed each time you open it.

However, a better method is to use ReadFile (or ReadFileEx) until you encounter something meaningful. Serial protocols are always designed with one or more sync bytes for this very purpose. Unless you are writing a terminal program or similar, you will have to do like this anyhow, since the Windows PC will never be in sync with the microcontroller otherwise.

Share:
11,994
Mawg says reinstate Monica
Author by

Mawg says reinstate Monica

Donate a cup of food for free: Click to Give @ The Hunger Site SOreadytohelp

Updated on June 04, 2022

Comments

  • Mawg says reinstate Monica
    Mawg says reinstate Monica almost 2 years

    I am trying to get a microcontroller to communicate with a Windows PC over serial port.

    It looks to me like Windows is buffering the input on COM1 such that if I stop both programs running, then restart only the Windows program it is still receiving some output from the previous run of the microcontroller's program.

    After I open COM1 can I some how flush its receive buffer before beginning to read? Is there a function call to do that?

  • Mawg says reinstate Monica
    Mawg says reinstate Monica about 11 years
    + (and probably the answer) PurgeComm looks great. Would it make sense to have a bi-directional protocol (sort of CTS/RS) where the sender waits until the receiver says it is ready to receive? (and would it be simpler to impement sender having a blocking call waiting for that before beginning transmission (i.e use data), or to use CTS/RTS?)
  • Lundin
    Lundin about 11 years
    @Mawg I would advise you to use software handshaking only. All the various signals of RS-232 are usually more trouble than what they are worth. Especially since your microcontroller program would have to implement RTS/CTS in a RS-232 compliant way, as these pins are not part of the standard MCU UART hardware.
  • Mawg says reinstate Monica
    Mawg says reinstate Monica about 11 years
    +1 so (for the answer), my receiver should send "ok, gimme data" at startup & my sender should not transmit until he receives it?
  • Lundin
    Lundin about 11 years
    @Mawg That is one possibility. Does the microcontroller care if anyone listens? Does it take actions based on what the PC is telling it? If so, then the kind of handshaking you describe is suitable. If not, then alternatively the sender could just spam "here is data, here is data, here is data", where the first part of the message is some sort of sync byte preferably one which is unlikely to appear in the actual data.
  • Mawg says reinstate Monica
    Mawg says reinstate Monica about 11 years
    Thanks for all of your help