Pages: 1 ... 10 11 [12] 13   Go Down
Author Topic: SD card read/write with Arduino  (Read 100493 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 8
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi

Thanks for the reply Cemath. Really sorry the late post. I tried out as you said. But still I am not getting the expected output. I found that increasing or decreasing the buffer size [ default 7 ] as no effect on the output. The only change is that suppose if I set buffer[10], then while reading the data, I get a junk character or symbol after each tenth character. So, I googled again and seeked help from other forums too. Finally I found the sdfatlib library doing the GPS logging and SDcard read/write functionality. http://code.google.com/p/sdfatlib/.
I tried the examples provided by that library and it worked fine. I was able to read data in char datatype. But since, the GPS sentences logged by GPS are of varied length due to absence of some fields, I had problems in parsing the sentence from the file and extracting the latitude and longitude alone for further processing.
So, I tried the otherway around and modified the GPS logging code[ SdFatGPSLogger example from the sdfatlib library] to log only the latitude and longitude into the sdcard textfile. I worked fine. The log file has contents like below,
Code:
13.1224,80.2222
13.1224,80.2222
13.1224,80.2222
13.1224,80.2222
13.1224,80.2222
13.1224,80.2222
13.1224,80.2222
13.1224,80.2222
13.1224,80.2222
13.1224,80.2223
13.1224,80.2223
13.1224,80.2223
13.1224,80.2223
13.1224,80.2223
13.1224,80.2223
13.1224,80.2223
13.1224,80.2222
13.1224,80.2222
13.1224,80.2222
13.1225,80.2222
13.1225,80.2222
13.1226,80.2222
13.1226,80.2222
13.1226,80.2222
13.1226,80.2222
13.1226,80.2222
13.1226,80.2222
13.1226,80.2221
13.1227,80.2221
13.1227,80.2221
13.1227,80.2220
13.1227,80.2220
13.1227,80.2219
13.1227,80.2219
13.1227,80.2218
13.1227,80.2218
13.1227,80.2217
13.1227,80.2217
13.1227,80.2216
13.1227,80.2216
13.1227,80.2215
13.1227,80.2215
13.1227,80.2214
13.1227,80.2214
13.1227,80.2214
13.1227,80.2213
13.1227,80.2213
13.1227,80.2213
13.1227,80.2213
13.1228,80.2213
Now, I stored this file in sdcard and tried to read it using the SdFatRead example. the example read the contents. Since, the file contents in each line are of same size, I used a fixed buffer size and used the comma delimiter to parse the data. I stored the latitude and longitude temporarily within the loop using two char arrays. I tried printing it as I read from the card. It worked.
Now, my problem is that , As I read the above data line by line from the card I need to compare it with another char array, so that If the arrays matches, I will send some data to print on the LCD display.
I used string functions. no use. Since the comparsion is between two char arrays, Inclusion of loops doesnot have data in it to compare. I really dont where is the mistake happening. I am stuck in this issue. I have posted the modified code here [ with no comparsion part] . Please help me out.
Code:
/*
 * This sketch reads and prints the file
 * PRINT00.TXT created by SdFatPrint.pde or
 * WRITE00.TXT created by SdFatWrite.pde
 */
 #include <stdio.h>
#include <SdFat.h>
#include <SdFatUtil.h>

Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;

// store error strings in flash to save RAM
#define error(s) error_P(PSTR(s))
void error_P(const char *str)
{
  PgmPrint("error: ");
  SerialPrintln_P(str);
  if (card.errorCode()) {
    PgmPrint("SD error: ");
    Serial.print(card.errorCode(), HEX);
    Serial.print(',');
    Serial.println(card.errorData(), HEX);
  }
  while(1);
}
void setup(void)
{
  Serial.begin(4800);
  Serial.println();
  Serial.println("type any character to start");
  while (!Serial.available());
  Serial.println();
  
  // initialize the SD card
  if (!card.init()) error("card.init");
  
  // initialize a FAT volume
  if (!volume.init(card)) error("volume.init");
  
  // open the root directory
  if (!root.openRoot(volume)) error("openRoot");
  
  // open a file
  if (file.open(root, "GPSLOG00.TXT", O_READ)) {
    Serial.println("Opened GPSLOG00.TXT");
  }
  else if (file.open(root, "WRITE00.TXT", O_READ)) {
    Serial.println("Opened WRITE00.TXT");    
  }
  else{
    error("file.open");
  }
  Serial.println();
  
  // copy file to serial port
  int16_t n;
//  uint8_t buf[19];// nothing special about 7, just a lucky number.
  char buf[15];
  char lat[8],lon[8];
  char temp;
int linecount=494,count=0; // char *latitude="13.1224",*longitude="80.2222";
  char array1[linecount][8],array2[linecount][8];
 while ((n = file.read((uint8_t *)buf, sizeof(buf))) > 0)
  {
    for(int i=0;i<n;i++)
    {
     if(buf[i]!=',')
      {
        lat[i]=buf[i];
        Serial.print(lat[i]); // This place is where comparsion will occur
      }
      else
      {
        i=i+1;
        lon[i]=buf[i]; // This place is where comparsion will occur
        Serial.print(lon[i]);
      }
    }
  }
  /* easier way
  int16_t c;
  while ((c = file.read()) > 0) Serial.print((char)c);
  */
 Serial.println("\nDone");
}

void loop(void) {}

My doubt may be silly. But please help me out since I need to complete the project as part of my academics.
Thanks in advance
Regards
N.Nandhakumar
Logged

Indonesia
Offline Offline
Jr. Member
**
Karma: 0
Posts: 70
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Dear All
I don't meant to hijack this thread, but I also got same problem with sdfatlib, and when I put sdfatlib as search keyword it refer to this thread.

So here we go.
I have a data file like this :
Code:
1474,254
1616,253
2998,254
3153,253
3925,254
4094,253
4642,254
4827,253
5255,254
5459,253
5810,254
6039,253
6336,254
6597,253
6851,254
7160,253
7379,254
7768,253
7957,254
8547,253
8705,254
10133,255
10293,254
10831,255
11031,254
11365,255
11617,254
11866,255
12210,254
12405,255
13096,254
13240,255
13600,256
13744,255
14413,256
14614,255
14931,256
15209,255
15431,256
15918,255
16077,256
16803,257
16963,256
17434,257
17664,256
17922,257
18298,256
18474,257
19442,258
19619,257
19981,258
20254,257
20468,258
21838,259
22057,258
22318,259
22746,258
22905,259
23336,260
23494,259
23917,260
24187,259
24395,260
25432,261
25643,260
25905,261
26455,260
26592,261
26613,262
26757,261
27244,262
27523,261
27721,262
28491,263
28690,262
28963,263
30133,264
30414,263
30605,264
31214,265
31406,264
31682,265
32712,266
32995,265
33180,266
33666,267
33852,266
34131,267
35051,268
35337,267
35517,268
35902,269
36082,268
36364,269
37199,270
37488,269
37662,270
37963,271
38138,270
38424,271
39185,272
39479,271
39648,272
39873,273
40042,272
40335,273
41035,274
41333,273
41497,274
41662,275
41826,274
42122,275
42768,276
43072,275
43231,276
43333,277
43491,276
43797,277
44401,278
44717,277
44870,278
44891,279
45039,278
45369,279
45949,280
46294,279
46436,280
46457,281
46621,280
46899,281
47374,282
47659,281
47817,282
47869,283
48025,282
48314,283
48764,284
49059,283
49211,284
49232,285
49389,284
49670,285
50078,286
50366,285
50518,286
50539,287
50699,286
50967,287
51327,288
51599,287
51754,288
51775,289
51932,288
52199,289
52528,290
52797,289
52951,290
52972,291
53133,290
53385,291
53673,292
53928,291
54086,292
54107,293
54268,292
54517,293
54773,294
55019,293
55179,294
55200,295
55361,294
55603,295
55835,296
56079,295
56238,296
56259,297
56427,296
56655,297
56844,298
57069,297
57236,298
57257,299
57418,298
57651,299
57837,300
58073,299
58231,300
58252,301
58427,300
58636,301
58760,302
58962,301
59140,302
59184,303
59356,302
59565,303
59682,304
59889,303
60061,304
60082,305
60251,304
60461,305
60567,306
60773,305
60943,306
60964,307
61139,306
61338,307
61406,308
61594,307
61777,308
61798,309
61965,308
62170,309
62247,310
62447,309
62617,310
62638,311
62827,310
63006,311
63027,312
63205,311
63392,312
63429,313
63616,312
63793,313
63814,314
64001,313
64177,314
64198,315
64391,314
64561,315
64582,316
64788,315
64947,316
64968,317
65219,316
65354,317
65375,318

and here is what I got from SdFatTail.pde


Question :
How to put each "field" of the output into to different variable (ie: var1, var2) rather than printing it out.

here is the code (small edited from original sample)
Code:
/*
 * This sketch reads and prints the tail of all files
 * created by SdFatAppend.pde, SdFatPrint.pde, and
 * SdFatWrite.pde.
 */
#include <SdFat.h>
#include <SdFatUtil.h>

Sd2Card card;
SdVolume volume;
SdFile root;
SdFile file;

// store error strings in flash to save RAM
#define error(s) error_P(PSTR(s))
void error_P(const char *str)
{
  PgmPrint("error: ");
  SerialPrintln_P(str);
  if (card.errorCode()) {
    PgmPrint("SD error: ");
    Serial.print(card.errorCode(), HEX);
    Serial.print(',');
    Serial.println(card.errorData(), HEX);
  }
  while(1);
}

void setup(void)
{
  Serial.begin(9600);
  Serial.println();
  Serial.println("type any character to start");
  while (!Serial.available());
  Serial.println();
  
  // initialize the SD card
  if (!card.init()) error("card.init");
  
  // initialize a FAT volume
  if (!volume.init(card)) error("volume.init");
  
  // open the root directory
  if (!root.openRoot(volume)) error("openRoot");
}

/*
 * Print tail of all SdFat example files
 */
void loop(void)
{
  dir_t dir;
  char name[13];
  
  // read next directory entry
  if (root.readDir(dir) != sizeof(dir)) {
    Serial.println("End of Directory");
    while(1);
  }
  
  // check for file name "APPEND.TXT", "PRINT*.TXT"
  // or "WRITE*.TXT"
  // first 8 bytes are blank filled name
  // last three bytes are blank filled extension
  if ((strncmp((char *)dir.name, "MYSTEP", 6)) ||
      strncmp((char *)&dir.name[8], "TXT", 3)) {
        return;
  }
  // format file name
  SdFile::dirName(dir, name);
  
  // remember position in root dir
  uint32_t pos = root.curPosition();
  
  // open file
  if (!file.open(root, name, O_READ)) error("file.open");
  
  // restore root position
  if (!root.seekSet(pos)) error("root.seekSet");
  
  // print file name message
  Serial.print("Tail of: ");
  Serial.println(name);
  
  // position to tail of file
  //if (file.fileSize() > 100) {
  //  if (!file.seekSet(file.fileSize() - 100)) error("file.seekSet");
  //}
  int16_t c;
  // find end of line  
  //while ((c = file.read()) > 0 && c != '\n');
  
  // print rest of file
  while ((c = file.read()) > 0)
  {
    Serial.print((char)c);
  }
  file.close();
  Serial.println();
}

Sincerely
-bino-
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 1
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Does it work with a micro-SD ? I been trying use it but it didnt work out  smiley-sad
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 1
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I'm having the same problem as alecjcook.  when i put the #includes in an otherwise skeleton sketch i get:

C:\Program Files\arduino-0018\libraries\SDcard\arduino sd card example.cpp:161: error: 'DEC' was not declared in this scope

along with 'HEX' not declared, 'Serial' not declared, 'delay' not declared ...

does the cpp file need some tweaking maybe?
Logged

Orduña- Bizkaia
Offline Offline
Sr. Member
****
Karma: 0
Posts: 317
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi, delete #include <FatStructs.h> and the problems disappear.

I have other problem how i can change the pins 10-13 to 5-8?I modified Sd2PinMap but not working.

Thanks
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 1
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi everyone,
I'm sorry to re-ressurect this, but this library seems to be the best (of the thousand SD Libraries) to fit my needs...

I've got the same problem as  post number 136 in page 10 (I would post the link, but I'm not allowed).

Seems like it is not compiling in Arduino 19. I tried out the soluton proposed in the next post, but it didn't help smiley-sad

EDIT: Ok, it's because it doesn't work on ATmega328...
« Last Edit: November 09, 2010, 04:45:45 am by Lennyh » Logged

Brazil
Offline Offline
God Member
*****
Karma: 3
Posts: 616
Wusik Dot Com
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Guys, how do I get this working with the Arduino Mega (Atmega1280) Thanks.
Logged


Offline Offline
Sr. Member
****
Karma: 0
Posts: 445
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

H there,

First of all, thanls so much for this great tutorial. Some weeks ago i developed my own SD Card shield and it runs perfectly.

However, now i have a problem: sometimes it does not write data into the SD.

Let me explain. I made a datalogger based on a RTC ds1337 and a SD card wired such as showed in this topic. No apparenty it is not the problem.
I have the arduino sleeping most of the time, and ones per hour the rtc get up the arduino and measure by different senors, and save the data into a SD.

From time to time i remove the SD card from its slot and check the new data. I observed that when i do it (remove and put the SD card into the slot again, it does not save the data). BUT if i remove the slot, but if i remove the power to arduino just immediately after to put the SD card into the slot, OR push the reset button (at the end it is the same)... the next data are saved. :-/

