Pages: [1]   Go Down
Author Topic: Need help to input variables to SD card built in function.  (Read 570 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 36
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hello, I need to dynamically change the directory or file name in the SD.open() [ex. SD.open("/0/file.txt") ] function. I tried String typecasting into the function but I get an error. I need to dynamically change which directory I'm opening based on an externally inputted variable while the Arduino is running in the wild. For example, if the number I get in the wild is 1,2,3 I would need a way to do this SD.open(1/2/3); without having to hard code the "1/2/3" argument in the function.
I tried typecasting the variables as a String, char, and char* but none of these worked and produced errors. If you know of a way to dynamically change the directory on the fly then that would be very much appreciated!
Thanks, here's my code.

Code:
#include <SD.h>
byte SD_CS = 4;
File test_file;
void setup(){
 Serial.begin(9600); //open serial port
 
 Serial.println("Initializing SD Card");
 pinMode(SD_CS, OUTPUT); //CS for SD card
 pinMode(10, OUTPUT); //CS must be an output for SPI to work
 
 if(!SD.begin(SD_CS)){
 Serial.println("SD card initialization failed");
 return;
 }
 
 Serial.println("SD card ready");
 
 test_file = SD.open(String(/0/test.txt), FILE_WRITE); //this line causes problems
}

void loop(){
 
}
Logged

Massachusetts, USA
Offline Offline
Tesla Member
***
Karma: 180
Posts: 8081
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
char filename[50];
int filenameIndex = 0;

filename[filenameIndex++] = '/';  // Root directory

int input = Serial.read();
if (input >= '0' && input <= '9')
    filename[filenameIndex++] = input;
 
if (input == ',')
    filename[filenameIndex++] = '/';


...


   strcpy(filename+filenameIndex, "filename.txt"); // Add the filename (and null terminator)
   test_file = SD.open(filename, FILE_WRITE);
Logged

Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

Offline Offline
Newbie
*
Karma: 0
Posts: 36
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks! However I don't understand what the "filename+filenameIndex" means in: strcpy(filename+filenameIndex, "filename.txt");
« Last Edit: May 05, 2013, 08:52:51 pm by ebird97 » Logged

Massachusetts, USA
Offline Offline
Tesla Member
***
Karma: 180
Posts: 8081
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks! However I don't understand what the "filename+filenameIndex" means in: strcpy(filename+filenameIndex, "filename.txt");

It means the same as "&filename[filenameIndex]" which means "address of the element in filename at index filenameIndex".
Logged

Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

Pages: [1]   Go Up
Jump to: