PIC + USB Communication (how it works)
The USB spec has the PC (host) tell the device when to send a packet, and when to receive a packet. The USB device cannot "send" data without the PC asking it for it. Thus, just checking "is last transmission done" is not sufficient; you also have to check "has PC sent a request?"

That being said, it's likely the PIC USB support library abstracts that part away. Maybe HIDTxHandleBusy does that for you?

To update the code in question to only send data when you have data available, you could simply change the if() statement that calls HIDTxHandleBusy() to also check whether you have any data you want to send, and only send data if that is the case:

if(!HIDTxHandleBusy(lastTransmission) &amp;&amp; IHaveSomeDataToSend)


Or maybe the send/receive functions block until the PC sends the appropriate command on the bus -- you'll have to check the documentation for the chip and the support library to get the real answer for that.

Doing a very quick Google, it seems that the support library takes ownership of your buffer when transmitting, and you cannot overwrite the buffer until the HandleBusy call returns done.

Btw: The code above is actually kind-of gross, because it first checks whether a transmission was complete (for the Rx case) and then starts a new transmission (receipt) and THEN it starts reading bytes out of the buffer (at the point when the USB hardware already has re-taken ownership of the buffer.) This seems like it's a race condition, given that HIDRxBuffer() takes ownership of the buffer.