Example #1
0
/*
  Description:
    Requrest for a specific file at a specified position within the directory
    The path argument is identical to the path which was provided to last
    call to "mas_sdfat_move_to_pwd"
*/
uint8_t mas_sdfat_get_nth_file(const char *path, uint16_t n, char *buf, uint8_t *is_dir)
{
  uint16_t c = 0;

  if ( mas_sdfat_move_to_pwd(path) == 0 )
    return 0;
  
  if ( mas_sdfat_file_is_open != 0 )
  {
    mas_sdfat_file.close();
    mas_sdfat_file_is_open = 0;
  }
  
  mas_sdfat_sd->vwd()->rewind();
  while (mas_sdfat_file.openNext(mas_sdfat_sd->vwd(), O_READ)) 
  {
    if ( n == c )
    {
      mas_sdfat_file.getFilename(buf);
      buf[12] = '\0';
      *is_dir = mas_sdfat_file.isDir();
      mas_sdfat_file.close();
      return 1;
    }
    c++;
    mas_sdfat_file.close();
  }
  return 0;
}
Example #2
0
// grafix has to be stored at /gfx/
int speedo_disp::sd2ssd(char filename[10],int frame){
	send_command(0x15);
	send_command(0x00);
	send_command(0x7F);
	send_command(0x75);
	send_command(0x00);
	send_command(0x3F);

	SdFile root;
	SdFile file;
	SdFile subdir;
	root.openRoot(&pSD->volume);

	if(!subdir.open(&root, "gfx", O_READ))    {  return 1; };
	if(!file.open(&subdir, filename, O_READ)) {  return 2; };
	unsigned long frame_seeker=(unsigned long)frame*64*64;
	if(!file.seekSet(frame_seeker))			  {  return 3; }; // ein bild ist 64*64 Byte groß, da wir 64 lines zu je 64*2*4 Bit Breite haben

	uint8_t buf[65];
	//int n;
	//while ((n = file.read(buf, sizeof(byte)*64)) > 0) {
	for (int zeile=0;	(file.read(buf, sizeof(byte)*64)>0)	&& zeile<64;	zeile++ ) {
		for(int j=0;j<64;j++){
			send_char(buf[j]);
		};
	};
	file.close();
	subdir.close();
	root.close();
	return 0;
};
Example #3
0
// this little helper is used to traverse paths
SdFile SDClass::getParentDir(const char *filepath, int *index)
{
	// get parent directory
	SdFile d1 = root; // start with the mostparent, root!
	SdFile d2;

	// we'll use the pointers to swap between the two objects
	SdFile *parent = &d1;
	SdFile *subdir = &d2;

	const char *origpath = filepath;

	while (strchr(filepath, '/'))
	{

		// get rid of leading /'s
		if (filepath[0] == '/')
		{
			filepath++;
			continue;
		}

		if (!strchr(filepath, '/'))
		{
			// it was in the root directory, so leave now
			break;
		}

		// extract just the name of the next subdirectory
		uint8_t idx = strchr(filepath, '/') - filepath;
		if (idx > 12)
			idx = 12; // dont let them specify long names
		char subdirname[13];
		strncpy(subdirname, filepath, idx);
		subdirname[idx] = 0;

		// close the subdir (we reuse them) if open
		subdir->close();
		if (!subdir->open(parent, subdirname, O_READ))
		{
			// failed to open one of the subdirectories
			return SdFile();
		}
		// move forward to the next subdirectory
		filepath += idx;

		// we reuse the objects, close it.
		parent->close();

		// swap the pointers
		SdFile *t = parent;
		parent = subdir;
		subdir = t;
	}

	*index = (int) (filepath - origpath);
	// parent is now the parent diretory of the file!
	return *parent;
}
idigi_callback_status_t iDigiFileSystem::app_process_file_stat(idigi_file_stat_request_t * const request_data,
                                                     idigi_file_stat_response_t * const response_data)
{
    idigi_file_stat_t *pstat = &response_data->statbuf;
    idigi_callback_status_t status = idigi_callback_continue;

    SdFile entry = DigiSD.open(request_data->path);

    if (!entry.isOpen())
    {
     	APP_DEBUG("stat cannot open: %s\n", request_data->path);
        goto done;   	
    }

    pstat->last_modified = 0;					// Last modified date unsupported:
    pstat->hash_alg = idigi_file_hash_none;	// File hash not supported
    pstat->file_size = (size_t) entry.fileSize();
    pstat->flags = 0;
    if (entry.isDir())
    	pstat->flags |= IDIGI_FILE_IS_DIR;
    else
    	pstat->flags |= IDIGI_FILE_IS_REG;

    entry.close();

done:
    return status;
}
void HAL::syncEEPROM() { // store to disk if changed
  millis_t time = millis();

  if (eprSyncTime && (time - eprSyncTime > 15000)) // Buffer writes only every 15 seconds to pool writes
  {
    eprSyncTime = 0;
    bool failed = false;
    if (!sd.sdactive) // not mounted
	  {
		  if (eepromFile.isOpen())
			  eepromFile.close();
        Com::printErrorF("Could not write eeprom to sd card - no sd card mounted");
        Com::println();
		  return;
	  }

	  if (!eepromFile.seekSet(0))
		  failed = true;

	  if(!failed && !eepromFile.write(virtualEeprom, EEPROM_BYTES) == EEPROM_BYTES)
      failed = true; 
    
    if(failed) {
        Com::printErrorF("Could not write eeprom to sd card");
        Com::println();
    }
  }
}
Example #6
0
void LogTemps(){
   if (!file.open(root, filename, O_CREAT | O_APPEND | O_WRITE)) {
     //error(“open”);
   }
   
// write values to the file

          sensorsa.requestTemperatures(); 
          sensorsb.requestTemperatures(); 
          sensorsc.requestTemperatures(); 
          sensorsd.requestTemperatures(); 
          

file.print(now() );
file.print("|");
file.print(sensorsa.getTempCByIndex(0));
file.print("|");
file.print(sensorsb.getTempCByIndex(0));
file.print("|");
file.print(sensorsc.getTempCByIndex(0));
file.print("|");
file.print(sensorsd.getTempCByIndex(0));
file.print("\n");

if (!file.close() || file.writeError){
 // error(“close/write”);
}
  
}
Example #7
0
int WiFiCmdRobot::WiFiSendPicture (int16_t n)
{
  int ret=SUCCESS;
  int16_t nbytes; 
  uint8_t buf[PAYLOAD_SIZE];
  char filename[12+1];
 
  Serial.print("n: ");
  Serial.println(n);
  
  // Open the file
  sprintf(filename, "PICT%02d.jpg", n);
  if (!FilePicture.open(&root, filename, O_READ)) return FILE_OPEN_ERROR;  

  Serial.print("Open file: ");
  Serial.println(filename);

  // read from the file until there's nothing else in it:
  while ((nbytes = FilePicture.read(buf, sizeof(buf))) > 0 && ret == SUCCESS) {
       for (unsigned int idx = 0; idx<nbytes;idx++)
       {
           tcpClient.print(buf[idx]);
       }
 
  }// while
  
  //Close file
  if (!FilePicture.close()) return FILE_CLOSE_ERROR;  
  
  return SUCCESS;
}
// Enumerate and possibly display the animated GIF filenames in GIFS directory
int enumerateGIFFiles(const char *directoryName, boolean displayFilenames) {

    numberOfFiles = 0;

    // Set the current working directory
    if (! sd.chdir(directoryName, true)) {
        sd.errorHalt("Could not change to gifs directory");
    }
    sd.vwd()->rewind();

    char fn[13];
    while (file.openNext(sd.vwd(), O_READ)) {
        file.getName(fn, 13);
        // If filename not deleted, count it
        if (fn[0] != '_') {
            numberOfFiles++;
            if (displayFilenames) {
                Serial.println(fn);
                delay(20);
            }
        }
        file.close();
    }
    // Set the current working directory
    if (! sd.chdir("/", true)) {
        sd.errorHalt("Could not change to root directory");
    }
    return numberOfFiles;
}
Example #9
0
void readSettings() {
	int n,cc;
	char ch, buff[24];
	char  buff2[80];
	unsigned int ndx=0;
	int read=0;
    if (!settingsFile.open(&root, settingsFileName, O_READ)) {
        console.printf("DBG: Creating New Settings File\r\n"); console.flush();
        writeSettings();
        return;
	}
    console.printf("DBG: Opened Settings File: %s\r\n",settingsFileName);
	settingsFile.seekSet(0);
	while ((read=settingsFile.read(buff, sizeof(buff))) > 0) {
        //console.printf("DBG: READ %d\r\n",read); console.flush();
        for (cc=0; cc < read ; cc++) {
            
            ch=buff[cc];
            //console.putChar(ch); console.flush();
            buff2[ndx]=ch;
            if (ndx<MAX_INPUT_LINE) {ndx++;}
            if (ch=='\n'){//console.putChar('\r');
                if(ndx) {
                    ndx--; // eat the newline.
                }
                buff2[ndx]='\0';
                //console.puts(buff2);
                if ((ndx>4) && buff2[3]=='!') {//fix this when the files are better
                    buff2[3]='\0';
                    n=lookupIndex(buff2);
                    switch (n) {
                        case _NPW_:
                            networkSetPassword(buff2+4);
                            break;
                        case _NJN_:
                            Watchdog_Reset();
                            networkJoin(buff2 +4);
                            break;
                        case _PKY_:
                            strncpy(pachubeKey, buff2+4, MAX_PATCHUBE_KEY_LENGHT-1);
                            break;
                        case _PFD_:
                            strncpy(pachubeFeed, buff2+4, MAX_PATCHUBE_FEED_LENGHT-1);
                            break;
                        default:
                            break;
                    }
                    
                }
            
                ndx=0; 

            }
        }
    }
    
    console.printf("DBG: Finished with Settings File: %s\r\n",settingsFileName);
    
	settingsFile.close();
}
Example #10
0
  /**
   * Get a long pretty path based on a DOS 8.3 path
   */
  void CardReader::printLongPath(char *path) {
    lsAction = LS_GetFilename;

    int i, pathLen = strlen(path);

    // SERIAL_ECHOPGM("Full Path: "); SERIAL_ECHOLN(path);

    // Zero out slashes to make segments
    for (i = 0; i < pathLen; i++) if (path[i] == '/') path[i] = '\0';

    SdFile diveDir = root; // start from the root for segment 1
    for (i = 0; i < pathLen;) {

      if (path[i] == '\0') i++; // move past a single nul

      char *segment = &path[i]; // The segment after most slashes

      // If a segment is empty (extra-slash) then exit
      if (!*segment) break;

      // Go to the next segment
      while (path[++i]) { }

      // SERIAL_ECHOPGM("Looking for segment: "); SERIAL_ECHOLN(segment);

      // Find the item, setting the long filename
      diveDir.rewind();
      lsDive("", diveDir, segment);

      // Print /LongNamePart to serial output
      SERIAL_PROTOCOLCHAR('/');
      SERIAL_PROTOCOL(longFilename[0] ? longFilename : "???");

      // If the filename was printed then that's it
      if (!filenameIsDir) break;

      // SERIAL_ECHOPGM("Opening dir: "); SERIAL_ECHOLN(segment);

      // Open the sub-item as the new dive parent
      SdFile dir;
      if (!dir.open(diveDir, segment, O_READ)) {
        SERIAL_EOL;
        SERIAL_ECHO_START;
        SERIAL_ECHOPGM(MSG_SD_CANT_OPEN_SUBDIR);
        SERIAL_ECHO(segment);
        break;
      }

      diveDir.close();
      diveDir = dir;

    } // while i<pathLen

    SERIAL_EOL;
  }
Example #11
0
File: SD.cpp Project: Defragster/SD
File SDClass::open(const char *filepath, uint8_t mode) {
  /*

     Open the supplied file path for reading or writing.

     The file content can be accessed via the `file` property of
     the `SDClass` object--this property is currently
     a standard `SdFile` object from `sdfatlib`.

     Defaults to read only.

     If `write` is true, default action (when `append` is true) is to
     append data to the end of the file.

     If `append` is false then the file will be truncated first.

     If the file does not exist and it is opened for writing the file
     will be created.

     An attempt to open a file for reading that does not exist is an
     error.

   */

  int pathidx;

  // do the interative search
  SdFile parentdir = getParentDir(filepath, &pathidx);
  // no more subdirs!

  filepath += pathidx;

  if (! filepath[0]) {
    // it was the directory itself!
    return File(parentdir, "/");
  }

  // Open the file itself
  SdFile file;

  // failed to open a subdir!
  if (!parentdir.isOpen())
    return File();

  if ( ! file.open(parentdir, filepath, mode)) {
    return File();
  }
  // close the parent
  parentdir.close();

  if (mode & (O_APPEND | O_WRITE)) 
    file.seekSet(file.fileSize());
  return File(file, filepath);
}
  boolean put_handler(AtMegaWebServer& web_server) {
	const char* length_str = web_server.get_header_value("Content-Length");
	long length = atol(length_str);
	const char *path = web_server.get_path();

	SdFile file;
	if(!file.open(path, O_CREAT | O_WRITE | O_TRUNC)){
		 // maybe the folder must be created
		char *c = strrchr(path, '/');
		if(c){
			*c = 0;
			if(sdfat.mkdir(path)){
#if DEBUG
				Serial << "put_handler make DIR: ok " << path <<'\n';
#endif
				*c = '/';
				if(!file.open(path, O_CREAT | O_WRITE | O_TRUNC)){
#if DEBUG
					Serial << "put_handler open FILE: failed " << path <<'\n';
#endif
				}
			}
			*c = '/';
		}
	}
	if(file.isOpen()){

		EthernetClient client = web_server.get_client();
		long size = 0;
		int read = 0;
		while(size < length && web_server.waitClientAvailable()){
			read = client.read((uint8_t*)buffer, sizeof(buffer));
			file.write(buffer, read);
			size += read;
		}
		file.close();
#if DEBUG
		Serial << "file written: " << size << " of: " << length << '\n';
#endif
		if(size < length){
			web_server.sendHttpResult(404);
		}else{
			web_server.sendHttpResult(200);
			web_server << path;
		}

	}else{
		web_server.sendHttpResult(422); // assuming it's a bad filename (non 8.3 name)
#if DEBUG
		Serial << F("put_handler open file failed: send 422 ") << path <<'\n';
#endif
	}
	return true;
  }