So, i am a little bit lost in this situation. It is not a big problem, because to remove the power and connecting it again is enough, or pushing the reset button but it is not ideal for my project..., right?

I use the filelogger library.

The code is prettly long, so i put here just only the essential lines..

Code:
#include <FileLogger.h>                      // Librería para almacenamiento de dtos en microSD
#include <DallasTemperature.h>               // Librería para el sensor de temperatura DS18B20
#include <OneWire.h>
#include <Wire.h>
#include <DS1337.h>                          // Librería para el RTC DS1307
#include <Sensirion.h>                       // Librería para el sensor de temperatura y humedad SH15
#include <avr/power.h>
#include <avr/sleep.h>                       // Librería para modo dormir del microcontrolado

// Definición de los pin analógicos
#define luz 0                                // Luminosidad LDR
#define suelo 1                              // Humedad del suelo
#define lluvia 2                             // Intensidad de la lluvia
#define bateria 3                            // Voltaje de entrada

// Definición de los pin digitales
#define alarma 2                             // Alarmas del RTC DS1337
#define viento 3                             // Anemómetro QRD1114
#define tempsuelo 4                          // Temperatura del suelo DS18B20
#define temphumdat 5                         // Temperatura/humedad/Punto de rocío SH15
#define temphumcl 6                          // Temperatura-humedad SH15
#define vida 7                               // Led de vida
#define power 8                              // Alimentación de los sensores
#define temp 9                               // Temperatura al sol DS18B20

