Can i clear the serial port every time after reading the data from it?
i need to clear the data on serial port when i have read the data from it before i read the data again? i m using c/c+开发者_如何学Python+ on windows xp
how can i do so ?
thanx in advance.
Purging the receive buffer is almost always wrong. Serial port communications are asynchronous by nature, you'll risk deleting good data. Only if you use a master-slave protocol (the device only ever transmits when queried by the host) would allow purging. But then, if the receive buffer actually has data to purge then you're ignoring a protocol violation, something you never want to just ignore.
Reliable serial port communication requires a protocol. A checksum to verify message integrity and ACK/NAK handshaking to recover from data corruption. Check out the RATP protocol, described in RFC 916. Widely ignored btw but I've used it in the past. Its only weakness is buffered connection attempts.
The C++ standard has interfaces for writing to files, to the screen and to a log. It also has interfaces for reading from files and reading from "standard input." There is no standard way to interact with serial ports, network connections, etc.
Luckily your operating system or platform will have an interface for this. But (1) what you have to do to read from a serial connection, and (2) what you need to do between consecutive reads, and (3) how to do it are all platform dependent.
Looking at some Microsoft Documentation, you don't have to "clear the port" at all. But when a flag is set to signal something -- for instance that an error occurred -- then you need to reset the flag before continuing. Of course you reset the flag after handling whatever the flag was meant to signal.
The following solution is not the best, but it is suitable for many cases:
Read a large number of bytes from the serial port rendering it empty. For example:
ReadFile(Port,TMP,4096,&ioread,NULL);
tmp[ ]: is the variable that will hold the data that you don't want (flush data) ioread: Number of bytes read
So the above will read 4096 bytes from the serial port. You can increase the number to make sure you end up with a clean port after the statement.
P.S. I had used this with Visual Studio 2010, C++, Windows 7 - 64 bit
精彩评论