flysight/flysight — pull request #42 by crwper (2014-09-21 21:48:15+00:00)
Title: Fix UART overflow and timing issues

Previously, we have seen some timing issues resulting from time spent in FatFS functions. Namely:

1. Calls to ```f_sync``` would block the main loop, preventing the handling of data from the UART. This meant that if the call took too long to return, the UART buffer would overflow and data would be lost.

2. Similarly, by blocking in the main loop prevented the timely handling of tone updates, which led to a "stutter" in tones that should have been very regular.

3. Finally, blocking the main loop would prevent ```Tone_Task``` from loading new waveform data for spoken indications, which would result in a buffer overflow there and "clipped" speech.

Looking into the problem, I determined that the ```f_sync``` function was taking up to 140 ms to return. To put this into perspective, the tone buffer is only 131 ms long. Looking more closely, I determined that these long return times resulted from ```FatFS``` waiting for the microSD card to be ready. In particular, when a write to the microSD card crosses a cluster boundary, the card must clear the next cluster before it can be written. The ```f_sync``` operation cannot complete until this is done.

Looking more closely yet, I determined that there are two places in particular where the ```f_sync``` function tends to block. The three new ```f_sync_x``` functions break the original function into three parts around these two blocking points.

After examining the operations in each block, I believe that it is safe to access the card in a "read only" capacity between the three new ```f_sync``` operations. This means we can, e.g., fill the audio buffer in this time. Since a single blocking operation always takes less than 70 ms (when ```f_sync``` blocks for 140 ms, it is actually blocking twice internally), our current tone buffer is sufficient to provide audio during this time.

In testing, I have found that even with the present changes, the audio buffer is not sufficient if we double the audio rate (i.e., going from 7812 Hz to 15625 Hz). Therefore, I don't think we will be able to increase the audio sample rate without increasing the size of the audio buffer. It is doubtful we will be able to free up enough memory to do so.

Testing the new firmware for 3 continuous hours, I could detect no audio buffer overflows or UART buffer overflows.