I have been trying to find ways to write to the SD card from a serial stream as quickly as possible, but I have ran into problems and have been unable to find a solution. I have seen many posts that talk about this topic in a general way, but have seen nothing specific that has helped.
My code looks like this:
public static void Main()
{
serial = new SerialPort(SerialPorts.COM1, 115200, Parity.None, 8, StopBits.One);
serial.Open();
serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived);
Thread.Sleep(Timeout.Infinite);
}
static void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
do
{
readLen = serial.Read(buffer, bufferPos, ProtocolLength - bufferPos);
bufferPos += readLen;
if (bufferPos > 2000)
{
bufferPos = 0;
using (StreamWriter sw = new StreamWriter(new FileStream(@"SDtest.txt", FileMode.Append)))
{
led.Write(true);
sw.Write(new string(Toolbox.NETMF.Tools.Bytes2Chars(buffer)));
//sw.Close();
//sw.Dispose();
led.Write(false);
}
buffer = new byte[ProtocolLength];
}
}
while (readLen > 0);
}
Basically I am sending data to a 2k buffer that I then write to an SD card once the buffer comes close to filling up. I am receiving GPS data at intervals of 1 second and have my serial connection setup to receive as fast as I am able to. The incoming data varies between 600 bytes and around 2k bytes. What is happening is that when the program goes to write the data to the SD card data is lost is the process.
Any advice or suggestions would be greatly appreciated.
Things I have tried include looking at the SD card speed which is around 9MB/sec and removing "sw.Close()" and "sw.Dispose()" to try and gain any extra speed...I have even tried "Thread.Sleep()" mainly out of desperation. All have made no long term difference.