Arduino y 2 SD a la vez - AYUDA -

Buenos días, soy nuevo en este foro y vengo necesitando ayuda urgente o ideas que me hagan salir de esta frustración que tengo... explico... estoy obteniendo los valores de un sensor de temperatura para guárdalos en una sd, ahi me funciona perfecto pero.. no deseo una, sino guardar en 2 a la vez... compre el modulo catalex v1 (link: http://www.ebay.com/itm/Micro-SD-TF-Card-Storage-Memory-Module-For-Arduino-SPI-Level-conversion-TOP-/321461876510?pt=LH_DefaultDomain_0&hash=item4ad89ef71e) entiendo que se comunican por SPI con el arduino, estoy utilizando el esquema de la imagen que dejo adjunto... utilizo un mega2560 y comprendo que los pines 50-MISO, 51-MOSI y 52-SCK.. El ss los tengo definido en el 40 y 41 para la sd1 y sd2 respectivamente.. que ocurre... que me guarda solo en una, pero al guardarlo en la segunda me envia erro de inciacion sd, no se que ocurre ya que al usar la primera defino metodos para controlar los pines para que no existan los dos SD a la vez por comunicacion SPI:

void Ac_eXT1(){

pinMode(SD1, OUTPUT);
digitalWrite(SD1, LOW);
pinMode(PIN_SD2,OUTPUT);
digitalWrite(PIN_SD2, HIGH);

}

Y al usar la sd 2 uso el metodo:

void Ac_eXT1(){

pinMode(SD1, OUTPUT);
digitalWrite(SD1, HIGH);
pinMode(PIN_SD2,OUTPUT);
digitalWrite(PIN_SD2, LOW);

}

pero no me funciona... solo copia en la primera y la segunda me marca error de inicio

ambas funcionan ya que hize las pruebas conectandolas sola...

alguien podria ayudarme con comunicacion de dos tragetas SD por sSPI en arduino mega?

11351559_10153372890871703_548024873_n.jpg

Esta todo bien salvo que: SS es activo bajo, y debes garantizar que SS en los demas dispostivos este disable usando un resistor de 10K a 5V cosa que no se si trae tu placa. Verifica eso por favor.

Las definiciones se hacen en el setup, no en todo momento.

pon en el setup

void setup(){
  pinMode(SD1, OUTPUT);
  pinMode(SD2, OUTPUT);
  // mas lo que haga falta
}

luego las habilitas con tu procedimiento

void Ac_eXT1(){
 digitalWrite(SD2, HIGH); // deshabilita SD2
 digitalWrite(SD1, LOW);  // habilita SD1
}

void Ac_eXT2(){
 digitalWrite(SD1, HIGH); // deshabilita SD1
 digitalWrite(SD2, LOW);   // habilita SD2
}

Creo que te complicas la vida. Con inicializar las 2 SD con nombres distintos y cada una con su correspondiente pin de SS, tiene que ser suficiente. La librería ya se encargará de seleccionar la que uses en cada momento. No tienes que seleccionarla tu de esa forma.

Edito: Lo acabo de probar, y tengo problemas para inicializar la segunda SD, ya que no es posible hacer 2 inits, porque creía recordar que en el init de la SD, se le asignaba un nombre, pero no es así. Es un init genérico.

El problema reside en que, aunque tu cambies el estado de los pins, detrás vendrá la librería SD y lo volverá a cambiar.
Pruebo más cosas y te comento.

Definitivamente, no encuentro una forma fácil de hacerlo. Lo único que se me ocurre, es usar un arduino por cada SD, que se comuniquen por serial para pasar la información de uno a otro, y que cada uno grabe en su SD.

Por otro lado, ¿es absolutamente necesario grabar en dos tarjetas SD? Puedes grabar en una sola, en dos archivos distintos...

En unas horas estare probando comunicando 2 arduinos por serial..para que uno guarde en la otra sd, estaba pensando en unsar un mini, minipro... pero aun no me decido, hare pruebas con mi arduino mega y uno xD.. cameloco si necesario porque necesito a la SD 1 entrar solo yo.. digamos que la SD 2 la puedo extender con unos cable y llevarla un poco mas lejos y que sea accedida por otro usuario ajeno al sistema :slight_smile: es la idea, una SD SOLAMENTE la controlo yo y la otra pues es ocmo quien dice publica..saludos a todos, y gracias por comentar, surbyte no sabia lo de definirlos en el setup.. intentare eso tambien :).. comentare mas tarde

