我在编程时遇到了如下情况:我用的是重叠的方式进行串口通信,开始我由计算机向单片机发送一个数据,此时单片机一直在发等待命令;在发完数据以后,我使用FlushFileBuffers函数来清空串口缓冲区,然后去读串口的数据,但是我使用ReadFile收到的还是上一次发的值(即单片机开始等待时,向串口发的值);于是我怀疑串口缓冲区没有被清空,我就用函数PurgeComm来强行清空缓冲区的数据,结果我成功的收到了单片机发过来的数据.我不清楚为什么我用FlushFileBuffers函数不能清空,而用PurgeComm就可以?另外,还有一个问题是:计算机的串口缓冲区是分接受串口缓冲区和发送串口缓冲区,还是公用一个缓冲区?

解决方案 »

  1.   

    If a thread uses PurgeComm to flush an output buffer, the deleted characters are not transmitted. 
    the FlushFileBuffers function (a synchronous operation) empties the output buffer while ensuring that the contents are transmitted.
     
    Note, however, that FlushFileBuffers is subject to flow control but not to write time-outs, and it will not return until all pending write operations have been transmitted.计算机的串口缓冲区是分接受串口缓冲区和发送串口缓冲区的,可以用SetupComm设定各自的大小
      

  2.   

    谢谢楼上的回答,你上面的是msdn里的原文.
    里面对FlushFileBuffers 的描述,与我遇到的问题遇到的不完全相同.我向单片机发送数据以后,我使用FlushFileBuffers 返回的值是非零的.说明此函数已经执行成功了.但是串口缓冲区没有被清空,是不是意味着没有满足"while ensuring that the contents are transmitted."条件.那么"while ensuring that the contents are transmitted."的中文确切意思是什么哪?把它理解为"当确保发送的数据被发送的时候";
      

  3.   

    FlushFileBuffers 返回的值是非零只是说明该函数调用成功了,但是它的清除是滞后的,就是说直到缓冲区中的数据传输完毕才清除缓冲区。而PurgeComm是直接删除未传输的数据。所以不同啊,其实你的问题是出在延时上,所以用PurgeComm就成功了