I want to read and write from serial using events/interrupts. Currently, I have it in a while loop and it continuously reads and writes through the serial. I want it to only read when something comes from the serial port. How do I implement this in C++?
This is my current code:
while(true) { //read if(!ReadFile(hSerial, szBuff, n, &dwBytesRead, NULL)){ //error occurred. Report to user. } //write if(!WriteFile(hSerial, szBuff, n, &dwBytesRead, NULL)){ //error occurred. Report to user. } //print what you are reading printf('%s\n', szBuff); }
Use a
selectstatement, which will check the read and write buffers without blocking and return their status, so you only need to read when you know the port has data, or write when you know there’s room in the output buffer.The third example at http://www.developerweb.net/forum/showthread.php?t=2933 and the associated comments may be helpful.
Edit: The man page for select has a simpler and more complete example near the end. You can find it at http://linux.die.net/man/2/select if
man 2 selectdoesn’t work on your system.Note: Mastering
select()will allow you to work with both serial ports and sockets; it’s at the heart of many network clients and servers.