// Activación de librerías
DS1337 RTC = DS1337();                       // Configuración librería RTC DS1337
OneWire oneWire(temp);                       // Configuración librería termómetro DS18B20
DallasTemperature sensors(&oneWire);
OneWire oneWire2(tempsuelo);                 // Configuración librería termómetro DS18B20
DallasTemperature sensors2(&oneWire2);
DeviceAddress tempDeviceAddress;             // Define la dirección de cada sensor de temperatura
Sensirion SH15 = Sensirion(temphumdat, temphumcl);          

// Definición de constantes
const float pi = 3.14159265;                 // Numero PI
const float volt = 0.0108480556;             // Resolución voltaje de entrada
const int periodo2 = 10000;                  // Periodo de medida del anemómetro (ms)
const int radio = 65;                        // Radio de anemómetro (mm)
const int temp_precision = 12;               // Resolución de los sensores de temperarura (bits)
const int sensibilidad = 30;                 // Sensibilidad del disdrometro
const float area=0.001654;                   // Area de medida del sensor disdrómetro (m^2)

// Definición de variables
long contador = 1;                           // Contador de datos almacenados
unsigned int year = 0000;                    // Año
int month = 00;                              // Mes
int day = 00;                                // Día
int hora = 00;                               // Hora
int minuto = 00;                             // Minuto
int segundo = 00;                            // Segundos
float batt = 0;                              // Voltage de entrada
float innerVcc;                              // Voltaje interno
float innertemp;                             // Temperarura interna
float ambtemp = 0;                           // Temperatura ambiental SH15 (ºC)
float humedad = 0;                           // Humedad ambiental SH15 (%)
float TRocio = 0;                            // Punto de rocio (ºC)
unsigned long BWCounter = 0;                 // Pulsos Blanco/Negro del anemómetro
float velviento = 0;                         // Velocidad del viento (m/s)
long lux = 0;                                // Luminosidad (LUX)
float tempext = 0;                           // Temperatura (ºC)
float suelohum = 0;                          // Humedad del suelo (%)
float TSAr = 0;                              // Temperatura del suelo arriba (ºC)
float TSAb = 0;                              // Temperatura del suelo abajo (ºC)
unsigned long intensidad = 0;                // Intensidad de lluvia (gotas/horas/m2)


