Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

SD card sample


  • Please log in to reply
12 replies to this topic

#1 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 02 September 2010 - 05:47 PM

To test the new Netduino v4.1.1 (alpha 1) firmware, I built a sample project using the Adafruit GPS shield (and tested it with the Adafruit Datalogger shield as well). It will also work with any SD card adapter which supports 3.3V signals and uses pin D10 for the chip select.

I added SecretLabs.NETMF.IO.dll and System.IO as references in my project and then put this code in my Netduino app's Program.cs file. It simply mounts the SD card, gets a directory listing, and then prints out both the list of directories and the contents of the SD1 folder.

using System.IO;
using SecretLabs.NETMF.IO;

// ...

        public static void Main()
        {
            StorageDevice.MountSD("SD1", SPI_Devices.SPI1, Pins.GPIO_PIN_D10);

            string[] directories = System.IO.Directory.GetDirectories(@"\");
            Debug.Print("directory count: " + directories.Length.ToString());

            for (int i = 0; i < directories.Length; i++)
            {
                Debug.Print("directory: " + directories[i]);
            }

            string[] files = System.IO.Directory.GetFiles(@"\SD1");
            Debug.Print("file count: " + files.Length.ToString());

            for (int i = 0; i < files.Length; i++)
            {
                Debug.Print("filename: " + files[i]);
                FileStream fs = new FileStream(files[i], FileMode.Open, FileAccess.Read, FileShare.None, 512);
                StreamReader sr = new StreamReader(fs);
                Debug.Print("contents: " + sr.ReadToEnd());
            }
        }

Three notes:
1. The current alpha release ignores all parameters except for the first parameter (the target mounting folder). We'll be enabling support of different chip select lines and also an auto-mounting feature in an alpha/beta release next week.
2. You must use SD cards which support SPI. SDHC cards are not supported at this time. So I'd recommend SD cards that are <=2GB. I'm using a Kingston 2GB MicroSD cards in a MicroSD->SD adapter in this sample project.
3. I'm using StreamReader.ReadToEnd() here. That will only work with small files (as it reads the entire file into memory), and is just used as a simple example. If you would like to read/write large files, you'll want to read/write small chunks of data instead.

Enjoy!

Chris

#2 Steven Behnke

Steven Behnke

    Advanced Member

  • Members
  • PipPipPip
  • 70 posts
  • LocationLas Vegas, NV

Posted 02 September 2010 - 08:37 PM

Chris, what happens if StorageDevice.MountSD fails? Does it throw an exception? If it does, shouldn't your example catch it?

#3 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 02 September 2010 - 08:56 PM

Hi Steven, Good point. It's an alpha (pre-beta) release; no exception handling has been implemented yet. We'll update the sample when the code is further along. I'll also update the sample to iterate through the directories instead of hardcoding "SD1" in there twice... Good feedback. Thanks! Chris

#4 Steven Behnke

Steven Behnke

    Advanced Member

  • Members
  • PipPipPip
  • 70 posts
  • LocationLas Vegas, NV

Posted 02 September 2010 - 08:58 PM

Do you have a finite number of mount points? Should that be a ENUM instead, or a const string or something?

#5 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 02 September 2010 - 09:05 PM

Do you have a finite number of mount points? Should that be a ENUM instead, or a const string or something?


We're currently limiting it to one SD card mounted per Netduino--although we may be able to expand it. We wanted to offer users the flexibility of naming the mount point whatever they wanted, but maybe there's wisdom in returning a string with the name of the folder instead of letting the user specify it.

Oh, we do currently throw an ArgumentException from StorageDevice.Unmount(...) if you try to unmount an unmounted mount point.

[We're also thinking of renaming StorageDevice to PersistentStorage -- we'll talk more about that later.] We'd like to get the namespace and featureset locked down before we transition into the beta phase. We'd like to release v4.1.1 around the end of September, though, so this will be a pretty quick alpha->beta->RC->RTM cycle. Very little code should change between now and then; mostly just bugfixes and wrapper code...

Chris

#6 Caffeine

Caffeine

    Member

  • Members
  • PipPip
  • 22 posts
  • LocationSydney, Australia

Posted 03 September 2010 - 07:35 AM

Works with a SparkFun MicroSD shield, with a wire connecting D8 and D10...

Used a Sandisk 2GB MicroSD card borrowed from a friend's phone :)

directory count: 1
directory: \SD1
file count: 17
filename: \SD1\winamp_cache_0001.xml
filename: \SD1\PMP_USB.INI
filename: \SD1\DevIcon.fil
filename: \SD1\DevLogo.fil
filename: \SD1\WMPInfo.xml
filename: \SD1\qf
filename: \SD1\TMP65a01.$$$
filename: \SD1\Foo.m3u
filename: \SD1\shakesms-v1.02-symbiansigned.sisx
filename: \SD1\Track list.m3u
filename: \SD1\opera-mini-4.2.13337-advanced-en-gb.jar
filename: \SD1\Gang gang dance.m3u
filename: \SD1\Gurrumul.m3u
filename: \SD1\Kings o leon.m3u
filename: \SD1\Coldplay.m3u
filename: \SD1\Running.m3u
filename: \SD1\356255019313162.ndif



#7 fisu

fisu

    New Member

  • Members
  • Pip
  • 4 posts

Posted 28 November 2010 - 07:42 AM

I added reference to the SecretLabs.NETMF.IO.dll and copy&pasted the code but I'm missing System.IO.Directory and FileStream, StreamReader etc. am I missing some references?

#8 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 28 November 2010 - 07:51 AM

I added reference to the SecretLabs.NETMF.IO.dll and copy&pasted the code but I'm missing System.IO.Directory and FileStream, StreamReader etc. am I missing some references?


fisu,

Welcome to the Netduino community.

Did you add System.IO.dll as a reference to your project as well?

Chris

#9 fisu

fisu

    New Member

  • Members
  • Pip
  • 4 posts

Posted 28 November 2010 - 10:09 AM

fisu,

Welcome to the Netduino community.

Did you add System.IO.dll as a reference to your project as well?

Chris


That was the problem. It compiles now and I will be testing this with two different SD card shields. The smallest microSD card that I was able to find was 2GB but it says SDHC on the package. Do you think that it will work?

#10 Chris Walker

Chris Walker

    Secret Labs Staff

  • Moderators
  • 7767 posts
  • LocationNew York, NY

Posted 28 November 2010 - 08:07 PM

That was the problem. It compiles now and I will be testing this with two different SD card shields. The smallest microSD card that I was able to find was 2GB but it says SDHC on the package. Do you think that it will work?


I've never seen a 2GB card marked SDHC. The native SD drivers in .NET MF only support 32-bit addressing via SPI, so as a general rule SDHC is unsupported...but the card might support regular SD SPI mode.

There are a lot of resellers (including Amazon.com) selling inexpensive <=2GB MicroSD cards on the Internet. I can get you some links if interested.

Chris

#11 Oammar

Oammar

    New Member

  • Members
  • Pip
  • 3 posts

Posted 12 September 2011 - 09:47 AM

Does the MicroSD card breakout board+ work with this? Or is the fix still required? Edit: Didn't realize this post was so old. I'm assuming the current firmware is compatible with it?

#12 MosziNet

MosziNet

    Member

  • Members
  • PipPip
  • 13 posts
  • LocationBudapest, Hungary

Posted 25 October 2011 - 09:22 PM

An other sample, that may be relevant to using the SD card.


using System;
using Microsoft.SPOT;
using Microsoft.SPOT.IO;
using System.IO;

namespace Moszi.Net.Duino.WebServer
{
    /// <summary>
    /// The <see cref="FileManager"/> class is responsible of creating the profile file names based on the Netduino SD card name.
    /// </summary>
    public static class FileManager
    {
        private static bool hasFileSystemSupport;
        private static string rootFolderName; 

        /// <summary>
        /// Sets up the file manager class.
        /// </summary>
        static FileManager()
        {
            // find all volumes 
            VolumeInfo[] volumes = VolumeInfo.GetVolumes();
            foreach (var volumeInfo in volumes)
            {
                // then search for the sd card volume
                if (volumeInfo.Name == Constants.SDCardName)
                {
                    // check if the volume is formatted, if not then we can't use this
                    if (!volumeInfo.IsFormatted)
                    {
                        break;
                    }

                    // build the root folder name, and set our file system support flag to true
                    rootFolderName = Path.Combine( "\\" + volumeInfo.Name, Constants.HomeControllerFolder);

                    // create the directory if it doesn't exist
                    if (!Directory.Exists(rootFolderName))
                    {
                        Directory.CreateDirectory(rootFolderName);
                    }

                    hasFileSystemSupport = true;
                }
            }
        }

        private static string RootFolderName
        {
            get
            {
                return rootFolderName;
            }
        }

        /// <summary>
        /// Returns whether there is file system support in this HomeController.
        /// </summary>
        public static bool HasFileSystemSupport
        {
            get
            {
                return hasFileSystemSupport;
            }
        }

        /// <summary>
        /// Returns the filename for the password.
        /// </summary>
        public static string PasswordFilename
        {
            get
            {
                // build and return the 
                return Path.Combine(RootFolderName, Constants.HomeControllerPassword);
            }
        }
    }
}

The example uses the following constants:

        /// <summary>
        /// The name of the volume where Netduino can save information. Change this to SD if you are using
        /// a real NetDuino device, or change it to WINFS if you are using the emulator.
        /// </summary>
        public const string SDCardName = @"SD";

        /// <summary>
        /// The folder where Netduino stores information.
        /// </summary>
        public const string HomeControllerFolder = "DuinoWebServer";

        /// <summary>
        /// The password file name.
        /// </summary>
        public const string NetDuinoPassword = "password.txt";


#13 stotech

stotech

    Advanced Member

  • Members
  • PipPipPip
  • 143 posts
  • LocationAustralia

Posted 16 August 2012 - 06:20 AM

In the original post you writ

3. I'm using StreamReader.ReadToEnd() here. That will only work with small files (as it reads the entire file into memory), and is just used as a simple example. If you would like to read/write large files, you'll want to read/write small chunks of data instead.

Can you please elaborate. I'm trying to return a 60k html file and I'm running out of memory.

This is what I've tried but it's not returning the whole file, Just the last piece. If I use ddebug.print it prints it all broken line by line. But ie just shows the last line.
                 case "SetUp":
                    {
                        bool state = (e.Command.Arguments[0].Equals("on") ? true : false);
                        using (var filestream = new FileStream(@"\SD\SETUP.txt", FileMode.Open))
                        {
                            StreamReader sr = new StreamReader(filestream);
                            {
                                char[] buffer = new char[2 * 2];
                                int position = 0;
                                int charsRead = 0;
                                while ((charsRead = sr.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    string contentToProcess = new string(buffer, 0,charsRead);
                                    e.ReturnString = contentToProcess.ToString();
                                    position += charsRead;
                                }
                            }
                        }
                        break;
Thanks in advance.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.