Notes About Working with Various Arduino & Netduino Microcontroller Boards

Thursday, November 8, 2012

Writing to an SD Card with the Netduino Plus

The following example works with the Netduino Plus (v. 1), firmware and framework v. 4.1.

Netduino Plus 2 and NETMF v. 4.2 require a backslash at the start of the file path (i.e., \SD\test.txt).

I am using a 2GB SD card. Larger cards won't work.

For the following sample to work, add a reference to System.IO in the project's References section.

using System.IO;
using Microsoft.SPOT;

namespace SDTest
{
  public class Program
  {
    public static void Main()
    {
      // Test writing to file
      using (var filestream = new FileStream(@"SD\test.txt", FileMode.Create))
      {
        StreamWriter streamWriter = new StreamWriter(filestream);
        streamWriter.WriteLine("\nThis is a test...\nThis is only a test...\n");
        streamWriter.Close();
      }
      // Test reading from file just written
      using (var filestream = new FileStream(@"SD\test.txt", FileMode.Open))
      {
        StreamReader reader = new StreamReader(filestream);
        Debug.Print(reader.ReadToEnd());
        reader.Close();
      }
    }
  }
}


Here is a fancier example that uses event handlers to detect when the SD card is inserted or ejected. The program writes the test file to the SD card when it detects it is inserted (or already inserted when the program starts).

Be sure to add the references to System.IO and Microsoft.SPOT.IO.

using System.IO;
using Microsoft.SPOT;
using Microsoft.SPOT.IO;
using Microsoft.SPOT.Hardware;
using System.Threading;

namespace SDTest
{
  public class Program
  {
    public static void Main()
    {
      RemovableMedia.Insert += new InsertEventHandler(RemovableMedia_Insert);
      RemovableMedia.Eject += new EjectEventHandler(RemovableMedia_Eject);
      Thread.Sleep(Timeout.Infinite);
    }
    static void RemovableMedia_Insert(object sender, MediaEventArgs e)
    {
      Debug.Print("SD card inserted.\n");
      using (var filestream = new FileStream(@"SD\test2.txt", FileMode.Create))
      {
        StreamWriter streamWriter = new StreamWriter(filestream);
        streamWriter.WriteLine("\nThis is a test...\nThis is only a test...\n");
        streamWriter.Close();
      }
      using (var filestream = new FileStream(@"SD\test2.txt", FileMode.Open))
      {
        StreamReader reader = new StreamReader(filestream);
        Debug.Print(reader.ReadToEnd());
        reader.Close();
      }
    }
    static void RemovableMedia_Eject(object sender, MediaEventArgs e)
    {
      Debug.Print("SD card ejected.\n");
    }
  }
}

No comments:

Post a Comment