void setup(){
  // Inicializacion RTC
  RTC.start();
  // Configuración de la alarma
  RTC.enable_interrupt();
  RTC.setSeconds(55);
  RTC.setMinutes(59);
  RTC.setAlarmRepeat(EVERY_HOUR);
  RTC.writeAlarm();
  pinMode(alarma, INPUT);                   // Receptor de alarmas
  digitalWrite(alarma, HIGH);
  // Configuración de pins
  pinMode(power, OUTPUT);                    // Alimentacion de sensores
  pinMode(vida, OUTPUT);                     // Led de vida
  // Inicializacion del puerto serie
  Serial.begin(9600);                        // Inicia comunicaciones
  // Inicialización de sensores
  sensors.begin();                           // Inicia el sensor de temperatura DS18B20
  sensors2.begin();
  // Mostrar cabecera por puerto serie (*)
  SplashScreen();
}

void loop(){
  digitalWrite(power, HIGH);
  delay(5000);
  digitalWrite(vida, HIGH);                // Enciende el led mientras realiza las lecturas
  tiempo();                                // Toma la hora
  delay(20);
  readVcc();                               // Lee el voltaje interior
  delay(20);
  midebateria();                           // Mide el voltaje de entrada
  delay(20);
  readTemp();                              // Mide la temperatura interna
  delay(20);
  midegotas();                             // Mide la intensidad de lluvia (disdrómetro)
  delay(20);
  temperatura();                           // Mide la temperatura exterior (DS18B20)
  delay(20);
  sueloH();                                // Mide la humedad del suelo
  delay(20);
  suelotemp();                             // Mide la temperatura del suelo
  delay (20);
  temphumroc();                            // Lee temperatura y humedad (SH15) y calcula el punto de rocío
  delay (20);
  luminosidad();                           // Mide la luminosidad (LDR)
  delay  (20);
  velocidadviento();                       // Mide la velocidad del viento (QRD1114)
  mostrar();                             // Muestra los datos a través del puerto serial
  grabar();                              // Graba los datos en formato ascii en un soporte microSD
  delay(5000);
  contador = contador + 1;                 // Actualiza el contador de medidas
  digitalWrite(vida, LOW);                 // Apaga el led al acabar el proceso
  digitalWrite(power, LOW);
  //attachInterrupt(0, Despertar, FALLING);
  delay(500);
  Dormir();
}


void Despertar(){
}

void Dormir(){
  attachInterrupt(0, Despertar, FALLING);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  RTC.enable_interrupt();
  sleep_mode();
  // -->FASE DE BAJO CONSUMO DEL DISPOSITIVO<--
  sleep_disable();
  RTC.disable_interrupt();
  detachInterrupt(0);
}