Hola.
Puedes intentar a ver si con este código puedes manejar dos SD a la vez. Básicamente es el ejemplo read/write duplicado. El objeto SD ya viene definido en la librería, así que lo aprovecho, y creo además otro SD1 para intentar manejar la segunda SD. No lo puedo comprobar, aunque sí compila.

/*
  SD card read/write

 This example shows how to read and write data to and from an SD card file
 The circuit:
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4

 created   Nov 2010
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe

 This example code is in the public domain.

 */

#include <SPI.h>
#include <SD.h>

SDClass SD1;

File myFile, myFile1;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }


  Serial.print("Initializing SD card0...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  Serial.print("Initializing SD card1...");

  if (!SD1.begin(5)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }


  myFile1 = SD1.open("test.txt", FILE_WRITE);
  // if the file opened okay, write to it:
  if (myFile1) {
    Serial.print("Writing to test.txt on SD1...");
    myFile1.println("testing 1, 2, 3.");
    // close the file:
    myFile1.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile1 = SD1.open("test.txt");
  if (myFile1) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile1.available()) {
      Serial.write(myFile1.read());
    }
    // close the file:
    myFile1.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }


}

void loop()
{
  // nothing happens after setup
}

EDITADO: he corregido algunas erratas, aunque pudiera haber quedado alguna confusión entre sd y sd1 o myfile y myfile1

Bueno yo no me he extendido como carmeloco o noter porque supuse que inicialización y demás estarían bien.
Por eso se debe publicar siempre todo el código y no parcialmente.
El problema comandando dos dispositivos SPI esta siempre en tener las lineas SS debidamente activas cuando es debido y para ello, el dispositivo debe permitir usar algun PIN distinto de 4 o 10.
Como acá se habla de dos SD, supongo que no tendremos ese problema y entonces una debe estar con el PIN 10 y la otra SD con el pin 4.
Esto es fundamental y debe asegurarse que ambas queden desactivadas PIN en HIGH cuando se definen enel setup

void setup(){
  pinMode(SD1, OUTPUT);
  pinMode(SD2, OUTPUT);
  digitalWrite(SD1, HIGH);
  digitalWrite(SD2, HIGH);
  // mas lo que haga falta
}

Acá pueden ver una nota muy bien escrita en la que explican esto que menciono.
Running multiple slave devices on arduino SPI BUs

noter, he probado tu código, y pasa algo un poco raro. En la SD nunca escribe nada, aunque no da error, en cambio en la SD1 si que escribe.

He modificado el código para que se diferencia completamente entre SD1 y SD2, pero sigue sin funcionar.

/*
  SD card read/write

 This example shows how to read and write data to and from an SD card file
 The circuit:
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4

 created   Nov 2010
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe

 This example code is in the public domain.

 */

#include <SPI.h>
#include <SD.h>

SDClass SD1;
SDClass SD2;