void loop() { 
  uint32_t t;
  double r;

  Serial.println("Type any character to start");
  while (!Serial.available()) SPARK_WLAN_Loop();
  while (Serial.available()) Serial.read();

  // open or create file - truncate existing file.
  if (!file.open(&root, "BENCH.DAT", O_CREAT | O_TRUNC | O_RDWR)) {
    error("open failed");
  }
  // fill buf with known data
  for (uint16_t i = 0; i < (BUF_SIZE-2); i++) {
    buf[i] = 'A' + (i % 26);
  }
  buf[BUF_SIZE-2] = '\r';
  buf[BUF_SIZE-1] = '\n';
  Serial.print("File size ");
  Serial.print(FILE_SIZE_MB);
  Serial.println(" MB");
  uint32_t n = FILE_SIZE/sizeof(buf);
  Serial.println("Starting write test.  Please wait up to a minute");
  // do write test
  t = millis();
  for (uint32_t i = 0; i < n; i++) {
    if (file.write(buf, sizeof(buf)) != sizeof(buf)) {
      error("write failed");
    }
  }
  t = millis() - t;
  file.sync();
  r = (double)file.fileSize()/t;
  Serial.print("Write ");
  Serial.print(r);
  Serial.println(" kB/sec");
  Serial.println();
  Serial.println("Starting read test.  Please wait up to a minute");
  // do read test
  file.rewind();
  t = millis();
  for (uint32_t i = 0; i < n; i++) {
    if (file.read(buf, sizeof(buf)) != sizeof(buf)) {
      error("read failed");
    }
  }
  t = millis() - t;
  r = (double)file.fileSize()/t;
  Serial.print("Read ");
  Serial.print(r);
  Serial.println(" kB/sec");
  Serial.println("Done");
  file.close();
}
Example #14
0
void HAL::importEEPROM() {
    if (eepromFile.isOpen())
			eepromFile.close();
		if (!eepromFile.open("eeprom.bin", O_RDWR | O_CREAT | O_SYNC) ||
			eepromFile.read(virtualEeprom, EEPROM_BYTES) != EEPROM_BYTES)
		{
			Com::printFLN(Com::tOpenFailedFile, "eeprom.bin");
		} else {
      Com::printFLN("EEPROM read from sd card.");
    }
    EEPROM::readDataFromEEPROM(true);
}
// Get the full path/filename of the GIF file with specified index
void getGIFFilenameByIndex(const char *directoryName, int index, char *pnBuffer) {

    char filename[13];

    // Make sure index is in range
    if ((index >= 0) && (index < numberOfFiles)) {

        // Set the current working directory
        if (! sd.chdir(directoryName, true)) {
            sd.errorHalt("Could not change to gifs directory");
        }

        // Make sure file is closed before starting
        file.close();

        // Rewind the directory to the beginning
        sd.vwd()->rewind();

        while ((file.openNext(sd.vwd(), O_READ)) && (index >= 0)) {

            file.getName(filename, 13);

            // If filename is not marked as deleted, count it
            if ((filename[0] != '_') && (filename[0] != '~')) {
                index--;
            }
            file.close();
        }
        // Set the current working directory back to root
        if (! sd.chdir("/", true)) {
            sd.errorHalt("Could not change to root directory");
        }
        // Copy the directory name into the pathname buffer
        strcpy(pnBuffer, directoryName);

        // Append the filename to the pathname
        strcat(pnBuffer, filename);
    }
}
idigi_callback_status_t iDigiFileSystem::app_process_file_close(idigi_file_request_t * const request_data,
                                                      idigi_file_response_t * const response_data)
{
    idigi_callback_status_t status = idigi_callback_continue;
    SdFile *file = (SdFile *) request_data->handle;

    file->close();

    APP_DEBUG("close %p\n", (void *) file);
    free(file);

    return status;
}
idigi_callback_status_t iDigiFileSystem::app_process_file_closedir(idigi_file_request_t * const request_data,
                                                         idigi_file_response_t * const response_data)
{
    SdFile *dir = (SdFile *) request_data->handle;

    APP_DEBUG("closedir %p\n", (void *) dir);

    if (dir->isOpen())
    	dir->close();
    free(dir);

    return idigi_callback_continue;
}
Example #18
0
int wctx(long flen)
{
  int thisblklen;
  int sectnum, attempts, firstch;
  long charssent;
  
//DSERIAL.println("\nwctx");

  charssent = 0;  
  firstsec=TRUE;  
  thisblklen = blklen;
  vfile(F("wctx:file length=%ld"), flen);

  while ((firstch=readline(Rxtimeout))!=NAK && firstch != WANTCRC
    && firstch != WANTG && firstch!=TIMEOUT && firstch!=CAN)
    ;
  if (firstch==CAN) {
    zperr("Receiver CANcelled");
    return ERROR;
  }
  if (firstch==WANTCRC)
    Crcflg=TRUE;
  if (firstch==WANTG)
    Crcflg=TRUE;
  sectnum=0;
  for (;;) {
    if (flen <= (charssent + 896L))
      thisblklen = 128;
    if ( !filbuf(txbuf, thisblklen))
      break;
    if (wcputsec(txbuf, ++sectnum, thisblklen)==ERROR)
      return ERROR;
    charssent += thisblklen;
  }
  //fclose(in);
  fout.close();
  attempts=0;
  do {
    purgeline();
    sendline(EOT);
    //fflush(stdout);
    ++attempts;
  }
  while ((firstch=(readline(Rxtimeout)) != ACK) && attempts < Tx_RETRYMAX);
  if (attempts == Tx_RETRYMAX) {
    zperr("No ACK on EOT");
    return ERROR;
  }
  else
    return OK;
}
Example #19
0
bool FileSystem::initSDCard() {
    boolean status;

    if (root.isOpen())
        root.close();      // allows repeated calls

    // First, detect the card
    status = card.init(pinCS); // Audio shield has SD card SD on pin 10
    if (status) {
        Serial.println("SD card is connected :-)");
    } else {
        Serial.println("SD card is not connected or unusable :-(");
        sdCardInitialized = false;
        return sdCardInitialized;
    }

    // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
    if (!volume.init(card)) {
        Serial.println(
                "Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
        sdCardInitialized = false;
        return sdCardInitialized;
    }

    root.openRoot(volume);

    // print the type and size of the first FAT-type volume
    Serial.print("\nVolume type is FAT");
    Serial.println(volume.fatType(), DEC);
    Serial.println();

    float size = volume.blocksPerCluster() * volume.clusterCount();
    size = size * (512.0 / 1e6); // convert blocks to millions of bytes
    Serial.print("File system space is ");
    Serial.print(size);
    Serial.println(" Mbytes.");

    status = SD.begin(pinCS); // Audio shield has SD card CS on pin 10
    if (status) {
        Serial.println("SD library is able to access the filesystem");
    } else {
        Serial.println("SD library can not access the filesystem!");
        Serial.println(
                "Please report this problem, with the make & model of your SD card.");
        Serial.println(
                "  http://forum.pjrc.com/forums/4-Suggestions-amp-Bug-Reports");
    }
    sdCardInitialized = true;
    return sdCardInitialized;
}
Example #20
0
boolean callback_pathExists(SdFile& parentDir, char *filePathComponent, 
			    boolean isLastComponent, void *object) {
  /*
  */
  SdFile child;

  boolean exists = child.open(parentDir, filePathComponent, O_RDONLY);
  
  if (exists) {
     child.close(); 
  }
  
  return exists;
}
  boolean get_handler(AtMegaWebServer& web_server){
	const char* filename = web_server.get_path();
#if DEBUG
	Serial << F("file_handler path: ") << filename << '\n';
#endif

  if (!filename) {
    web_server.sendHttpResult(404);
#if DEBUG
    Serial << F("Could not parse URL");
#endif
    return true;
  }

  if(filename[0] == '/' && filename[1] == 0){ // root dir, file.open() will fail
    listDirectory(web_server, SdBaseFile::cwd());
	return true;
  }

  SdFile file;
  if(file.open(filename, O_READ)){
#if DEBUG
     Serial << "file isOpen: " << filename << '\n';
#endif
	  if (file.isDir())
	  {
		listDirectory(web_server, &file);
	  }
	  else
	  {
		AtMegaWebServer::MimeType mime_type
		  = AtMegaWebServer::get_mime_type_from_filename(filename);

  // If you want to send a file with a non-supported MimeType you can:
  // web_server.sendHttpResult(200, 0, "Content-Type: image/tiff" CRLF);

        web_server.sendHttpResult(200, mime_type);
#if DEBUG
		Serial << F("Read file ");
		Serial.println(filename);
#endif
		web_server.send_file(file);
	  }
	  file.close();
    }else{
      web_server.sendHttpResult(404);
    }
    return true;
}
Example #22
0
uint16_t mas_sdfat_get_directory_file_cnt(const char *path)
{
  uint8_t cnt;
  cnt = 0;
  
  if ( mas_sdfat_move_to_pwd(path) == 0 )
    return 0;

  if ( mas_sdfat_file_is_open != 0 )
  {
    mas_sdfat_file.close();
    mas_sdfat_file_is_open = 0;
  }
  
  mas_sdfat_sd->vwd()->rewind();
  while (mas_sdfat_file.openNext(mas_sdfat_sd->vwd(), O_READ)) 
  {
    cnt++;
    mas_sdfat_file.close();
    if ( cnt == 0x0ffff )
      break;
  }
  return cnt;
}
Example #23
0
bool change_to_dir(const char *dir)
{
  SdFile newdir;
  bool result = false;
  //Goto parent directory
  //@NOTE: This is a fix to make this work. Should be replaced with
  //proper handling. Limitation: setting::max_folder_depth subfolders
  //ERROR  if (strcmp_P(dir, F("..")) == 0) {

  if (strcmp_P(dir, PSTR("..")) == 0) {
    result = true;
    currentDirectory.close();
    if (!currentDirectory.openRoot(&volume)) {
       systemError(error_code::root_init);
    }
    int8_t index = getNextFolderTreeIndex() - 1;
    if (index >= 0) {
      for (int8_t iTemp = 0; iTemp < index; iTemp++){
        result = newdir.open(&currentDirectory, folderTree[iTemp], O_READ);
        if (!result){
            break;
        }
        currentDirectory = newdir; //Point to new directory
        newdir.close();
      }
      memset(folderTree[index], 0, 11);
    }
    if (((feedback_mode & setting::extended_info) > 0) && (result == false)){
      NewSerial.print(F("cannot cd to parent directory: "));
      NewSerial.println(dir);
    }
  }else {
    result = newdir.open(&currentDirectory, dir, O_READ);
    if (!result) {
      if ((feedback_mode & setting::extended_info) > 0){
        NewSerial.print(F("directory not found: "));
        NewSerial.println(dir);
      }
    }else {
      currentDirectory = newdir; //Point to new directory
      int8_t index = getNextFolderTreeIndex();
      if (index >= 0){
        strncpy(folderTree[index], dir, 11);
      }
    }
  }
  return result;
}
Example #24
0
void setup(void) {
  Serial.begin(BPS_115200);
  Serial.println();
  PgmPrintln("Type any character to start");
  while (!Serial.available());
  
  //PgmPrint("FreeRam: ");
  //Serial.println(FreeRam());
  
  // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
  // breadboards.  use SPI_FULL_SPEED for better performance.
  if (!card.init(SPI_HALF_SPEED)) error("card.init failed");

  // initialize a FAT volume
  if (!volume.init(&card)) error("volume.init failed");

  // open the root directory
  if (!root.openRoot(&volume)) error("openRoot failed");
  
  strcpy_P(buf, PSTR("APPEND.TXT"));
  // open for read
  if (!from.open(&root, buf, O_READ)) {
    PgmPrint("Can't open "); 
    Serial.println(buf);
    PgmPrintln("Run the append example to create the file.");
    error("from.open failed");
  }
  strcpy_P(buf, PSTR("ACOPY.TXT"));
  // create if needed, truncate to zero length, open for write
  if (!copy.open(&root, buf, O_CREAT | O_TRUNC | O_WRITE)) {
    error("copy.open failed");
  }
  // count for printing periods
  uint16_t p = 0;
  int16_t n;  
  while ((n = from.read(buf, sizeof(buf))) > 0) {
    if (copy.write(buf, n) != n) error("write failed");
    // print progress periods
    if (!(p++ % 25)) Serial.print('.');
    if (!(p % 500)) Serial.println();
  }
  Serial.println();
  if (n != 0) error ("read");
  // force write of directory entry and last data
  if (!copy.close()) error("copy.close failed");
  PgmPrintln("Copy done.");
}
Example #25
0
uint16_t SD_NumberOfFiles(void)
{
    uint16_t fileCount = 0;

    buffer[0] = 0x01;
    usb_rawhid_send(buffer, 100);
    while(file.openNext(sdf.vwd(), O_READ))
    {
        fileCount++;

        buffer[0]++;
        usb_rawhid_send(buffer, 100);

    }
    file.close();
    return fileCount;
}
Example #26
0
uint32_t SD_GetFileSize(void)
{
    uint32_t retVal = 0;
    //TEST.TXT
    sdf.chdir();	// Change directory to root
    // OPEN the file for reading:
    if (!file.open("TEST.TXT", O_READ)) {
        sdf.errorHalt("opening FILE for read failed");
    }
    else
    {
        retVal = file.fileSize();
        file.close();

    }

    return retVal;
}
void MP3Player::Halt()
{
	Timer1.detachInterrupt();
	PLAY=false; 
	while(!myFile.close())
	{
	   #if DEBUG
	   Serial.println("close audio file");
	   #endif 
	}
	//AMPSHUTDOWN();
	#if DEBUG
    Serial.println("finish");
	#endif 
	delayMicroseconds(100000);
	name = "";
	  if(isPlayAll)
		PlayTrack("",0,"");
}
Example #28
0
boolean callback_pathExists(SdFile& parentDir, char *filePathComponent, 
			    boolean isLastComponent, void *object) {
  /*

    Callback used to determine if a file/directory exists in parent
    directory.

    Returns true if file path exists.

  */
  SdFile child;

  boolean exists = child.open(parentDir, filePathComponent, O_RDONLY);
  
  if (exists) {
     child.close(); 
  }
  
  return exists;
}
Example #29
0
void SD_ListFiles(void)
{

    Serial.begin(9600);
    while (!Serial) {}
    delay(1000);
    Serial.println();
    while (file.openNext(sdf.vwd(), O_READ)) {
        file.printFileSize(&Serial);
        Serial.write(' ');
        file.printModifyDateTime(&Serial);
        Serial.write(' ');
        file.printName(&Serial);
        if (file.isDir()) {
            // Indicate a directory.
            Serial.write('/');
        }
        Serial.println();
        file.close();
    }
}
Example #30
0
File: main.cpp Project: keax/SdFat
int main()
{

	// initialize the SD card at SPI_FULL_SPEED for best performance.
	// try SPI_HALF_SPEED if bus errors occur.
	if (!sd.begin(SD_ENABLE_PIN, SPI_FULL_SPEED)) sd.initErrorHalt();


	if (!myFile.open("test.txt", O_RDWR | O_CREAT | O_AT_END)) {
		sd.errorHalt("opening test.txt for write failed");
	}

	myFile.println("testing 1, 2, 3.");

	// close the file:
	myFile.close();

	while (1);

	return 0;
}