// Lee el Reloj de Tiempo Real (DS1337)
void tiempo(){
  // Lee el RTC
  RTC.readTime();
  // Memoriza la fecha actual
  day = RTC.getDays();
  month = RTC.getMonths();
  year = RTC.getYears();
  //Memoriza la hora actual
  hora = RTC.getHours();
  minuto = RTC.getMinutes();
  segundo = RTC.getSeconds();
  return;
}

// Lee el voltaje de entrada
float midebateria(){
  batt = (analogRead(bateria))*volt;
  return batt;
}

 

Code follows with other functions to measure the different sensors. I think that they are not essential here...

[Sorry, comments are in Spanish]

So,any idea about what could be the idea and how could i solve it by software or hardware?

Thanks!!
« Last Edit: December 03, 2010, 08:03:52 pm by madepablo » Logged

Newcastle, England
Offline Offline
Sr. Member
****
Karma: 3
Posts: 489
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I've been meaning to intergrate an SD card inot one of my projects a while
ago, only I had no idea how to. Now, all I need is to find somewhere that
sells the SD card holder. I do not have anything to dismantle so I would
have to buy one.
Logged

My website: http://www.harryrabbit.co.uk/electronics/home.html Up and running now! (Feel free to look round!) smiley-grin

Brazil
Offline Offline
God Member
*****
Karma: 3
Posts: 616
Wusik Dot Com
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Here's the one I used:

http://www.sparkfun.com/products/10117



This one is better, but more expensive:

http://www.sparkfun.com/products/204
Logged


Brazil
Offline Offline
God Member
*****
Karma: 3
Posts: 616
Wusik Dot Com
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

And here's the sketch I used to test my SD card with direct write/reading. (no FAT) Its VERY fast to handle the SD card, as I needed speed, and not FAT16 or anything like that.

Code:
/*

  Basic instructions for recording data in an SD Card in native mode
  The SD card (3.3 V) must be properly interfaced to Arduino (5 V)
  Didier Longueville invenit et fecit February 2010
  
  
  Serial 115200
  
*/

// Ports for Arduino Mega //
int PIN_CS = PINB0;      // chip select
int PIN_MOSI = PINB2;    // master out slave in
int PIN_MISO = PINB3;    // master in slave out
int PIN_CLOCK = PINB1;   // clock

int blockPosition = 30;

/********************** SPI SECTION BELOW **********************/

// SPI Variables
byte clr;     // dummy variable used to clear some of the SPI registers
byte spi_err; // SPI timeout flag, must be cleared manually

// send an SPI command, includes time out management
// returns spi_err: "0" is "no error"
byte spi_cmd(volatile char data)
{
  spi_err = 0; // reset spi error
  SPDR = data; // start the transmission by loading the output byte into the spi data register
  int i = 0;
  while (!(SPSR & (1<<SPIF)))
  {
    i++;
    if (i >= 0xFF)
    {
      spi_err = 1;
      return(0x00);
    }
  }
  // returned value
  return(SPDR);
}

// initialize SPI port
void spi_initialize(void)
{
  SPCR = (1<<SPE) | (1<<MSTR); // spi enabled, master mode
  clr = SPSR; // dummy read registers to clear previous results
  clr = SPDR;
}

/********************** SD CARD SECTION BELOW **********************/

// SD Card variables
#define blockSize 512          // block size (default 512 bytes)
byte vBlock[blockSize];        // set vector containing data that will be recorded on SD Card
byte vBuffer[16];

#define GO_IDLE_STATE 0x00     // resets the SD card
#define SEND_CSD 0x09          // sends card-specific data
#define SEND_CID 0x0A          // sends card identification
#define READ_SINGLE_BLOCK 0x11 // reads a block at byte address
#define WRITE_BLOCK 0x18       // writes a block at byte address
#define SEND_OP_COND 0x29      // starts card initialization
#define APP_CMD 0x37           // prefix for application command

