Advertisement
LXL15

basic SD card read/write

Oct 30th, 2013
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.03 KB | None | 0 0
  1. /*
  2.   SD card read/write
  3.  
  4.  This example shows how to read and write data to and from an SD card file  
  5.  The circuit:
  6.  * SD card attached to SPI bus as follows:
  7.  ** MOSI - pin 11
  8.  ** MISO - pin 12
  9.  ** CLK - pin 13
  10.  ** CS - pin 10
  11.  
  12.  created   Nov 2010
  13.  by David A. Mellis
  14.  modified 9 Apr 2012
  15.  by Tom Igoe
  16.  
  17.  This example code is in the public domain.
  18.      
  19.  */
  20.  
  21. #include <SD.h>
  22.  
  23. File myFile;
  24.  
  25. char character;
  26. char last_char;
  27. int line_num = 1;
  28.  
  29. void setup()
  30. {
  31.  // Open serial communications and wait for port to open:
  32.   Serial.begin(9600);
  33.    while (!Serial) {
  34.     ; // wait for serial port to connect. Needed for Leonardo only
  35.   }
  36.  
  37.  
  38.   Serial.print("Initializing SD card...");
  39.   // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  40.   // Note that even if it's not used as the CS pin, the hardware SS pin
  41.   // (10 on most Arduino boards, 53 on the Mega) must be left as an output
  42.   // or the SD library functions will not work.
  43.    pinMode(10, OUTPUT);
  44.    
  45.   if (!SD.begin(10)) {
  46.     Serial.println("initialization failed!");
  47.     return;
  48.   }
  49.   Serial.println("initialization done.");
  50.  
  51.   // open the file. note that only one file can be open at a time,
  52.   // so you have to close this one before opening another.
  53.   myFile = SD.open("teamlist.txt");
  54.  
  55.   if (myFile) {
  56.     Serial.println("teamlist.txt:");
  57.    
  58.     // read from the file until there's nothing else in it:
  59.     while (myFile.available()) {
  60.       character = myFile.read();
  61.       if (last_char == '\n')
  62.       {
  63.         line_num = line_num + 1;
  64.       }
  65.       if (line_num == 2)
  66.       {
  67.       Serial.write(character);
  68.       }
  69.       last_char = character;
  70.     }
  71.    
  72.     int num_byte = myFile.size();
  73.     Serial.println("File size:");
  74.     Serial.println(num_byte);    
  75.     // close the file:
  76.     myFile.close();
  77.     Serial.println("File closed");
  78.   } else {
  79.     // if the file didn't open, print an error:
  80.     Serial.println("error opening test.txt");
  81.   }
  82. }
  83.  
  84. void loop()
  85. {
  86.     // nothing happens after setup
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement