title: Write data to an SD card through a buffer without a race condition
body: <p>I am writing firmware for a data logging device. It reads data from sensors at 20 Hz and writes data to an SD card. However, the time to write data to SD card is not consistent (about 200-300&nbsp;ms). Thus one solution is writing data to a buffer at a consistent rate (using a timer interrupt), and have a second thread that writes data to the SD card when the buffer is full.</p>
  
  <p>Here is my naive implementation:</p>
  
  <pre><code>#define N 64
  char buffer[N];
  int count;
  
  ISR() {
      if (count &lt; N) {
          char a = analogRead(A0);
          buffer[count] = a;
          count = count + 1;
      }
  }
  
  void loop() {
      if (count == N) {
          myFile.open("data.csv", FILE_WRITE);
  
          int i = 0;
          for (i = 0; i &lt; N; i++) {
              myFile.print(buffer[i]);
          }
          myFile.close();
          count = 0;
      }
  }
  </code></pre>
  
  <p>The code has the following problems:</p>
  
  <ol>
  <li>Writing data to the SD card is blocking reading when the buffer is full</li>
  <li>It might have a race conditions.</li>
  </ol>
  
  <p>What is the best way to solve this problem? Using a circular buffer, or double buffering? How do I ensure that a race condition does not happen?</p>