// Send a SD command, num is the actual index, NOT OR'ed with 0x40.
// arg is all four bytes of the argument
byte sdc_cmd(byte commandIndex, long arg)
{
  PORTB &= ~(1<<PIN_CS);   // assert chip select for the card
  spi_cmd(0xFF);           // dummy byte
  commandIndex |= 0x40;    // command token OR'ed with 0x40
  spi_cmd(commandIndex);   // send command
  for (int i=3; i>=0; i--)
  {
    spi_cmd(arg>>(i*8));   // send argument in little endian form (MSB first)
  }
  spi_cmd(0x95);           // checksum valid for GO_IDLE_STATE, not needed thereafter, so we can hardcode this value
  spi_cmd(0xFF);           // dummy byte gives card time to process
  byte res = spi_cmd(0xFF);
  return (res);  // query return value from card
}

// initialize SD card
// retuns 1 if successful
byte sdc_initialize(void)
{
  // set slow clock: 1/128 base frequency (125Khz in this case)
  SPCR |=  (1<<SPR1) | (1<<SPR0); // set slow clock: 1/128 base frequency (125Khz in this case)
  SPSR &= ~(1<<SPI2X);            // No doubled clock frequency
  // wake up SD card
  PORTB |=  (1<<PIN_CS);          // deasserts card for warmup
  PORTB |=  (1<<PIN_MOSI);        // set MOSI high
  for(byte i=0; i<10; i++)
  {
    spi_cmd(0xFF);                // send 10 times 8 pulses for a warmup (74 minimum)
  }
  // set idle mode
  byte retries=0;
  PORTB &= ~(1<<PIN_CS);          // assert chip select for the card
  while(sdc_cmd(GO_IDLE_STATE, 0) != 0x01)
  {
    // while SD card is not in iddle state
    retries++;
    if (retries >= 0xFF)
    {
      return(NULL); // timed out!
    }
  }
  // at this stage, the card is in idle mode and ready for start up
  retries = 0;
  sdc_cmd(APP_CMD, 0); // startup sequence for SD cards 55/41
  while (sdc_cmd(SEND_OP_COND, 0) != 0x00)
  {
    retries++;
    if (retries >= 0xFF)
    {
      return(NULL); // timed out!
    }
    sdc_cmd(APP_CMD, 0);
  }
  // set fast clock, 1/4 CPU clock frequency (4Mhz in this case)
  SPCR &= ~((1<<SPR1) | (1<<SPR0)); // Clock Frequency: f_OSC / 4
  SPSR |=  (1<<SPI2X);              // Doubled Clock Frequency: f_OSC / 2
  return (0x01); // returned value (success)
}

// clear block content
void sdc_clearVector(void)
{
  for (int i=0; i<blockSize; i++)
  {
    vBlock[i] = 0;
  }
}

// get nbr of blocks on SD memory card from
long sdc_totalNbrBlocks(void)
{
  sdc_readRegister(SEND_CSD);
  // compute size
  long C_Size = ((vBuffer[0x08] & 0xC0) >> 6) | ((vBuffer[0x07] & 0xFF) << 2) | ((vBuffer[0x06] & 0x03) << 10);
  long C_Mult = ((vBuffer[0x08] & 0x80) >> 7) | ((vBuffer[0x08] & 0x03) << 2);
  return ((C_Size+1) << (C_Mult+2));
}

// read SD card register content and store it in vBuffer
void sdc_readRegister(byte sentCommand)
{
  byte res=sdc_cmd(sentCommand, 0);
  while(res != 0x00) res=spi_cmd(0xFF); // retry

  // wait for data token
  while (spi_cmd(0xFF) != 0xFE);
  // read data
  for (int i=0; i<16; i++)
  {
    vBuffer[i] = spi_cmd(0xFF);
  }
  // read CRC (lost results in blue sky)
  spi_cmd(0xFF); // LSB
  spi_cmd(0xFF); // MSB
}

// write block on SD card
// addr is the address in bytes (multiples of block size)
void sdc_writeBlock(long blockIndex)
{  
  while(sdc_cmd(WRITE_BLOCK, blockIndex * blockSize) != 0x00) { }
  spi_cmd(0xFF); // dummy byte (at least one)
  // send data packet (includes data token, data block and CRC)
  // data token
  spi_cmd(0xFE);
  // copy block data
  for (int i=0; i<blockSize; i++)
  {
    spi_cmd(vBlock[i]);
  }
  // write CRC (lost results in blue sky)
  spi_cmd(0xFF); // LSB
  spi_cmd(0xFF); // MSB
  // wait until write is finished
  while (spi_cmd(0xFF) != 0xFF); // kind of NOP
}