File MyFile1, MyFile2;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  Serial.print("Initializing SD card1...");
  if (!SD1.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
  Serial.print("Initializing SD card2...");
  if (!SD2.begin(5)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  MyFile1 = SD1.open("SD1.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (MyFile1) {
    Serial.print("Writing to SD1.txt on SD1...");
    MyFile1.println("SD1 text");
    // close the file:
    MyFile1.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening-write SD1.txt");
  }
  // re-open the file for reading:
  MyFile1 = SD1.open("SD1.txt");
  if (MyFile1) {
    Serial.println("SD1.txt:");
    // read from the file until there's nothing else in it:
    while (MyFile1.available()) {
      Serial.write(MyFile1.read());
    }
    // close the file:
    MyFile1.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening SD1.txt");
  }
  MyFile2 = SD2.open("SD2.txt", FILE_WRITE);
  // if the file opened okay, write to it:
  if (MyFile2) {
    Serial.print("Writing to SD2.txt on SD2...");
    MyFile2.println("SD2 text");
    // close the file:
    MyFile2.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening-write SD2.txt");
  }
  // re-open the file for reading:
  MyFile2 = SD2.open("SD2.txt");
  if (MyFile2) {
    Serial.println("SD2.txt:");
    // read from the file until there's nothing else in it:
    while (MyFile2.available()) {
      Serial.write(MyFile2.read());
    }
    // close the file:
    MyFile2.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening SD2.txt");
  }
}

void loop()
{
  // nothing happens after setup
}

surbyte, en el código de noter, se inicializan las dos SD en los pines 4 y 5

En todos lados dicen que si no se usa PIN 10 y no se pone en HIGH hay problemas.
Al menos inicializarlo como OUTPUT y luego ponerlo en HIGH.

surbyte:
En todos lados dicen que si no se usa PIN 10 y no se pone en HIGH hay problemas.
Al menos inicializarlo como OUTPUT y luego ponerlo en HIGH.

Eso, normalmente, se hace para que no haya problemas, si usas el módulo SD de los shields ethernet o wifi, ya que si no pones el pin 10 en HIGH, no deshabilitas la parte ethernet o wifi del shield.

En un módulo SD independiente, esto no aplica.

Tiene razón surbyte en lo del pin 10 (o 53 en el mega), ya que si no se pone como salida no se habilita el SPI, aunque supongo que la propia librería lo hace, pues una de las SD funciona. Prueba a ver si con este código diferencia las dos tarjetas:

#include <SPI.h>
#include <SD.h>

// set up variables using the SD utility library functions:
Sd2Card card1, card2;
SdVolume volume1, volume2;
SdFile root1, root2;

const int chipSelect1 = 4, chipSelect2 = 5;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }


  Serial.print("\Inicializando tarjetas...");

  if (!card1.init(SPI_HALF_SPEED, chipSelect1)) {
    Serial.println("Error al inizializar card1");
    return;
  } else {
    Serial.println("Card1 OK.");
  }
  if (!card2.init(SPI_HALF_SPEED, chipSelect2)) {
    Serial.println("Error al inizializar card2");
    return;
  } else {
    Serial.println("Card2 OK.");
  }

  // print the type of card
  Serial.print("\nCard1 type: ");
  switch (card1.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }
  Serial.print("\nCard2 type: ");
  switch (card2.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume1.init(card1)) {
    Serial.println("Error al abrir Volumen1");
    return;
  }
  if (!volume2.init(card2)) {
    Serial.println("Error al abrir Volumen2");
    return;
  }


  uint32_t volumesize;


  Serial.print("\nVolume1 type is FAT");
  Serial.println(volume1.fatType(), DEC);
  Serial.println();

  volumesize = volume1.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume1.clusterCount();       // we'll have a lot of clusters
  volumesize *= 512;                            // SD card blocks are always 512 bytes
  Serial.print("Volume1 size (bytes): ");
  Serial.println(volumesize);
  Serial.print("Volume1 size (Kbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume1 size (Mbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);


  Serial.print("\nVolume2 type is FAT");
  Serial.println(volume2.fatType(), DEC);
  Serial.println();

  volumesize = volume2.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume2.clusterCount();       // we'll have a lot of clusters
  volumesize *= 512;                            // SD card blocks are always 512 bytes
  Serial.print("Volume2 size (bytes): ");
  Serial.println(volumesize);
  Serial.print("Volume2 size (Kbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume2 size (Mbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);


  Serial.println("\nFiles found on the card1 (name, date and size in bytes): ");
  root1.openRoot(volume1);

  // list all files in the card with date and size
  root1.ls(LS_R | LS_DATE | LS_SIZE);


  Serial.println("\nFiles found on the card2 (name, date and size in bytes): ");
  root2.openRoot(volume2);

  // list all files in the card with date and size
  root2.ls(LS_R | LS_DATE | LS_SIZE);
}


void loop(void) {

}

No lo hace.. muchos videos hay al respecto que recomiendan si no se usa PIN 10 que se defina como salida y luego se ponga en HIGH.

En un rato pruebo tu nuevo código noter.

Lo que no entiendo es lo del pin 10, ya que el ejemplo ReadWrite que viene con el IDE para la librería SD, no lleva lo del pin 10, y funciona perfectamente.

OK, este el codigo completo que estoy usando, mi logica me dice que deberia funcionar pero no lo esta haciendo, por eso esta frustracion... les recuerdo que estoy usando un arduino mega :c ... no se porque falla...

50 MISO
51 MOSI
52 SCK

// UTILIZANDO ARDUINO MEGA

#define SEGUNDA_SD 39 
#define PRIMERA_SD 38

#include <SPI.h>
#include <SD.h>

File myFile_sd_primera;
File myFile_sd_segunda;

SDClass sd_primera;
SDClass sd_segunda;

void setup() {
  //Se desactiva el pin 53 del arduino mega ya que por defecto esta esperando un dispositivo spi
  pinMode(53,OUTPUT); 
  digitalWrite(53,HIGH);
  // SD 
  pinMode(PRIMERA_SD, OUTPUT);  
  pinMode(SEGUNDA_SD, OUTPUT); 
  digitalWrite(PRIMERA_SD, HIGH);  
  digitalWrite(SEGUNDA_SD, HIGH);   
  Serial.begin(9600);
  
}

void loop() {

  while (!Serial) {}
  Serial.println("Ingrese tantos caracteres como escritura desea...");
  while (Serial.read() <= 0) {}
  delay(400); 
  ESCRIBIR_PRIMERA_SD();
  ESCRIBIR_SEGUNDA_SD();
  
}

void ESCRIBIR_PRIMERA_SD(){

  digitalWrite(PRIMERA_SD, LOW); 
  digitalWrite(SEGUNDA_SD, HIGH); 

  Serial.print("Iniciando SD 1... ");
  if (!sd_primera.begin(PRIMERA_SD)) {
    Serial.println("Fallido!");
    return;
  }
  Serial.println("Exito!.");
  myFile_sd_primera = sd_primera.open("SD1.txt", FILE_WRITE);
  // si no hay problemas en el archivo, entonces escribir
  if (myFile_sd_primera) {
    Serial.print("Escribiendo en SD1.txt...");
    myFile_sd_primera.println("testing 1, 2, 3.");
  // cerramos archivo
    myFile_sd_primera.close();
    Serial.println(" OK.");
  } else {
    // si no se pudo abrir el archivo:
    Serial.println("Error al abrir archivo SD1.txt");
  }
}

void ESCRIBIR_SEGUNDA_SD(){

  digitalWrite(SEGUNDA_SD, LOW); 
  digitalWrite(PRIMERA_SD, HIGH); 

  Serial.print("Iniciando SD 2... ");
  if (!sd_segunda.begin(PRIMERA_SD)) {
    Serial.println("Fallido!");
    return;
  }
  Serial.println("Exito!.");
  myFile_sd_segunda = sd_segunda.open("SD2.txt", FILE_WRITE);
  // si no hay problemas en el archivo, entonces escribir
  if (myFile_sd_segunda) {
    Serial.print("Escribiendo en SD2.txt...");
    myFile_sd_segunda.println("testing 1, 2, 3.");
  // cerramos archivo
    myFile_sd_segunda.close();
    Serial.println(" OK.");
  } else {
    // si no se pudo abrir el archivo:
    Serial.println("Error al abrir archivo SD2.txt");
  }
}

saludos a todos, me ocurre lo que publicaron anteriormente, me escribe en una en la otra no, o sino incializa una pero la otra no :confused:

Bueno, yo estoy usando un Arduino Uno para las pruebas, y después de ver cosas muy raras por la consola serie, decido usar dos tarjetas SD idénticas (estaba usando dos tarjetas distintas), pero con un archivo .txt distinto en cada una, y obtengo este resultado:

Inicializando tarjetas...Card1 OK.
Card2 OK.

Card1 type: SDHC

Card2 type: SDHC

Volume1 type is FAT32

Volume1 size (bytes): 3988783104
Volume1 size (Kbytes): 3895296
Volume1 size (Mbytes): 3804

Volume2 type is FAT32

Volume2 size (bytes): 3988783104
Volume2 size (Kbytes): 3895296
Volume2 size (Mbytes): 3804

Files found on the card1 (name, date and size in bytes): 
TEST-SD1.TXT  2015-06-17 18:44:14 8

Files found on the card2 (name, date and size in bytes): 
TEST-SD1.TXT  2015-06-17 18:44:14 8

¿Cómo? Pero si cada tarjeta tiene un archivo con nombre distinto. Entonces, intercambio los cables de los SS de cada módulo SD y veo esto:

Inicializando tarjetas...Card1 OK.
Card2 OK.

Card1 type: SDHC

Card2 type: SDHC

Volume1 type is FAT32

Volume1 size (bytes): 3988783104
Volume1 size (Kbytes): 3895296
Volume1 size (Mbytes): 3804

Volume2 type is FAT32

Volume2 size (bytes): 3988783104
Volume2 size (Kbytes): 3895296
Volume2 size (Mbytes): 3804

Files found on the card1 (name, date and size in bytes): 
TEST-SD2.TXT  2015-06-17 18:21:56 8

Files found on the card2 (name, date and size in bytes): 
TEST-SD2.TXT  2015-06-17 18:21:56 8

Con lo que llego a la conclusión de que solo está leyendo la tarjeta de uno de los dos módulos, pero ambos módulos funcionan y ambas tarjetas funcionan (descarto un problema adicional de hardware).

Pues mucho me temo que la librería sólo va a permitir tener abierto un solo archivo/volumen/SD simultáneamente.
Tal vez se pueda hacer algo así, aunque no será lo mismo:

#include <SPI.h>
#include <SD.h>


void setup()
{
  Serial.begin(9600);
  test(4);
  test(5);
}

void loop()
{
  
}

void test(int pin){
  File myFile;

  if (!SD.begin(pin)) {
    Serial.println("initialization failed!");
    return;
  }
  myFile = SD.open("test.txt", FILE_WRITE);

  if (myFile) {
    char myBuff[20];
    sprintf(myBuff, "Escribiendo en %d", pin);
    myFile.println(myBuff);
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    char myBuff[20];
    sprintf(myBuff, "Test.txt en SD%",pin);
    Serial.println(myBuff);
    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }  
}

Bueno revisando un poco la libreria, es cierto lo que dice el amigo noter, al parecer solo se puede usar un solo sd/archivo/volumen... intentare comunicacion por serial con otro arduino y les cuento.. creen que se puede usar con un Arduino ProMini o Nano? cual de los dos seria mejor?

No deberías tener ninguna diferencia.
SOn exactamente como el UNO.

muy buenas
igual llego un poco tarde pero creo que se me ha ocurrido una posible solución.
la librería sd solo deja inicializar una única tarjeta por lo que al realizar la inicialización en el setup (una detrás de la otra) solo reconoce la una de ellas. para solventarlo he pensado en inicializarlas en el loop.
NOTA: el código lo he creado para escribir en dos sd de forma selectiva (yo decido en cual mediante un selector) no creo que sea difícil cambiarlo para lo que quieres. solo ten en cuenta que parece que la inicialización de cada una de ellas conlleva bastante tiempo de ciclo.

//inclusion de las librerias necesarias

#include<SD.h>//libreria para el empleo de tarjetas SD

/pines para el protocolo SPI no hace falta declararlos pero para tenerlos en cuenta
MISO-->Pin 50
MOSI-->Pin 51
SCK -->Pin 52
SS -->Pin 53
/

/en vez de usar el pin 53 usaremos el 49 y el 48
pero el 53 ha de quedar como salida
/

//comenzamos con la asignacion de pines

const int selector_tarjeta_1=5;
const int selector_tarjeta_2=6;
const int tarjeta_2=48;
const int tarjeta_1=49;
const int led_tarjeta_1=3;
const int led_tarjeta_2=4;

void setup(){

Serial.begin(9600);

//definimos las entradas

pinMode(selector_tarjeta_1,INPUT);
pinMode(selector_tarjeta_2,INPUT);
pinMode(2,INPUT);

//acivamos las PULLUP de las entradas para activarlas por nivel bajo

digitalWrite(2,HIGH);
digitalWrite(selector_tarjeta_1,HIGH);
digitalWrite(selector_tarjeta_2,HIGH);

//definimos las salidas

pinMode(tarjeta_1,OUTPUT);
pinMode(tarjeta_2,OUTPUT);
pinMode(led_tarjeta_1,OUTPUT);
pinMode(led_tarjeta_2,OUTPUT);
pinMode(53,OUTPUT);

//dejamos las salidas en su estado de reposo normal

digitalWrite(tarjeta_1,HIGH);//para seleccionar esta tarjeta se pondria la salida a nivel bajo
digitalWrite(tarjeta_2,HIGH);//para seleccionar esta tarjeta se pondria la salida a nivel bajo
digitalWrite(led_tarjeta_1,LOW);
digitalWrite(led_tarjeta_2,LOW);

//la inicialezacion de la tarjeta se realizará dentro del loop

}

void activar_tarjeta_1(){
desactivar_tarjeta_2();
do {
SD.begin(tarjeta_1);
}
while(!SD.begin(tarjeta_1));
digitalWrite(led_tarjeta_1,HIGH);
}

void desactivar_tarjeta_1(){
digitalWrite(led_tarjeta_1,LOW);
digitalWrite(tarjeta_1,HIGH);
}

void activar_tarjeta_2(){
desactivar_tarjeta_1();
do {
SD.begin(tarjeta_2);
}
while(!SD.begin(tarjeta_2));
digitalWrite(led_tarjeta_2,HIGH);
}

void desactivar_tarjeta_2(){
digitalWrite(led_tarjeta_2,LOW);
digitalWrite(tarjeta_2,HIGH);
}

void loop(){

//comprobamos si hemos activado la tarjeta y la inicializamos

if(digitalRead(selector_tarjeta_1)==LOW&&digitalRead(led_tarjeta_1)==LOW){
activar_tarjeta_1();
}

if(digitalRead(selector_tarjeta_2)==LOW&&digitalRead(led_tarjeta_1)==LOW){
activar_tarjeta_2();
}

if(digitalRead(selector_tarjeta_1)==HIGH&&digitalRead(selector_tarjeta_2)==HIGH&&(digitalRead(led_tarjeta_1)==HIGH||digitalRead(led_tarjeta_2)==HIGH)){
desactivar_tarjeta_1();
desactivar_tarjeta_2();
}

if(digitalRead(led_tarjeta_1)==HIGH||digitalRead(led_tarjeta_2)==HIGH){

File dataFile=SD.open("valores.txt",FILE_WRITE);
if (dataFile){

dataFile.println("dato");
dataFile.close();

}
}

}