bool Tune::begin() { // Pin configuration pinMode(DREQ, INPUT_PULLUP); pinMode(XDCS, OUTPUT); pinMode(XCS, OUTPUT); pinMode(SDCS, OUTPUT); // Deselect control & data ctrl digitalWrite(XCS, HIGH); digitalWrite(XDCS, HIGH); // Deselect SD's chip select digitalWrite(SDCS, HIGH); // SD card initialization if (!sd.begin(SDCS, SPI_HALF_SPEED)) { sd.initErrorHalt(); // describe problem if there's one return 0; } // Tracklisting also return the number of playable files Serial.print(listFiles()); Serial.print(" tracks found, "); // SPI bus initialization SPI.begin(); SPI.setDataMode(SPI_MODE0); // Both SCI and SDI read data MSB first SPI.setBitOrder(MSBFIRST); // From the datasheet, max SPI reads are CLKI/6. Here CLKI = 26MHz -> SPI max speed is 4.33MHz. // We'll take 16MHz/4 = 4MHz to be safe. // Plus it's the max recommended speed when using a resistor-based lvl converter with an SD card. SPI.setClockDivider(SPI_CLOCK_DIV4); SPI.transfer(0xFF); delay(10); // Codec initialization // Software reset setBit(SCI_MODE, SM_RESET); delay(5); // VS1022 "New mode" activation setBit(SCI_MODE, SM_SDINEW); // Clock setting (default is 24.576MHz) writeSCI(SCI_CLOCKF, 0x32, 0xC8); delay(5); // Wait until the chip is ready while (!digitalRead(DREQ)); delay(100); // Set playState flag playState = idle; // Set volume to avoid hurt ears ;) setVolume(150); Serial.println("Tune ready !"); return 1; }
/** * Function starts the SD card service and makes sure that the appropriate directory * structure exists, then creates the file to use for logging data. Data will be logged * to a file called fileNamePrefix_0.csv or fileNamePrefix_0.bin (number will be incremented * for each new log file) * * @param chipSelectPin Arduino pin SD card reader CS pin is attached to * @param fileNamePrefix string to prefix at beginning of data file * @param csvData boolean flag whether we are writing csv data or binary data (used for filename) * * @return true if successful, false if failed */ bool beginDataLog(int chipSelectPin, const char *fileNamePrefix, bool csvData) { bool ret; int i = 0; int max_len; char fileName[19]; char prefix[8]; char rootPath[] = "/data"; if (_output_buffer != NULL) { delete []_output_buffer; } OUTPUT_BUF_SIZE = 512; _output_buffer = vol.cacheAddress()->output_buf; if (freeMemory() < 400) { strcpy_P(_getOutBuf(), sd_card_error); Serial.print(_getOutBuf()); Serial.print(freeMemory()); Serial.println(", need 400)"); ret = false; } else { ret = sd.begin(chipSelectPin, SPI_FULL_SPEED); } //Filenames need to fit the 8.3 filename convention, so truncate down the //given filename if it is too long. memcpy(prefix, fileNamePrefix, 7); prefix[7] = '\0'; if (ret) { if (!sd.exists(rootPath)) ret = sd.mkdir(rootPath); if (ret) { while (true) { if (i < 10) { max_len = 7; } else if (i < 100) { max_len = 6; } else if (i < 1000) { max_len = 5; } else { break; } prefix[max_len - 1] = '\0'; sprintf(fileName, "%s/%s%d.%s", rootPath, prefix, i, csvData ? "csv" : "bin"); if (!sd.exists(fileName)) { file = sd.open(fileName, FILE_WRITE); break; } i++; } } } return file.isOpen(); }
void error(String message) { if(self.isInState(Start)) { sd.initErrorPrint(&terminal); } else { sd.errorPrint(&terminal); } terminal.flush(); errorMessage = message; self.transitionTo(Error); }
void fastLog(){ if (blockNum == DATA_DIM-1){ if (!sd.card()->isBusy()){ if (!sd.card()->writeData((uint8_t*)&block)){ error("fast write failed"); } blockNum = 0; } else Serial.println("Card BUSY!"); } else blockNum++; }
void renderError() { Display.setTextColor(RED, BLACK); /***** Error Message *****/ Display.setTextSize(1); Display.setCursor(1, 55); Display.println(errorMessage); if(self.isInState(Start)) { sd.initErrorPrint(&Display); } else { sd.errorPrint(&Display); } }
void enterStart() { // Read configuration from Flash Time.zone(-6); // TODO: store in Flash and add configuration // Display splash screen Display.print("Mane Avis v"); Display.println(MANE_AVIS_VERSION); Display.print("Firmware: "); Display.println(System.version()); // TODO: display a real splash screen // Read alarms from SD card if(sd.exists(STORE)) { digitalWrite(D7, HIGH); if(!store.open(STORE, O_READ)) { error("Failed to open store"); return; } String line; while((line = store.readStringUntil('\r')) != NULL) { alarms.add(line); store.read(); // clear '\n' } } store.close(); digitalWrite(D7, LOW); }
// Get the full path/filename of the GIF file with specified index void getGIFFilenameByIndex(const char *directoryName, int index, char *pnBuffer) { char fname[30]; // Make sure index is in range if ((index < 0) || (index >= numberOfFiles)) return; File directory = sd.open(directoryName); if (!directory) return; File file = directory.openNextFile(); while (file && (index >= 0)) { file.getName(fname, sizeof(fname)); if (isAnimationFile(fname)) { index--; // Copy the directory name into the pathname buffer strcpy(pnBuffer, directoryName); // Append the filename to the pathname strcat(pnBuffer, fname); } file.close(); file = directory.openNextFile(); } file.close(); directory.close(); }
// Enumerate and possibly display the animated GIF filenames in GIFS directory int enumerateGIFFiles(const char *directoryName, boolean displayFilenames) { char fname[30]; numberOfFiles = 0; File directory = sd.open(directoryName); if (!directory) { return -1; } File file = directory.openNextFile(); while (file) { file.getName(fname, sizeof(fname)); Serial.println(fname); if (isAnimationFile(fname)) { numberOfFiles++; if (displayFilenames) { Serial.println(fname); } } file.close(); file = directory.openNextFile(); } file.close(); directory.close(); return numberOfFiles; }
void SDcard::writefile(uint64_t timestamp_sd, int eeprom){ myfile = SD.open("data.txt", FILE_WRITE); if (myfile) { myfile.print("G|"); uint64_t xx = timestamp_sd/1000000000ULL; if (xx >0) myfile.print((long)xx); myfile.print((long)(timestamp_sd-xx*1000000000)); myfile.print("|"); myfile.print(eeprom); myfile.print("|"); for(int i = 0; i<3;i++){ // nombre de capteurs = 3 String data = this->mem->getNext(); myfile.print(data); if (i!=2) myfile.print("|"); } myfile.write('\n'); //myfile.print("|H,"); //myfile.println(value); myfile.close(); } else { Serial.println("error opening data.txt"); } }
void init() { close(); #ifdef SDCARD if (!sd.begin(SD_CS, SPI_FULL_SPEED)) { // error_P("card.init"); return; } #endif }
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 init_SD(){ if (!sd.begin(SDCARD_CSPIN, SPI_HALF_SPEED)) { f.SDCARD = 0; // If init fails, tell the code not to try to write on it debug[1] = 999; } else { f.SDCARD = 1; debug[1] = 000; } }
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 TicketflySDBeacon::SDBeaconSetup (SdFat& SD) { Serial.begin (9600); Serial.print(F("Initializing SD card...")); pinMode(10, OUTPUT); if (!SD.begin(4)) { Serial.println(F("initialization failed!")); return; } Serial.println(F("initialization done.")); }
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; }
// 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; }
void TicketflySDBeacon::writeToSD (String writeThisString, String fileName, SdFat& SD) { File myFile; const char* conversion = fileName.c_str(); Serial.println (conversion); myFile = SD.open(conversion); if (myFile) { myFile.println(writeThisString); myFile.close(); } else { Serial.println(F("error opening example.txt")); } }
boolean delete_handler(AtMegaWebServer& web_server){ const char *path = web_server.get_path(); #if DEBUG Serial << "delete_handler: " << path << '\n'; #endif int len = strlen(path); char *c = (char *)(path + len - 1); if(*c == '/') *c = 0;// remove tailing '/' if(sdfat.remove(path) || sdfat.rmdir(path)){ #if DEBUG Serial << "delete: " << path << '\n'; #endif web_server.sendHttpResult(200); web_server << path; }else{ web_server.sendHttpResult(404); #if DEBUG Serial << F("not exists or failed deleting: ") << path << '\n'; #endif } return true; }
void ScriviSd(void) { int n; n = 0; if (!sd.init(SPI_HALF_SPEED, 10)) { sd.initErrorHalt(); return; } if (!myFile.open("test-1.txt", O_WRITE | O_CREAT | O_APPEND)) { delay(800); digitalWrite(7, LOW); delay(200); digitalWrite(7, HIGH); delay(800); sd.errorHalt("opening test.txt for write failed"); return; } // Serial.println(nMin); // for(n = 0; n < nCount; n++) // { // myFile.print("TIME: "); // myFile.print(nMin); // myFile.print(" min. - VALUE : "); // myFile.print(nValue[n]); myFile.println(" mTesla"); // } // Serial.println("ScriviSd5"); // nCount = 0; // nMin++; myFile.close(); }
void SDcard::readfile(){ // re-open the file for reading: myfile = SD.open("data.txt"); if (myfile) { // read from the file until there's nothing else in it: while (myfile.available()) { Serial.write(myfile.read()); } // close the file: myfile.close(); } else { Serial.println("error opening data.txt"); } }
void SDcard::setup(){ Serial.begin(115200); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } Serial.print("Initializing SD card..."); pinMode(10,OUTPUT); if (!SD.begin(4)) { Serial.println("Initialization failed!"); return; } Serial.println("initialization done."); }
boolean SD_ReadFile(const char *filename) { uint32_t t_arrival = millis(); boolean retVal = false; sdf.chdir(); if (!file.open(filename, O_READ)) { sdf.errorHalt("opening FILE for read failed"); } else { uint32_t len = file.fileSize(); uint8_t index = 0; for(uint32_t i=0; i< len; i++) { int intData = file.read(); char byteData; int base = 10u; //itoa(intData,&byteData,base); // Convert to ASCII buffer[index] = (uint8_t)intData;//byteData; if(index < 63u) { index++; } else { usb_rawhid_send(buffer, 100u); index = 0; } } file.close(); uint32_t t_exit = millis() - t_arrival; buffer[62] = (uint8_t)((t_exit & 0x000000FF)>>8); buffer[63] = (uint8_t)t_exit; usb_rawhid_send(buffer,100u); } }
void TicketflySDBeacon::simpleReadSD (String fileName, SdFat& SD){ File myFile; const char* conversion = fileName.c_str(); myFile = SD.open(conversion, FILE_READ); if (myFile) { while (myFile.available()) { Serial.write(myFile.read()); } myFile.close(); } else { Serial.print(F("Error opening ")); Serial.println (fileName); } }
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; }
// for renaming files and dirs boolean move_handler(AtMegaWebServer& web_server){ const char *path = web_server.get_path(); #if DEBUG Serial << F("move_handler filename: ") << path << '\n'; #endif const char* length_str = web_server.get_header_value("Content-Length"); int len = atoi(length_str); Client& client = web_server.get_client(); int i = 0; int baselen = 0; char* c; if((c = strrchr(path, '/'))) baselen = c - path + 1; char buf[baselen + len + 1]; if(baselen) strncpy(buf, path, baselen); i = baselen; for(; i < (baselen + len) && web_server.waitClientAvailable(); i++) { buf[i] = client.read();// (char) } buf[i] = 0; #if DEBUG Serial << buf << "|end: " << i << '\n'; #endif if(i == (len + baselen)){ if(sdfat.rename(path, buf)){ #if DEBUG Serial << "renaming: " << path << " to: " << buf << '\n'; #endif web_server.sendHttpResult(200); web_server << buf; }else{ #if DEBUG Serial << "renaming: failed\n" << buf << LF; #endif web_server.sendHttpResult(422); } }else{ web_server.sendHttpResult(404); } return true; }
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(); } }
boolean MP3Player::Setup_STA013(void) { byte buf[2]; if (!myFile.open("sta013.cfg", O_READ)) { #if DEBUG sd.errorHalt("cfg file error"); #endif return false; } #if DEBUG Serial.println("setting STA013 from cfgfile"); #endif while (myFile.available()) { buf[0]=byte (myFile.read()); buf[1]=byte (myFile.read()); I2C_Write(buf[0], buf[1]); // Serial.write(buf[0]); // Serial.write(buf[1]); } while(!myFile.close()) { #if DEBUG Serial.println("close cfg file.."); #endif } #if DEBUG Serial.println("Setup STA013 Register Done.."); #endif return true; }
boolean MP3Player::Play(const char* SongName) { if(!PLAY) { k=65; if(!myFile.isOpen()) { // open the file for read if (!myFile.open(SongName, O_READ)) { #if DEBUG sd.errorHalt("open audio file failed"); #endif return false; } } else name = SongName; Run_STA013(); delayMicroseconds(500000); Play_Pause(1); //AMPON(); #if DEBUG Serial.println("playing"); #endif filesize=myFile.fileSize(); Timer1.initialize(30);// 30 us = can check data request and send a byte to STA013 at 1/30u = 33.33kHz // able to play a song up to 33.33 x 8 /1024 = 260 kbps // recommend play song at 200kbps or lower (such as 128 kbps)for stable performance PLAY=true; Timer1.attachInterrupt(Callback); } return true; }
bool TicketflySDBeacon::searchDatabaseForTicket(String TicketString, SdFat& SD){ File myFile; const char* TicketNo = TicketString.c_str(); myFile = SD.open("example.txt"); if (myFile) { char buf[16]; myFile.read(buf, 16); if (strncmp(buf, TicketNo, 14) == 0) { Serial.println(F("Match!")); return true; } else { Serial.println (F("No Match")); return false; } myFile.close(); } else { Serial.println(F("error opening file")); } }
int Tune::play(char* trackName) { if (isPlaying()) return 1; // Exit if track not found if (!track.open(trackName, O_READ)) { sd.errorHalt("Track not found !"); return 3; } playState = playback; // Reset decode time & bitrate from previous playback writeSCI(SCI_DECODE_TIME, 0); delay(100); skipTag(); // Skip ID3v2 tag if there's one feed(); // Feed VS1011e attachInterrupt(0, feed, RISING); // Let the interrupt handle the rest of the process return 0; }