// read block on SD card and copy data in block vector
// retuns 1 if successful
void sdc_readBlock(long blockIndex)
{
  byte res = sdc_cmd(READ_SINGLE_BLOCK,  (blockIndex * blockSize));
  while(res != 0x00) res=spi_cmd(0xFF); // retry
  // read data packet (includes data token, data block and CRC)
  // read data token
  while (spi_cmd(0xFF) != 0xFE);
  // read data block
  for (int i=0; i<blockSize; i++)
  {
    vBlock[i] = spi_cmd(0xFF); // read data
  }
  // read CRC (lost results in blue sky)
  spi_cmd(0xFF); // LSB
  spi_cmd(0xFF); // MSB
}

/********************** MAIN ROUTINES SECTION  BELOW **********************/

void setup()
{
  // Set ports
  // Data in
  DDRB &= ~(1<<PIN_MISO);
  // Data out
  DDRB |=  (1<<PIN_CLOCK);
  DDRB |=  (1<<PIN_CS);
  DDRB |=  (1<<PIN_MOSI);  
  // Initialize serial communication
  Serial.begin(115200);
  // Initialize SPI and SDC
  spi_err=0;        // reset SPI error
  spi_initialize(); // initialize SPI port
  sdc_initialize(); // Initialize SD Card
  Serial.print(sdc_totalNbrBlocks(), DEC);
  Serial.println(" blocks");
  Serial.print("Block Size: ");
  Serial.println(blockSize);
}  

void loop()
{
  unsigned long tx1 = 0;
  unsigned long tx2 = 0;
  
  if (true) // WRITE //
  {
    vBlock[0] = blockPosition;
    vBlock[1] = blockPosition+1;
    vBlock[2] = blockPosition+2;
    tx1 = micros();
    sdc_writeBlock(blockPosition);
    tx2 = micros();
  
    Serial.print("Time to write: ");
    Serial.println(tx2-tx1);
    
    delay(25);
  }
  
  vBlock[0] = 0;
  vBlock[1] = 0;
  vBlock[2] = 0;
  
  tx1 = micros();
  sdc_readBlock(blockPosition);
  tx2 = micros();

  Serial.print("Time to read: ");
  Serial.println(tx2-tx1);
  Serial.print("Values: ");
  Serial.print(vBlock[0]);
  Serial.print(" ");
  Serial.print(vBlock[1]);
  Serial.print(" ");
  Serial.println(vBlock[2]);
  
  delay(400);  
  
  blockPosition++;
}
Logged


0
Offline Offline
Newbie
*
Karma: 0
Posts: 30
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Sorry newbie hear with a dump question again, can I use this file system with my 328 that's within my Arduino for midi file playing.

I not interested in recording any files just playing files that's on a fat 16 or fat 32 SD card.  
Logged

Brazil
Offline Offline
God Member
*****
Karma: 3
Posts: 616
Wusik Dot Com
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Sorry, you will need uFat or something that reads Fat16 files in a SD Card.

Take a look at this:
http://blushingboy.net/p/SDuFAT/

Wk
Logged


0
Offline Offline
Newbie
*
Karma: 0
Posts: 30
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Yes I understand that i will need more hardware, I've done all that now thanks: I was referring to software handling if it would handle it. So your post means it will thanks for that.
Got the software sorted now found what I needed on the net for my MIDI project, it's up and running but I need help with some parts of the programming still, editing mainly. I will be posting my project on this forum soon just need to find a suitable forum/place/thread.  
« Last Edit: December 18, 2010, 04:51:52 am by Popsworld » Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 14
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hello!
Can I use the same voltage divider (1,8 K & 3,3 K resistors) to power SD card, when not using Arduino, but only Atmega chip on breadboard? Or maybe I must put there 3v3 zener diode at the SD side?
Logged

Pages: 1 ... 10 11 [12] 13   Go Up
Jump to: