Sorting multiple incoming serial strings and storing to SD card

I have been working on a project which consists of two Uno’s and a Mega. The Uno’s each have an MPU-9150 attached and I am sending the values over an xbee to the Mega.

I am sending in the format of <SensorID,time,aX,aY,aZ,gX,gY,Gz.> at 100Hz.

I am able to collect the data from both Uno’s successfully in a .bin file, however I was wondering if there was a way to sort the two incoming messages in to columns within the bin file?

This is the example code I am using to store the values at the moment and it works pretty well, but it stores them in a column as they are received. If possible I would like to have Column 1 - Sensor 1, Column 2 - Sensor 2.

// Serial data logger example.
// Maximum baud rate for a Mega Arduino is 115200.
const uint32_t BAUD_RATE = 57600;

// Maximum time between sync() calls in milliseconds.  If Serial is always
// active, you must provide a way to stop the program and close the file.
const uint32_t MAX_SYNC_TIME_MSEC = 1000;

// Pin number for error blink LED.
// Set ERROR_LED_PIN to -1 for no error LED.
const int8_t ERROR_LED_PIN = 3;

#include <SdFat.h>
#include <SerialPort.h>

#if defined(__AVR_ATmega1280__)\
|| defined(__AVR_ATmega2560__)
// Mega, use 4096 byte RX buffer
SerialPort<0, 4096, 0> NewSerial;
#else // Mega
// not a Mega, use 1024 RX byte buffer
SerialPort<0, 1024, 0> NewSerial;

SdFat sd;
SdFile file;

// Error codes repeat as errno short blinks with a delay between codes.
const uint8_t ERROR_INIT   = 1;  // SD init error
const uint8_t ERROR_OPEN   = 2;  // file open error
const uint8_t ERROR_SERIAL = 3;  // serial error
const uint8_t ERROR_WRITE  = 4;  // SD write or sync error
void errorBlink(uint8_t errno) {
  uint8_t i;
  while (ERROR_LED_PIN < 0);
  while (1) {
    for (i = 0; i < errno; i++) {
      digitalWrite(ERROR_LED_PIN, HIGH);
      digitalWrite(ERROR_LED_PIN, LOW);
void setup() {

  if (!sd.begin()) {
  if (file.fileSize() == 0) {
    // Make sure first cluster is allocated.
// Time of last sync call.
uint32_t syncTime = 0;

uint8_t buf[32];
void loop() {
  if (NewSerial.getRxError()) {
  uint8_t n =, sizeof(buf));
  if (n > 0) {
    if (file.write(buf, n) != n) {
    // Don't sync if active.
  if ((millis() - syncTime) < MAX_SYNC_TIME_MSEC) return;
  if (!file.sync()) {
  syncTime = millis();  

Apologies if this is something easy I have missed in the examples given but I have hit a road block (impressed I managed to get this far to be honest).

The Mega must wait untul it gets both. Then it can write to the SD card. Maybe use a "timeout" so it doesn't wait forever if one unit stops transmitting.