int load_wav ( FIL *fp, /* Pointer to the open file object to play */ const char *title, /* Title (file name, etc...) */ void *work, /* Pointer to working buffer (must be-4 byte aligned) */ UINT sz_work /* Size of working buffer (must be power of 2) */ ) { UINT md, wi, br, tc, t, btr; DWORD sz, ssz, offw, szwav, wsmp, fsmp, eof; WAVFIFO fcb; BYTE k, *buff = work; char *p, nam[NBSIZE], art[NBSIZE]; //xprintf(PSTR("%s\n"), title); /* Put title */ /* Is it a WAV file? */ if (f_read(fp, buff, 12, &br) || br != 12) return -1; if (LD_DWORD(&buff[0]) != FCC('R','I','F','F')) return -1; if (LD_DWORD(&buff[8]) != FCC('W','A','V','E')) return -1; eof = LD_DWORD(&buff[4]) + 8; /* Analyze the RIFF-WAVE header and get properties */ nam[0] = art[0] = 0; md = fsmp = wsmp = offw = szwav = 0; while (f_tell(fp) < eof) { if (f_read(fp, buff, 8, &br) || br != 8) return -1; sz = (LD_DWORD(&buff[4]) + 1) & ~1; switch (LD_DWORD(&buff[0])) { case FCC('f','m','t',' ') : if (sz > 1000 || sz < 16 || f_read(fp, buff, sz, &br) || sz != br) return -1; if (LD_WORD(&buff[0]) != 0x1) return -1; /* Check if LPCM */ if (LD_WORD(&buff[2]) == 2) { /* Channels (1 or 2) */ md = 1; wsmp = 2; } else { md = 0; wsmp = 1; } if (LD_WORD(&buff[14]) == 16) { /* Resolution (8 or 16) */ md |= 2; wsmp *= 2; } fsmp = LD_DWORD(&buff[4]); /* Sampling rate */ break; case FCC('f','a','c','t') : f_lseek(fp, f_tell(fp) + sz); break; case FCC('d','a','t','a') : offw = f_tell(fp); /* Wave data start offset */ szwav = sz; /* Wave data length [byte] */ f_lseek(fp, f_tell(fp) + sz); break; case FCC('L','I','S','T'): sz += f_tell(fp); if (f_read(fp, buff, 4, &br) || br != 4) return -1; if (LD_DWORD(buff) == FCC('I','N','F','O')) { /* LIST/INFO chunk */ while (f_tell(fp) < sz) { if (f_read(fp, buff, 8, &br) || br != 8) return -1; ssz = (LD_DWORD(&buff[4]) + 1) & ~1; p = 0; switch (LD_DWORD(buff)) { case FCC('I','N','A','M'): /* INAM sub-chunk */ p = nam; break; case FCC('I','A','R','T'): /* IART sub-cnunk */ p = art; break; } if (p && ssz <= NBSIZE) { if (f_read(fp, p, ssz, &br) || br != ssz) return -1; } else { if (f_lseek(fp, f_tell(fp) + ssz)) return -1; } } } else { if (f_lseek(fp, sz)) return -1; /* Skip unknown sub-chunk type */ } break; default : /* Unknown chunk */ return -1; } } if (!szwav || !fsmp) return -1; /* Check if valid WAV file */ if (f_lseek(fp, offw)) return -1; /* Seek to top of wav data */ tc = (UINT)(szwav / fsmp / wsmp); /* Length (sec) */ //xprintf(PSTR("IART=%s\nINAM=%s\n"), art, nam); //xprintf(PSTR("Sample=%u.%ukHz/%ubit/%S\nLength=%u:%02u\n"), (UINT)(fsmp / 1000), (UINT)(fsmp / 100) % 10, (md & 2) ? 16 : 8, (md & 1) ? PSTR("st") : PSTR("mo"), tc / 60, tc % 60); /* Initialize stream parameters and start sound streming */ fcb.mode = md; fcb.buff = buff; fcb.sz_buff = sz_work; if (!sound_start(&fcb, fsmp)) return -1; k = 0; wi = 0; while (szwav || fcb.ct >= 4) { if (szwav && fcb.ct <= sz_work / 2) { /* Refill FIFO when it gets half empty */ btr = (szwav >= sz_work / 2) ? sz_work / 2 : szwav; f_read(fp, &buff[wi], btr, &br); if (br != btr) break; szwav -= br; wi = (wi + br) & (sz_work - 1); cli(); fcb.ct += br; sei(); } //if (uart_test()) { /* Exit if a command arrived */ // k = uart_getc(); // break; //} if (btn_check_press() == BTN2) { sound_stop(); break; } t = (f_tell(fp) - offw - fcb.ct) / fsmp / wsmp; /* Refresh time display every 1 sec */ if (t != tc) { tc = t; //xprintf(PSTR("\rTime=%u:%02u"), tc / 60, tc % 60); } } sound_stop(); /* Stop sound output */ //xputc('\n'); return k; /* Terminated due to -1:error, 0:eot, >0:key code */ }
void Tape_Routine() { static FIL tapeFile; static dword headerSize = 0; static dword dataSize = 0; const int LOOPS_SIZE = 0x10; static CTapeLoop loops[LOOPS_SIZE]; static int loopsSize; if (!tapeStarted && tapeFile.fsize != 0 && tapeFile.fptr >= tapeFile.fsize) { tapeRestart = true; } if (tapeStarted && (tapeFile.fsize == 0 || tapeRestart)) { if (f_open(&tapeFile, tapePath, FA_READ) == FR_OK) { //__TRACE( "Tape openned...\n" ); f_lseek(&tapeFile, 0); tapeTzx = false; headerSize = 0; dataSize = 0; loopsSize = 0; if (tapeFile.fsize >= 10) { char buff[10]; UINT res; f_read(&tapeFile, buff, 10, &res); if (res == 10 && buff[0] == 'Z' && buff[1] == 'X' && buff[2] == 'T') tapeTzx = true; else f_lseek(&tapeFile, 0); } } else { __TRACE("Cannot open tape file %s...\n", tapePath); tapeStarted = false; } tapeRestart = false; } static byte header[0x20]; static dword headerPos; while (tapeStarted && tapeFifo.GetFree() > 0) { if (headerSize > 0) { tapeFifo.WriteByte(header[headerPos++]); headerSize--; continue; } if (dataSize > 0) { byte data; UINT res; f_read(&tapeFile, &data, 1, &res); if (res == 1) { tapeFifo.WriteByte(data); dataSize--; continue; } else { tapeStarted = false; break; } } if (tapeFile.fptr >= tapeFile.fsize) { tapeFinished = true; break; } UINT res; f_read(&tapeFile, header, 1, &res); if (res != 1) { tapeFinished = true; break; } byte hs = GetHeaderSize(header[0]); f_read(&tapeFile, header + 1, hs - 1, &res); if (res + 1 != hs) { tapeFinished = true; break; } CTapeBlock temp; temp.ParseHeader(header); if (temp.tape_pilot > 0 || temp.tape_sync > 0 || temp.tape_pause > 0 || (temp.data_size > 0 && temp.data_type != SKIP_DATA)) { headerPos = 0; headerSize = hs; dataSize = temp.data_size; } else if (header[0] == 0x24) { if (loopsSize < LOOPS_SIZE) { loops[loopsSize].fptr = tapeFile.fptr; loops[loopsSize].counter = ReadWord(header + 1); loopsSize++; } } else if (header[0] == 0x25) { if (loopsSize > 0) { if (loops[loopsSize - 1].counter > 0) loops[loopsSize - 1].counter--; if (loops[loopsSize - 1].counter > 0) f_lseek(&tapeFile, loops[loopsSize - 1].fptr); else loopsSize--; } } else { //__TRACE( "0x%.4x - 0x%.2x - skip\n", tapeFile.fptr - hs, header[0] ); f_lseek(&tapeFile, tapeFile.fptr + temp.data_size); } } while (tapeStarted && SystemBus_Read(0xc00015) == 0) { if (Tape_FillBuffer() == false) break; } }
int load_cakes_info(const char *dirpath) { FRESULT fr; DIR dir; FILINFO fno; FIL handle; const int pathlen = strlen(dirpath); static char lfn[_MAX_LFN + 1]; fno.lfname = lfn; fno.lfsize = sizeof(lfn); fr = f_opendir(&dir, dirpath); if (fr != FR_OK) goto error; static_assert(MAX_CAKES < 0x100000 / sizeof(struct cake_info), "This function will overflow it's buffer"); while (cake_count < MAX_CAKES) { fr = f_readdir(&dir, &fno); if (fr != FR_OK) { goto error; } else if (fno.fname[0] == 0) { break; } char *fn = *fno.lfname ? fno.lfname : fno.fname; // Build the path string memcpy(cake_list[cake_count].path, dirpath, pathlen); cake_list[cake_count].path[pathlen] = '/'; strncpy(&cake_list[cake_count].path[pathlen + 1], fn, sizeof(cake_list->path) - pathlen - 1); // Recurse into subdirectories if (fno.fattrib & AM_DIR) { // Using the path stored in the current cake. fr = load_cakes_info(cake_list[cake_count].path); if (fr != FR_OK) return fr; continue; } // Make sure the filename ends in .cake if (!memsearch(cake_list[cake_count].path, ".cake", sizeof(cake_list[cake_count].path), 6)) { continue; } // Open the file fr = f_open(&handle, cake_list[cake_count].path, FA_READ); if (fr != FR_OK) goto error; // Get the header unsigned int bytes_read = 0; struct cake_header header; fr = f_read(&handle, &header, sizeof(header), &bytes_read); if (fr != FR_OK) goto error; // Only add patches applicable to the loaded firms struct firm_signature *current = NULL; switch (header.type) { case NATIVE_FIRM: current = current_firm; break; case AGB_FIRM: current = current_agb_firm; break; default: continue; } if (!current || header.firm_ver != current->version || header.console != current->console) { continue; } // Get the patch description const int desc_size = header.patches_offset - sizeof(header); fr = f_read(&handle, cake_list[cake_count].description, desc_size, &bytes_read); if (fr != FR_OK) goto error; fr = f_close(&handle); if (fr != FR_OK) goto error; cake_count++; } f_closedir(&dir); return 0; error: f_close(&handle); f_closedir(&dir); return fr; }
FRESULT LoadAllKeyXFromFile() { char fpath[_MAX_LFN + 1]; char *p; long keyslot; u8 key[AES_BLOCK_SIZE]; FILINFO fno; FRESULT r; FIL f; DIR d; UINT br; r = f_opendir(&d, dir); if (r == FR_NO_PATH) return FR_OK; else if (r != FR_OK) return r; fno.lfname = NULL; while (1) { r = f_readdir(&d, &fno); if (r != FR_OK) { Debug("Failed to read directory %s: %d", dir, r); f_closedir(&d); return r; } if (fno.fname[0] == 0) break; keyslot = strtol(fno.fname, &p, 16); if (strcmp(p, SUFFIX)) continue; snprintf(fpath, _MAX_LFN, "%s/%s", dir, fno.fname); r = f_open(&f, fpath, FA_READ); if (r) { Debug("Failed to open %s: %d", fpath, r); f_closedir(&d); return r; } r = f_read(&f, key, sizeof(key), &br); if (r) { Debug("Failed to read %s: %d", fpath, r); f_close(&f); f_closedir(&d); return r; } if (br < sizeof(key)) { Debug("%s is too small. expected: %d, result: %d", fpath, br, sizeof(key)); f_close(&f); f_closedir(&d); return -1; } f_close(&f); setup_aeskeyX(keyslot, key); } f_closedir(&d); return FR_OK; }
int main(void) { setvbuf(stdin, NULL, _IONBF, 0); setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stderr, NULL, _IONBF, 0); f3d_uart_init(); delay(10); f3d_delay_init(); delay(10); f3d_lcd_init(); delay(10); f3d_i2c1_init(); delay(10); f3d_accel_init(); delay(10); f3d_nunchuk_init(); delay(10); f3d_timer2_init(); delay(10); f3d_dac_init(); delay(10); f3d_rtc_init(); delay(10); f3d_systick_init(); delay(10); nunchuk_t nunc; nunchuk_t *nun = &nunc; int music = 0; const int fileNum = 3; char *musicFile[fileNum]; musicFile[0] = "thermo.wav"; musicFile[1] = "mario.wav"; musicFile[2] = "ting.wav"; printf("Reset\n"); //set up screen f3d_lcd_fillScreen(WHITE); f3d_lcd_drawString(37, 0, musicFile[0], RED, WHITE); f3d_lcd_drawString(37, 20 * 1, musicFile[1], BLUE, WHITE); f3d_lcd_drawString(37, 20 * 2, musicFile[2], BLUE, WHITE); f3d_lcd_drawString(33, 80, "WAV Player", BLACK, WHITE); f3d_lcd_drawString(43, 100, "sijlee", BLACK, WHITE); f3d_lcd_drawString(48, 120, "sp21", BLACK, WHITE); f_mount(0, &Fatfs);/* Register volume work area */ f3d_nunchuk_read(nun); while(1) { f3d_nunchuk_read(nun); int lastSelect = music; //nunchuk to right if (nun->jx == 255) { music = (music + 1) % 3; f3d_lcd_drawString(37, lastSelect * 20, musicFile[lastSelect], BLUE, WHITE); f3d_lcd_drawString(37, music * 20, musicFile[music], RED, WHITE); //nunchuk to left } else if (nun->jx == 0) { music = (music + 2) % 3; f3d_lcd_drawString(37, lastSelect * 20, musicFile[lastSelect], BLUE, WHITE); f3d_lcd_drawString(37, music * 20, musicFile[music], RED, WHITE); } //when selected, play music! if (nun->z) { FRESULT rc; /* Result code */ DIR dir; /* Directory object */ FILINFO fno; /* File information object */ UINT bw, br; unsigned int retval; int bytesread; printf("\nOpen %s\n", musicFile[music]); rc = f_open(&fid, musicFile[music], FA_READ); printf("opened file with rc: %d\n", rc); if (!rc) { printf("Success opening file\n"); struct ckhd hd; uint32_t waveid; struct fmtck fck; readckhd(&fid, &hd, 'FFIR'); f_read(&fid, &waveid, sizeof(waveid), &ret); if ((ret != sizeof(waveid)) || (waveid != 'EVAW')) return -1; readckhd(&fid, &hd, ' tmf'); f_read(&fid, &fck, sizeof(fck), &ret); // skip over extra info if (hd.cksize != 16) { printf("extra header info %d\n", hd.cksize - 16); f_lseek(&fid, hd.cksize - 16); } printf("audio format 0x%x\n", fck.wFormatTag); printf("channels %d\n", fck.nChannels); printf("sample rate %d\n", fck.nSamplesPerSec); printf("data rate %d\n", fck.nAvgBytesPerSec); printf("block alignment %d\n", fck.nBlockAlign); printf("bits per sample %d\n", fck.wBitsPerSample); // now skip all non-data chunks ! while(1){ printf("skipping all non-data chunks\n"); readckhd(&fid, &hd, 0); if (hd.ckID == 'atad') break; f_lseek(&fid, hd.cksize); } printf("Samples %d\n", hd.cksize); // Play it ! // audioplayerInit(fck.nSamplesPerSec); f_read(&fid, Audiobuf, AUDIOBUFSIZE, &ret); hd.cksize -= ret; audioplayerStart(); while (hd.cksize) { int next = hd.cksize > AUDIOBUFSIZE/2 ? AUDIOBUFSIZE/2 : hd.cksize; if (audioplayerHalf) { if (next < AUDIOBUFSIZE/2) bzero(Audiobuf, AUDIOBUFSIZE/2); f_read(&fid, Audiobuf, next, &ret); hd.cksize -= ret; audioplayerHalf = 0; } if (audioplayerWhole) { if (next < AUDIOBUFSIZE/2) bzero(&Audiobuf[AUDIOBUFSIZE/2], AUDIOBUFSIZE/2); f_read(&fid, &Audiobuf[AUDIOBUFSIZE/2], next, &ret); hd.cksize -= ret; audioplayerWhole = 0; } } audioplayerStop(); } printf("\nClose the file.\n"); rc = f_close(&fid); if (rc) die(rc); delay(1000); } } }
Cell* fatfs_read(Cell* stream) { Stream* s = (Stream*)stream->ar.addr; char* path = ((char*)s->path->ar.addr); if (!strncmp(path,"/sd/",4)) { char* filename = NULL; if (strlen(path)>4) { filename = path+4; } if (filename) { printf("FAT reading %s...\r\n",filename); FILINFO nfo; FRESULT rc = f_stat(filename, &nfo); if (rc) { printf("Failed to stat file %s: %u\r\n", filename, rc); return alloc_num_bytes(0); } FIL fp; rc = f_open(&fp, filename, FA_READ); if (rc) { printf("Failed to open file %s: %u\r\n", filename, rc); return alloc_num_bytes(0); } printf("filesize: %d\r\n",nfo.fsize); uint32_t buf_sz = nfo.fsize; Cell* result = alloc_num_bytes(buf_sz+1); UINT bytes_read; rc = f_read(&fp, result->ar.addr, buf_sz, &bytes_read); if (rc) printf("Read failed: %u\r\n", rc); rc = f_close(&fp); return result; } else { // directory Cell* res = alloc_num_string(4096); char* ptr = (char*)res->ar.addr; FRESULT rc; DIR dj; /* Pointer to the open directory object */ FILINFO fno; rc = f_opendir(&dj, "/"); printf("opendir: %d\r\n",rc); if (!rc) do { rc = f_readdir(&dj, &fno); printf("file: %s\r\n",fno.fname); int len = sprintf(ptr,"%s",fno.fname); ptr[len] = '\n'; ptr+=len+1; } while (!rc && dj.sect>0); return res; } } }
int LoadCampaign( const char *filename, CampaignSetting *setting, int max_missions, int max_characters) { FILE *f = NULL; int i; int err = CAMPAIGN_OK; int numMissions = max_missions; int numCharacters = max_characters; debug(D_NORMAL, "f: %s\n", filename); f = fopen(filename, "rb"); if (f == NULL) { err = CAMPAIGN_BADPATH; goto bail; } f_read32(f, &i, sizeof(i)); if (i != CAMPAIGN_MAGIC) { debug(D_NORMAL, "LoadCampaign - bad file!\n"); err = CAMPAIGN_BADFILE; goto bail; } f_read32(f, &i, sizeof(i)); if (i != CAMPAIGN_VERSION) { debug(D_NORMAL, "LoadCampaign - version mismatch!\n"); err = CAMPAIGN_VERSIONMISMATCH; goto bail; } f_read(f, setting->title, sizeof(setting->title)); f_read(f, setting->author, sizeof(setting->author)); f_read(f, setting->description, sizeof(setting->description)); f_read32(f, &setting->missionCount, sizeof(setting->missionCount)); if (max_missions <= 0) { size_t size = setting->missionCount * sizeof(struct Mission); CCALLOC(setting->missions, size); numMissions = setting->missionCount; } else if (setting->missionCount < max_missions) { numMissions = setting->missionCount; } debug(D_NORMAL, "No. missions: %d\n", numMissions); for (i = 0; i < numMissions; i++) { load_mission(f, &setting->missions[i]); } f_read32(f, &setting->characterCount, sizeof(setting->characterCount)); if (max_characters <= 0) { size_t size = setting->characterCount * sizeof(TBadGuy); CCALLOC(setting->characters, size); numCharacters = setting->characterCount; } else if (setting->characterCount < max_characters) { numCharacters = setting->characterCount; } debug(D_NORMAL, "No. characters: %d\n", numCharacters); for (i = 0; i < numCharacters; i++) { load_character(f, &setting->characters[i]); } bail: if (f != NULL) { fclose(f); } return err; }
void FFS_Ioctl(struct IPCMessage *msg) { FIL fil; u8 *bufin = (u8*)msg->ioctl.buffer_in; u32 lenin = msg->ioctl.length_in; u8 *bufout = (u8*)msg->ioctl.buffer_io; u32 lenout = msg->ioctl.length_io; s32 ret; //if( ((((vu32)bufin>>24)==0)&&lenin) || ((((vu32)bufout>>24)==0)&&lenout) ) //{ // dbgprintf("FFS:in:0x%p\tout:0x%p\n", bufin, bufout ); //} #ifdef EDEBUG dbgprintf("FFS:IOS_Ioctl( %d 0x%x 0x%p 0x%x 0x%p 0x%x )\n", msg->fd, msg->ioctl.command, bufin, lenin, bufout, lenout); #endif ret = FS_SUCCESS; switch(msg->ioctl.command) { case IOCTL_IS_USB: { ret = FS_SUCCESS; } break; case IOCTL_NANDSTATS: { if( lenout < 0x1C ) ret = -1017; else { NANDStat fs; //TODO: get real stats from SD CARD? fs.BlockSize = 0x4000; fs.FreeBlocks = 0x5DEC; fs.UsedBlocks = 0x1DD4; fs.unk3 = 0x10; fs.unk4 = 0x02F0; fs.Free_INodes = 0x146B; fs.unk5 = 0x0394; memcpy( bufout, &fs, sizeof(NANDStat) ); } ret = FS_SUCCESS; #ifdef DEBUG dbgprintf("FFS:GetNANDStats( %d, %p ):%d\n", msg->fd, msg->ioctl.buffer_io, ret ); #endif } break; case IOCTL_CREATEDIR: { ret = FS_CreateDir( (char*)(bufin+6) ); #ifdef USEATTR if( ret == FS_SUCCESS ) { //create attribute file char *path = (char*)heap_alloc_aligned( 0, 0x40, 32 ); _sprintf( path, "%s.attr", (char*)(bufin+6) ); if( f_open( &fil, path, FA_CREATE_ALWAYS | FA_WRITE ) == FR_OK ) { u32 wrote; f_lseek( &fil, 6 ); f_write( &fil, bufin+0x46, 4, &wrote); f_close( &fil ); } heap_free( 0, path ); } #endif #ifdef DEBUG dbgprintf("FFS:CreateDir(\"%s\", %02X, %02X, %02X, %02X ):%d\n", (char*)(bufin+6), *(u8*)(bufin+0x46), *(u8*)(bufin+0x47), *(u8*)(bufin+0x48), *(u8*)(bufin+0x49), ret ); #endif } break; case IOCTL_SETATTR: { if( lenin != 0x4A && lenin != 0x4C ) { ret = FS_EFATAL; } else { ret = FS_SetAttr( (char*)(bufin+6) ); } #ifdef USEATTR if( ret == FS_SUCCESS ) { //create attribute file char *path = (char*)heap_alloc_aligned( 0, 0x40, 32 ); _sprintf( path, "%s.attr", (char*)(bufin+6) ); if( f_open( &fil, (char*)path, FA_CREATE_ALWAYS | FA_WRITE ) == FR_OK ) { u32 wrote; if( lenin == 0x4A ) f_write( &fil, bufin, 4+2, &wrote); else f_lseek( &fil, 6 ); f_write( &fil, bufin+0x46, 4, &wrote); f_close( &fil ); } heap_free( 0, path ); } #endif #ifdef DEBUG dbgprintf("FFS:SetAttr(\"%s\", %08X, %04X, %02X, %02X, %02X, %02X):%d in:%X out:%X\n", (char*)(bufin+6), *(u32*)(bufin), *(u16*)(bufin+4), *(u8*)(bufin+0x46), *(u8*)(bufin+0x47), *(u8*)(bufin+0x48), *(u8*)(bufin+0x49), ret, lenin, lenout ); #endif } break; case IOCTL_GETATTR: { char *s=NULL; switch( lenin ) { case 0x40: s = (char*)(bufin); ret= FS_SUCCESS; break; case 0x4A: hexdump( bufin, lenin ); s = (char*)(bufin+6); ret= FS_SUCCESS; break; default: hexdump( bufin, lenin ); ret = FS_EFATAL; break; } if( ret != FS_EFATAL ) { if( f_open( &fil, s, FA_READ ) == FR_OK ) { f_close( &fil ); ret = FS_SUCCESS; } else { DIR d; if( f_opendir( &d, s ) == FR_OK ) { ret = FS_SUCCESS; } else { ret = FS_ENOENT2; } } #ifdef USEATTR //read attribute file char *path = (char*)heap_alloc_aligned( 0, 0x40, 32 ); _sprintf( path, "%s.attr", s ); if( f_open( &fil, path, FA_OPEN_EXISTING | FA_READ ) == FR_OK ) { u32 read; f_read( &fil, bufout, 4+2, &read); f_read( &fil, bufout+0x46, 4, &read); f_close( &fil ); } heap_free( 0, path ); #else *(u32*)(bufout) = 0x0000; *(u16*)(bufout) = 0x1000; *(u8*)(bufout+0x46) = 3; *(u8*)(bufout+0x47) = 3; *(u8*)(bufout+0x48) = 3; *(u8*)(bufout+0x49) = 3; #endif } #ifdef DEBUG dbgprintf("FFS:GetAttr(\"%s\", %02X, %02X, %02X, %02X ):%d in:%X out:%X\n", s, *(u8*)(bufout+0x46), *(u8*)(bufout+0x47), *(u8*)(bufout+0x48), *(u8*)(bufout+0x49), ret, lenin, lenout ); #endif } break; case IOCTL_DELETE: { ret = FS_DeleteFile( (char*)bufin ) ; #ifdef DEBUG dbgprintf("FFS:Delete(\"%s\"):%d\n", (char*)bufin, ret ); #endif } break; case IOCTL_RENAME: { ret = FS_Move( (char*)bufin, (char*)(bufin + 0x40) ); #ifdef USEATTR if( ret == FS_SUCCESS ) { //move attribute file char *src = (char*)heap_alloc_aligned( 0, 0x80, 32 ); char *dst = (char*)heap_alloc_aligned( 0, 0x80, 32 ); _sprintf( src, "%s.attr", (char*)bufin ); _sprintf( dst, "%s.attr", (char*)(bufin + 0x40) ); ret = FS_Move( src, dst ); //dbgprintf("FFS:Rename(\"%s\", \"%s\"):%d\n", src, dst, ret ); heap_free( 0, src ); heap_free( 0, dst ); } #endif #ifdef DEBUG dbgprintf("FFS:Rename(\"%s\", \"%s\"):%d\n", (char*)bufin, (char*)(bufin + 0x40), ret ); #endif } break; case IOCTL_CREATEFILE: { ret = FS_CreateFile( (char*)(bufin+6) ); #ifdef USEATTR if( ret == FS_SUCCESS ) { //create attribute file char *path = (char*)heap_alloc_aligned( 0, 0x40, 32 ); _sprintf( path, "%s.attr", (char*)(bufin+6) ); if( f_open( &fil, path, FA_CREATE_ALWAYS | FA_WRITE ) == FR_OK ) { u32 wrote; if( lenin == 0x4A ) f_write( &fil, bufin, 4+2, &wrote); else f_lseek( &fil, 6 ); f_write( &fil, bufin+0x46, 4, &wrote); f_close( &fil ); } heap_free( 0, path ); } #endif #ifdef DEBUG //if( ret != -105 ) dbgprintf("FFS:CreateFile(\"%s\", %02X, %02X, %02X, %02X):%d\n", (char*)(bufin+6), *(u8*)(bufin+0x46), *(u8*)(bufin+0x47), *(u8*)(bufin+0x48), *(u8*)(bufin+0x49), ret ); #endif } break; case IOCTL_GETSTATS: { ret = FS_GetStats( msg->fd, (FDStat*)bufout ); #ifdef DEBUG dbgprintf("FFS:GetStats( %d, %d, %d ):%d\n", msg->fd, ((FDStat*)bufout)->file_length, ((FDStat*)bufout)->file_length, ret ); #endif } break; case IOCTL_SHUTDOWN: //dbgprintf("FFS:Shutdown()\n"); //Close all open FS handles //u32 i; //for( i=0; i < MAX_FILE; ++i) //{ // if( fd_stack[i].fs != NULL ) // f_close( &fd_stack[i] ); //} ret = FS_SUCCESS; break; default: #ifdef EDEBUG dbgprintf("FFS:Unknown IOS_Ioctl( %d 0x%x 0x%p 0x%x 0x%p 0x%x )\n", msg->fd, msg->ioctl.command, bufin, lenin, bufout, lenout); #endif ret = FS_EFATAL; break; } #ifdef EDEBUG dbgprintf("FFS:IOS_Ioctl():%d\n", ret); #endif mqueue_ack( (void *)msg, ret); }
int main(int argc, char **argv) { uint32_t buff_r; FRESULT res; uint32_t n = 0, j = 0; int32_t y_temp = -1; int temp = 0; uint32_t time[64]; uint32_t time_temp[4]; uint32_t time_start = 0; uint32_t time_end = 0; /* 模块初始化 */ exc_init(); /* 中断初始化 */ sys_timer_init(); /* 系统时钟初始化 */ light_init(); /* LED灯初始化 */ serial_initialize((intptr_t)(NULL)); /* 初始化串口 */ sd_init(&Fatfs); /* 初始化SD卡,并创建文件 */ sd_create_file(&image_data, image_data_name); /* create a file */ printf("\n Welcome to k60 software platform! \n"); light_open(LIGHT4); res = f_open(&image_data, "0:DATA.TXT", FA_OPEN_EXISTING | FA_READ); res = f_read(&image_data, buffer, sizeof(buffer), &buff_r); ////// for(n=0; n<64; n++) ////// { ////// for(j=0;j<4;j++) ////// { // sys_timer_read(&time_start); compress_image(); // sys_timer_read(&time_end); ////// ////// time_temp[j] = time_start - time_end; ////// ////// } ////// time[n] = (time_temp[0] +time_temp[1]+time_temp[2]+time_temp[3])/4; ////// } // res = f_open(&image_data, "0:A_IMAGE.TXT", FA_OPEN_EXISTING | FA_WRITE); // /* 取出制表符 */ // if (image_data.fs) // { // for (n = 0; n < ((12800*2) +100) ; n++) // { // if((buffer[n] == '0') || (buffer[n] == '1')) // f_printf(&image_data, "%c", buffer[n]); // } // } // /* 写原始数据 */ //// if (image_data.fs) //// { //// for (n = 0; n < 12800 ; n++) //// { //// if(n%128 == 0) //// { //// y_temp ++; //// } //// //// if(buffer[n] == '0') //// { //// f_printf(&image_data, "%d\t", (n%128)); //// f_printf(&image_data, "%d\n", y_temp); //// } //// } //// } /* 写压缩后图像 */ // if (image_data.fs) // { // for (n = gl_SRNum; n >0 ; n--) // { // f_printf(&image_data, "%d\t%d\n", // (int)StrRoadFind[n].CenterX, (int)StrRoadFind[n].CenterY); // } // } for (n = 0; n <12800 ; n++) { buffer[n] = 0; } for (n = gl_SRNum; n >0 ; n--) { if((int)StrRoadFind[n].Width<12) buffer[(int)StrRoadFind[n].CenterY * 128 + (int)StrRoadFind[n].CenterX] = 1; } if (image_data.fs) { for (n = 12800; n >0 ; n--) { if(n%128 == 0) { f_printf(&image_data, "\n%d\t", (int)buffer[n]); } else { f_printf(&image_data, "%d\t", (int)buffer[n]); } } } // for (n = gl_SRNum; n > 0; n--) // { // printf("%d\t%d\n", (int) StrRoadFind[n].CenterX, // (int) StrRoadFind[n].CenterY); // } // printf("time cost is %d\n", (time_start - time_end)/100); //// for(n=0;n<64;n++) //// { //// f_printf(&image_data, "%d\t%d\n", //// n, time[n]); //// } //// // f_printf(&image_data, "COMPRESS OVER"); // sys_timer_read(&time_start); // find_road(); // sys_timer_read(&time_end); //printf("time cost is %d\n", (time_start - time_end)/100); sd_close_file(&image_data); /* 关闭文件 */ while(1) { light_open(LIGHT6); } }
u32 TRISetupGames(char *Path, unsigned int CurDICMD, u32 ISOShift) { u32 res = 0; u32 DOLOffset = 0; FIL f; FIL *fp = NULL; UINT read; FRESULT fres = FR_DISK_ERR; if(CurDICMD) { ReadRealDisc((u8*)&DOLOffset, 0x420+ISOShift, 4, CurDICMD); DOLOffset+=ISOShift; } else if(wiiVCInternal) { WDVD_FST_OpenDisc(0); WDVD_FST_LSeek(0x420+ISOShift); WDVD_FST_Read(wdvdTmpBuf, 4); memcpy(&DOLOffset, wdvdTmpBuf, 4); DOLOffset+=ISOShift; } else { char FullPath[260]; snprintf(FullPath, sizeof(FullPath), "%s:%s", GetRootDevice(), Path); fres = f_open_char(&f, FullPath, FA_READ|FA_OPEN_EXISTING); if (fres == FR_OK) { f_lseek(&f, 0x420+ISOShift); f_read(&f, &DOLOffset, 4, &read); DOLOffset+=ISOShift; } else { char FSTPath[260]; snprintf(FSTPath, sizeof(FSTPath), "%ssys/main.dol", FullPath); fres = f_open_char(&f, FSTPath, FA_READ|FA_OPEN_EXISTING); } if (fres != FR_OK) return 0; fp = &f; } // Create the save file if it doesn't already exist. char SaveFile[128]; if(DOLRead32(0x210320, DOLOffset, fp, CurDICMD) == 0x386000A8) { res = 1; gprintf("TRI:Mario Kart Arcade GP (ENG Feb 14 2006 13:09:48)\r\n"); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), CARD_NAME_GP1); CreateNewFile(SaveFile, 0x45); } else if(DOLRead32(0x25C0AC, DOLOffset, fp, CurDICMD) == 0x386000A8) { res = 1; gprintf("TRI:Mario Kart Arcade GP 2 (ENG Feb 7 2007 02:47:24)\r\n"); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), CARD_NAME_GP2); CreateNewFile(SaveFile, 0x45); } else if(DOLRead32(0x25C664, DOLOffset, fp, CurDICMD) == 0x386000A8) { res = 1; gprintf("TRI:Mario Kart Arcade GP 2 (JPN Feb 6 2007 20:29:25)\r\n"); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), CARD_NAME_GP2J); CreateNewFile(SaveFile, 0x45); } else if(DOLRead32(0x181E60, DOLOffset, fp, CurDICMD) == 0x386000A8) { res = 1; gprintf("TRI:F-Zero AX (Rev C)\r\n"); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), CARD_NAME_AX); CreateNewFile(SaveFile, 0xCF); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), SETTINGS_AX_RVC); CreateNewFile(SaveFile, 0x2A); } else if(DOLRead32(0x1821C4, DOLOffset, fp, CurDICMD) == 0x386000A8) { res = 1; gprintf("TRI:F-Zero AX (Rev D)\r\n"); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), CARD_NAME_AX); CreateNewFile(SaveFile, 0xCF); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), SETTINGS_AX_RVD); CreateNewFile(SaveFile, 0x2A); } else if(DOLRead32(0x18275C, DOLOffset, fp, CurDICMD) == 0x386000A8) { res = 1; gprintf("TRI:F-Zero AX (Rev E)\r\n"); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), CARD_NAME_AX); CreateNewFile(SaveFile, 0xCF); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), SETTINGS_AX_RVE); CreateNewFile(SaveFile, 0x2A); } else if(DOLRead32(0x01C2DF4, DOLOffset, fp, CurDICMD) == 0x386000A8) { res = 1; gprintf("TRI:Virtua Striker 3 Ver 2002\r\n"); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), SETTINGS_VS3V02); CreateNewFile(SaveFile, 0x12); } else if(DOLRead32(0x01CF1C4, DOLOffset, fp, CurDICMD) == 0x386000A8) { res = 1; gprintf("TRI:Virtua Striker 4 (Japan)\r\n"); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), SETTINGS_VS4JAP); CreateNewFile(SaveFile, 0x2B); } else if(DOLRead32(0x1C51E4, DOLOffset, fp, CurDICMD) == 0x386000A8) { res = 1; gprintf("TRI:Virtua Striker 4 (Export) (GDT-0014)\r\n"); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), SETTINGS_VS4EXP); CreateNewFile(SaveFile, 0x2B); } else if(DOLRead32(0x1C5514, DOLOffset, fp, CurDICMD) == 0x386000A8) { res = 1; gprintf("TRI:Virtua Striker 4 (Export) (GDT-0015)\r\n"); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), SETTINGS_VS4EXP); CreateNewFile(SaveFile, 0x2B); } else if(DOLRead32(0x24A4C8, DOLOffset, fp, CurDICMD) == 0x386000A8) { res = 1; gprintf("TRI:Virtua Striker 4 Ver 2006 (Japan) (Rev B)\r\n"); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), SETTINGS_VS4V06JAP); CreateNewFile(SaveFile, 0x2E); } else if(DOLRead32(0x24B248, DOLOffset, fp, CurDICMD) == 0x386000A8) { res = 1; gprintf("TRI:Virtua Striker 4 Ver 2006 (Japan) (Rev D)\r\n"); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), SETTINGS_VS4V06JAP); CreateNewFile(SaveFile, 0x2E); } else if(DOLRead32(0x20D7E8, DOLOffset, fp, CurDICMD) == 0x386000A8) { res = 1; gprintf("TRI:Virtua Striker 4 Ver 2006 (Export)\r\n"); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), SETTINGS_VS4V06EXP); CreateNewFile(SaveFile, 0x2B); } else if(DOLRead32(0x26B3F4, DOLOffset, fp, CurDICMD) == 0x386000A8) { res = 1; gprintf("TRI:Gekitou Pro Yakyuu (Rev B)\r\n"); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), SETTINGS_YAKRVB); CreateNewFile(SaveFile, 0xF5); } else if(DOLRead32(0x26D9B4, DOLOffset, fp, CurDICMD) == 0x386000A8) { res = 1; gprintf("TRI:Gekitou Pro Yakyuu (Rev C)\r\n"); snprintf(SaveFile, sizeof(SaveFile), "%s:%s", GetRootDevice(), SETTINGS_YAKRVC); CreateNewFile(SaveFile, 0x100); } if(wiiVCInternal) WDVD_FST_Close(); else if (fres == FR_OK) f_close(&f); return res; }
void patch9(void){ __asm__ volatile ( "PUSH {R0}\n" /* Disable ITCM and DTCM */ "MRC P15, 0, R0, C1, C0, 0\n" "BIC R0, #0x50000\n" "MCR P15, 0, R0, C1, C0, 0\n" /* Map ITCM */ "MOV R0, #0x0000001E\n" "MCR P15, 0, R0, C9, C1, 1\n" /* Map DTCM */ "LDR R0, =0x01FF800C\n" "MCR P15, 0, R0, C9, C1, 0\n" /* Enable ITCM and DTCM */ "MRC P15, 0, R0, C1, C0, 0\n" "ORR R0, #0x50000\n" "MCR P15, 0, R0, C1, C0, 0\n" "POP {R0}" ); /* Copy ITCM data to DTCM */ memcpy((void*)0x01FFB700, (void*)0x00A0B700, 0x900); memcpy((void*)0x01FFC000, (void*)0x00A0C000, 0xDE4); memcpy((void*)0x01FFD000, (void*)0x00A0D000, 0x2470); /* Clear out ITCM */ memset((void*)0x00A08000, 0, 0x8000); /* ARM9 */ u32* arm9bin = (void*)FIRM + FIRM[0xA0/4]; u32 arm9size = FIRM[0xA8/4]; /* Red/EmuNAND */ if (!(HIDKeyStatus() & KEY_L) && (REDNAND() == 0)){ for (u32 i = 0; i < (arm9size/4); i++){ /* SDMC Struct */ if (arm9bin[i] == 0x30201820){ emunand_code[21] = arm9bin[i+2] + arm9bin[i+3]; memcpy((void*)0x00A0FFA0, emunand_code, 0x60); } /* Branch to ITCM */ if (arm9bin[i] == 0x000D0004 && arm9bin[i+1] == 0x001E0017 && arm9bin[i+0x10] == 0x000D0004){ arm9bin[i] = 0x47A04C00; //LDR R4, =0x00A0FFA0; BLX R4 arm9bin[i+1] = 0x00A0FFA0; arm9bin[i+0x10] = 0x47A04C00; arm9bin[i+0x11] = 0x00A0FFA0; break; } } } /* ARM9 Thread */ FIL thread; u32 thread_br = 0; if (f_open(&thread, "thread.bin", FA_READ | FA_OPEN_EXISTING) == FR_OK){ if (f_size(&thread) <= 0x7F00){ //Max thread size for (u32 i = 0; i < (arm9size/4); i++){ if (arm9bin[i] == 0xE59F002C && arm9bin[i+1] == 0xE59F102C){ arm9_thread[13] = arm9bin[i+13]; //Set R0 memcpy((void*)0x00A0FF60, arm9_thread, 0x38); f_read(&thread, (void*)0x00A08000, f_size(&thread), &thread_br); arm9bin[i+1] = 0xE12FFF30; //BLX R0 arm9bin[i+13] = 0x00A0FF60; break; } } } f_close(&thread); } }
FRESULT Storage::copy(const char* pExistingFile, const char* pNewFile, unsigned int* pReadTime, unsigned int* pWriteTime, unsigned int* pBytesTransferred) { FRESULT status; FIL srcFile; FIL dstFile; unsigned int readTimeMs = 0; unsigned int writeTimeMs = 0; // Open Existing file if (FR_OK != (status = f_open(&srcFile, pExistingFile, FA_OPEN_EXISTING | FA_READ))) { return status; } // Open new file - overwrite if one exists if (FR_OK != (status = f_open(&dstFile, pNewFile, FA_CREATE_ALWAYS | FA_WRITE))) { f_close(&srcFile); return status; } /* Buffer should be at least he size of the sector */ char buffer[_MAX_SS]; unsigned int bytesRead = 0; unsigned int bytesWritten = 0; unsigned int totalBytesTransferred = 0; for (;;) { unsigned int startTime = sys_get_uptime_ms(); if(FR_OK != (status = f_read(&srcFile, buffer, sizeof(buffer), &bytesRead)) || 0 == bytesRead) { break; } readTimeMs += sys_get_uptime_ms() - startTime; startTime = sys_get_uptime_ms(); if(FR_OK != (status = f_write(&dstFile, buffer, bytesRead, &bytesWritten)) || bytesWritten != bytesRead) { break; } writeTimeMs += sys_get_uptime_ms() - startTime; totalBytesTransferred += bytesRead; } if(0 != pReadTime) { *pReadTime = readTimeMs; } if(0 != pWriteTime) { *pWriteTime = writeTimeMs; } if(0 != pBytesTransferred) { *pBytesTransferred = totalBytesTransferred; } f_close(&srcFile); f_close(&dstFile); return status; }
static BaseType_t prvPerformCopy( const char *pcSourceFile, int32_t lSourceFileLength, const char *pcDestinationFile, char *pxWriteBuffer, size_t xWriteBufferLen ) { int32_t lBytesRead = 0, lBytesToRead, lBytesRemaining; F_FILE *pxFile; BaseType_t xReturn = pdPASS; /* NOTE: Error handling has been omitted for clarity. */ while( lBytesRead < lSourceFileLength ) { /* How many bytes are left? */ lBytesRemaining = lSourceFileLength - lBytesRead; /* How many bytes should be read this time around the loop. Can't read more bytes than will fit into the buffer. */ if( lBytesRemaining > ( long ) xWriteBufferLen ) { lBytesToRead = ( long ) xWriteBufferLen; } else { lBytesToRead = lBytesRemaining; } /* Open the source file, seek past the data that has already been read from the file, read the next block of data, then close the file again so the destination file can be opened. */ pxFile = f_open( pcSourceFile, "r" ); if( pxFile != NULL ) { f_seek( pxFile, lBytesRead, F_SEEK_SET ); f_read( pxWriteBuffer, lBytesToRead, 1, pxFile ); f_close( pxFile ); } else { xReturn = pdFAIL; break; } /* Open the destination file and write the block of data to the end of the file. */ pxFile = f_open( pcDestinationFile, "a" ); if( pxFile != NULL ) { f_write( pxWriteBuffer, lBytesToRead, 1, pxFile ); f_close( pxFile ); } else { xReturn = pdFAIL; break; } lBytesRead += lBytesToRead; } return xReturn; }
/** * @brief Main routine for Mass Storage Class * @param None * @retval None */ static void MSC_Application(void) { FRESULT res; /* FatFs function common result code */ uint32_t byteswritten, bytesread; /* File write/read counts */ uint8_t wtext[] = "This is STM32 working with FatFs"; /* File write buffer */ uint8_t rtext[100]; /* File read buffer */ /* Register the file system object to the FatFs module */ if(f_mount(&USBDISKFatFs, (TCHAR const*)USBDISKPath, 0) != FR_OK) { /* FatFs Initialization Error */ Error_Handler(); } else { /* Create and Open a new text file object with write access */ if(f_open(&MyFile, "STM32.TXT", FA_CREATE_ALWAYS | FA_WRITE) != FR_OK) { /* 'STM32.TXT' file Open for write Error */ Error_Handler(); } else { /* Write data to the text file */ res = f_write(&MyFile, wtext, sizeof(wtext), (void *)&byteswritten); if((byteswritten == 0) || (res != FR_OK)) { /* 'STM32.TXT' file Write or EOF Error */ Error_Handler(); } else { /* Close the open text file */ f_close(&MyFile); /* Open the text file object with read access */ if(f_open(&MyFile, "STM32.TXT", FA_READ) != FR_OK) { /* 'STM32.TXT' file Open for read Error */ Error_Handler(); } else { /* Read data from the text file */ res = f_read(&MyFile, rtext, sizeof(rtext), (void *)&bytesread); if((bytesread == 0) || (res != FR_OK)) { /* 'STM32.TXT' file Read or EOF Error */ Error_Handler(); } else { /* Close the open text file */ f_close(&MyFile); /* Compare read data with the expected data */ if((bytesread != byteswritten)) { /* Read data is different from the expected data */ Error_Handler(); } else { /* Success of the demo: no error occurrence */ BSP_LED_On(LED4); } } } } } } /* Unlink the USB disk I/O driver */ FATFS_UnLinkDriver(USBDISKPath); }
const pm_char * bmpLoad(uint8_t *bmp, const char *filename, const xcoord_t width, const uint8_t height) { FIL bmpFile; UINT read; uint8_t palette[16]; uint8_t bmpBuf[LCD_W]; /* maximum with LCD_W */ uint8_t *buf = &bmpBuf[0]; if (width > LCD_W) { return STR_INCOMPATIBLE; } FRESULT result = f_open(&bmpFile, filename, FA_OPEN_EXISTING | FA_READ); if (result != FR_OK) { return SDCARD_ERROR(result); } if (f_size(&bmpFile) < 14) { f_close(&bmpFile); return STR_INCOMPATIBLE; } result = f_read(&bmpFile, buf, 14, &read); if (result != FR_OK || read != 14) { f_close(&bmpFile); return SDCARD_ERROR(result); } if (buf[0] != 'B' || buf[1] != 'M') { f_close(&bmpFile); return STR_INCOMPATIBLE; } uint32_t fsize = *((uint32_t *)&buf[2]); uint32_t hsize = *((uint32_t *)&buf[10]); /* header size */ uint32_t len = limit((uint32_t)4, (uint32_t)(hsize-14), (uint32_t)32); result = f_read(&bmpFile, buf, len, &read); if (result != FR_OK || read != len) { f_close(&bmpFile); return SDCARD_ERROR(result); } uint32_t ihsize = *((uint32_t *)&buf[0]); /* more header size */ /* invalid header size */ if (ihsize + 14 > hsize) { f_close(&bmpFile); return STR_INCOMPATIBLE; } /* sometimes file size is set to some headers size, set a real size in that case */ if (fsize == 14 || fsize == ihsize + 14) fsize = f_size(&bmpFile) - 2; /* declared file size less than header size */ if (fsize <= hsize) { f_close(&bmpFile); return STR_INCOMPATIBLE; } uint32_t w, h; switch (ihsize){ case 40: // windib case 56: // windib v3 case 64: // OS/2 v2 case 108: // windib v4 case 124: // windib v5 w = *((uint32_t *)&buf[4]); h = *((uint32_t *)&buf[8]); buf += 12; break; case 12: // OS/2 v1 w = *((uint16_t *)&buf[4]); h = *((uint16_t *)&buf[6]); buf += 8; break; default: f_close(&bmpFile); return STR_INCOMPATIBLE; } if (*((uint16_t *)&buf[0]) != 1) { /* planes */ f_close(&bmpFile); return STR_INCOMPATIBLE; } if (w > width || h > height) { f_close(&bmpFile); return STR_INCOMPATIBLE; } uint16_t depth = *((uint16_t *)&buf[2]); buf = &bmpBuf[0]; if (depth == 4) { if (f_lseek(&bmpFile, hsize-64) != FR_OK || f_read(&bmpFile, buf, 64, &read) != FR_OK || read != 64) { f_close(&bmpFile); return SDCARD_ERROR(result); } for (uint8_t i=0; i<16; i++) { palette[i] = buf[4*i] >> 4; } } else { if (f_lseek(&bmpFile, hsize) != FR_OK) {
/** * * File system example using SD driver to write to and read from an SD card * in polled mode. This example creates a new file on an * SD card (which is previously formatted with FATFS), write data to the file * and reads the same data back to verify. * * @param None * * @return XST_SUCCESS if successful, otherwise XST_FAILURE. * * @note None * ******************************************************************************/ int FfsSdPolledExample(void) { FRESULT Res; UINT NumBytesRead; UINT NumBytesWritten; u32 BuffCnt; u32 FileSize = (8*1024*1024); TCHAR *Path = "0:/"; for(BuffCnt = 0; BuffCnt < FileSize; BuffCnt++) { SourceAddress[BuffCnt] = TEST + BuffCnt; } /* * Register volume work area, initialize device */ Res = f_mount(&fatfs, Path, 0); if (Res != FR_OK) { return XST_FAILURE; } /* * Open file with required permissions. * Here - Creating new file with read/write permissions. . */ SD_File = (char *)FileName; Res = f_open(&fil, SD_File, FA_CREATE_ALWAYS | FA_WRITE | FA_READ); if (Res) { return XST_FAILURE; } /* * Pointer to beginning of file . */ Res = f_lseek(&fil, 0); if (Res) { return XST_FAILURE; } /* * Write data to file. */ Res = f_write(&fil, (const void*)SourceAddress, FileSize, &NumBytesWritten); if (Res) { return XST_FAILURE; } /* * Pointer to beginning of file . */ Res = f_lseek(&fil, 0); if (Res) { return XST_FAILURE; } /* * Read data from file. */ Res = f_read(&fil, (void*)DestinationAddress, FileSize, &NumBytesRead); if (Res) { return XST_FAILURE; } /* * Data verification */ for(BuffCnt = 0; BuffCnt < FileSize; BuffCnt++) { if(SourceAddress[BuffCnt] != DestinationAddress[BuffCnt]) { return XST_FAILURE; } } /* * Close file. */ Res = f_close(&fil); if (Res) { return XST_FAILURE; } return XST_SUCCESS; }
int main(void) { /* USER CODE BEGIN 1 */ // AxesRaw_t data; FRESULT res; /* FatFs function common result code */ uint32_t byteswritten, bytesread; /* File write/read counts */ char rtext[256]; /* File read buffer */ // HALL_SENS_PWR_ON; // CLAMP_SENS_PWR_ON; // 1. SPI1 is for ACC /* USER CODE END 1 */ /* MCU Configuration----------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* Configure the system clock */ SystemClock_Config(); /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_ADC_Init(); MX_SDIO_SD_Init(); MX_SPI1_Init(); MX_SPI2_Init(); MX_USART1_UART_Init(); MX_USART2_UART_Init(); MX_FATFS_Init(); MX_RTC_Init(); /* USER CODE BEGIN 2 */ HAL_RTCEx_DeactivateWakeUpTimer(&hrtc); HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, 1, RTC_WAKEUPCLOCK_CK_SPRE_16BITS); EXTI0_IRQHandler_Config(); // EXTI13_IRQHandler_Config(); // HAL_DBGMCU_EnableDBGStopMode(); //HALL_SENS_PWR_ON; //CLAMP_SENS_PWR_OFF; // init gpio before! UC_2_8V; printf("FW start\r\n"); LIS3DH_PreInit(); LIS3DH_SetMode(LIS3DH_NORMAL); //reg1 LIS3DH_SetODR(LIS3DH_ODR_400Hz); //reg1 LIS3DH_SetAxis(LIS3DH_X_ENABLE | LIS3DH_Y_ENABLE | LIS3DH_Z_ENABLE ); //reg1 //Direct IRQ from watemark and overrun to 1st pin. reg3 LIS3DH_SetInt1Pin(LIS3DH_CLICK_ON_PIN_INT1_DISABLE | LIS3DH_I1_INT1_ON_PIN_INT1_DISABLE | LIS3DH_I1_INT2_ON_PIN_INT1_DISABLE | LIS3DH_I1_DRDY1_ON_INT1_DISABLE | LIS3DH_I1_DRDY2_ON_INT1_DISABLE | LIS3DH_WTM_ON_INT1_ENABLE | LIS3DH_INT1_OVERRUN_DISABLE); //REG4 LIS3DH_SetBDU(MEMS_ENABLE); LIS3DH_SetFullScale(LIS3DH_FULLSCALE_2); //reg4 //REG5 LIS3DH_FIFOModeEnable(LIS3DH_FIFO_STREAM_MODE); //Enable store into FIFO reg5 LIS3DH_Int1LatchEnable(MEMS_ENABLE); //LIS3DH_FIFO_CTRL_REG LIS3DH_SetTriggerInt(LIS3DH_TRIG_INT1); LIS3DH_SetWaterMark(15); // watermark for irq generation from fifo LIS3DH_FIFO_CTRL_REG LIS3DH_ReadFIFO(); // clean FIFO and reset IRQ while (1) { //LIS3DH_GetInt1Src(&resp); //printf("INT1SRC %i ", resp); /*LIS3DH_GetFifoSourceBit(LIS3DH_FIFO_SRC_WTM, &resp); printf("WTM %i ", resp); LIS3DH_GetReg3Bit(LIS3DH_I1_WTM, &resp); printf("WMBIT %i ", resp); LIS3DH_GetFifoSourceFSS(&resp); printf("FIFO %i\r\n", resp); //LIS3DH_GetIntCounter(&resp); //printf("Interrupts counter=%i\r\n", resp); if (resp > 26) { //rep: //LIS3DH_GetFifoSourceFSS(&resp); //printf("> %i recs in FIFO (while)\r\n", resp); //HAL_Delay(15); //LIS3DH_GetInt1Src(&resp); /* rep: if(LIS3DH_GetAccAxesRaw(&data)==1){ LIS3DH_GetFifoSourceBit(LIS3DH_FIFO_SRC_WTM, &resp); //printf("X=%6d Y=%6d Z=%6d \r\n", data.AXIS_X, data.AXIS_Y, data.AXIS_Z); printf(" READ WTM%i\r\n", resp); } else { printf("ER\r\n"); } LIS3DH_GetFifoSourceFSS(&resp); if (resp > 0) goto rep; LIS3DH_ResetInt1Latch(); LIS3DH_FIFOModeEnable(LIS3DH_FIFO_STREAM_MODE);*/ LIS3DH_ReadFIFO(); HAL_Delay(2000); } //ENABLE ALL IRQs //LIS3DH_SetInt1Pin(LIS3DH_CLICK_ON_PIN_INT1_DISABLE | LIS3DH_I1_INT1_ON_PIN_INT1_ENABLE | LIS3DH_I1_INT2_ON_PIN_INT1_ENABLE | LIS3DH_I1_DRDY1_ON_INT1_ENABLE | LIS3DH_I1_DRDY2_ON_INT1_ENABLE | LIS3DH_WTM_ON_INT1_ENABLE | LIS3DH_INT1_OVERRUN_ENABLE); //LIS3DH_SetInt2Pin(LIS3DH_CLICK_ON_PIN_INT2_DISABLE | LIS3DH_I2_INT1_ON_PIN_INT2_ENABLE | LIS3DH_I2_INT2_ON_PIN_INT2_ENABLE | LIS3DH_I2_BOOT_ON_INT2_ENABLE | LIS3DH_INT_ACTIVE_HIGH); // HAL_Delay(2000); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ // if(LIS3DH_GetAccAxesRaw(&data)==1){ // printf("X=%6d Y=%6d Z=%6d \r\n", data.AXIS_X, data.AXIS_Y, data.AXIS_Z); // } else { // printf("ER\r\n"); // } HAL_Delay(50); // lowest_power(); //go to stop. Wakeup on RTC wakeup or 1st or 2d PIN wakeup } //SDIO FAT PART. //ENABLE_2_5V; //DC-DC enable SD_PWR_ON; //Power to SD card //INIT SD and CARD after because no power to sd HAL_Delay(50); MX_SDIO_SD_Init(); MX_FATFS_Init(); /*##-1- FatFS: Link the SD disk I/O driver ##########*/ if(FATFS_LinkDriver(&SD_Driver, SDPath) == 0){ /* success: set the orange LED on */ //HAL_GPIO_WritePin(GPIOG, GPIO_PIN_7, GPIO_PIN_RESET); /*##-2- Register the file system object to the FatFs module NB! mout right now! ###*/ res = f_mount(&SDFatFs, (TCHAR const*)SD_Path, 1) ; if(res != FR_OK){ /* FatFs Initialization Error : set the red LED on */ printf ("Problem fmount\r\n"); while(1); } else { /*##-3- Create a FAT file system (format) on the logical drive#*/ /* WARNING: Formatting the uSD card will delete all content on the device */ res = f_mkfs((TCHAR const*)SD_Path, 0, 0); if(res != FR_OK){ /* FatFs Format Error : set the red LED on */ printf ("Problem f_mkfs\r\n"); while(1); } else { /*##-4- Create & Open a new text file object with write access#*/ if(f_open(&MyFile, "Hello.txt", FA_CREATE_ALWAYS | FA_WRITE) != FR_OK){ /* 'Hello.txt' file Open for write Error : set the red LED on */ printf ("Problem f_open\r\n"); while(1); } else { /*##-5- Write data to the text file ####################*/ res = f_write(&MyFile, wtext, sizeof(wtext), (void*)&byteswritten); if((byteswritten == 0) || (res != FR_OK)){ /* 'Hello.txt' file Write or EOF Error : set the red LED on */ printf ("Problem f_write\r\n"); while(1); } else { /*##-6- Successful open/write : set the blue LED on */ // HAL_GPIO_WritePin(GPIOG, GPIO_PIN_12, GPIO_PIN_RESET); f_close(&MyFile); /*##-7- Open the text file object with read access #*/ if(f_open(&MyFile, "Hello.txt", FA_READ) != FR_OK){ /* 'Hello.txt' file Open for read Error : set the red LED on */ //HAL_GPIO_WritePin(GPIOG, GPIO_PIN_10, GPIO_PIN_RESET); printf ("Problem f_open\r\n"); while(1); } else { /*##-8- Read data from the text file #########*/ res = f_read(&MyFile, rtext, sizeof(wtext), &bytesread); // if((strcmp(rtext,wtext)!=0)|| (res != FR_OK)){ // /* 'Hello.txt' file Read or EOF Error : set the red LED on */ // printf ("Problem f_read\r\n"); // while(1); // } else { // printf ("FAT operation done OK!\r\n"); /* Successful read : set the green LED On */ //HAL_GPIO_WritePin(GPIOG, GPIO_PIN_6, GPIO_PIN_RESET); /*##-9- Close the open text file ################*/ f_close(&MyFile); } } } } } } /*##-10- Unlink the micro SD disk I/O driver #########*/ FATFS_UnLinkDriver(SD_Path); /* USER CODE END 3 */ }
static void loadHeader() { uint32_t count; uint8_t i; uint16_t songLength; uint16_t numberOfPatterns; uint16_t temp16; uint8_t masterVolume; uint8_t defaultPanning; uint8_t temp8; f_read(&file, uMod.S3m.name, 28, &count); f_lseek(&file, 0x20); f_read(&file, &songLength, 2, &count); f_read(&file, &uMod.S3m.numberOfInstruments, 2, &count); f_read(&file, &numberOfPatterns, 2, &count); uMod.S3m.fastVolumeSlides = false; f_read(&file, &temp16, 2, &count); // Flags if(temp16 & 64) uMod.S3m.fastVolumeSlides = true; // Fast volume slides flag f_read(&file, &temp16, 2, &count); // Created with tracker / version if((temp16 & 0xFFF) == 300) uMod.S3m.fastVolumeSlides = true; // Fast volume slides for Scream Tracker 3.00 f_lseek(&file, 0x30); f_read(&file, &uMod.S3m.globalVolume, 1, &count); f_read(&file, &uPlayer.S3m_player.speed, 1, &count); f_read(&file, &temp8, 1, &count); uPlayer.S3m_player.samplesPerTick = SAMPLERATE / (2 * temp8 / 5); // Hz = 2 * BPM / 5 f_read(&file, &masterVolume, 1, &count); // Check bit 8 later f_read(&file, &temp8, 1, &count); // Skip ultraclick removal f_read(&file, &defaultPanning, 1, &count); f_lseek(&file, 0x40); // Find the number of channels and remap the used channels linearly uMod.S3m.numberOfChannels = 0; memset(uMod.S3m.channelRemapping, 255, CHANNELS); for(i = 0; i < CHANNELS; i++) { f_read(&file, &temp8, 1, &count); if(temp8 < 16) { uMod.S3m.channelRemapping[i] = uMod.S3m.numberOfChannels; if(temp8 < 8) Mixer.channelPanning[uMod.S3m.numberOfChannels] = 0x3; else Mixer.channelPanning[uMod.S3m.numberOfChannels] = 0xC; uMod.S3m.numberOfChannels++; } } f_lseek(&file, 0x60); // Load order data f_read(&file, uMod.S3m.order, songLength, &count); // Calculate number of physical patterns uMod.S3m.songLength = 0; uMod.S3m.numberOfPatterns = 0; for(i = 0; i < songLength; i++) { uMod.S3m.order[uMod.S3m.songLength] = uMod.S3m.order[i]; if(uMod.S3m.order[i] < 254) { uMod.S3m.songLength++; if(uMod.S3m.order[i] > uMod.S3m.numberOfPatterns) uMod.S3m.numberOfPatterns = uMod.S3m.order[i]; } } // Load parapointers f_read(&file, uMod.S3m.instrumentParapointers, uMod.S3m.numberOfInstruments * 2, &count); f_read(&file, uMod.S3m.patternParapointers, numberOfPatterns * 2, &count); // If the panning flag is set then set default panning if(defaultPanning == 0xFC) { for(i = 0; i < CHANNELS; i++) { f_read(&file, &temp8, 1, &count); //R.K. added the uMod.S3m.channelRemapping[i]<CHANNELS because otherwise we would write to //an unknown memory if((temp8 & 0x20) && uMod.S3m.channelRemapping[i]<CHANNELS) Mixer.channelPanning[uMod.S3m.channelRemapping[i]] = temp8 & 0xF; } } // If stereo flag is not set then make song mono if(!(masterVolume & 128)) for(i = 0; i < CHANNELS; i++) Mixer.channelPanning[i] = 0x8; // Avoid division by zero for unused instruments for(i = 0; i < INSTRUMENTS; i++) uMod.S3m.instruments[i].middleC = 8363; // Load instruments for(i = 0; i < uMod.S3m.numberOfInstruments; i++) { // Jump to instrument parapointer and skip filename f_lseek(&file, (uMod.S3m.instrumentParapointers[i] << 4) + 13); // Find parapointer to actual sample data (3 bytes) f_read(&file, &temp8, 1, &count); // High byte f_read(&file, &temp16, 2, &count); // Low word uMod.S3m.instruments[i].sampleParapointer = temp16; // (temp8 << 16) + temp16 f_read(&file, &uMod.S3m.instruments[i].length, 2, &count); f_read(&file, &temp16, 2, &count); // Skip two bytes f_read(&file, &uMod.S3m.instruments[i].loopBegin, 2, &count); f_read(&file, &temp16, 2, &count); // Skip two bytes f_read(&file, &uMod.S3m.instruments[i].loopEnd, 2, &count); f_read(&file, &temp16, 2, &count); // Skip two bytes f_read(&file, &uMod.S3m.instruments[i].volume, 1, &count); f_read(&file, &temp16, 2, &count); // Skip two bytes f_read(&file, &temp8, 1, &count); // Instrument flags uMod.S3m.instruments[i].loop = temp8 & 1; // Loop enable flag f_read(&file, &uMod.S3m.instruments[i].middleC, 2, &count); if(!uMod.S3m.instruments[i].middleC) uMod.S3m.instruments[i].middleC = 8363; // Avoid division by zero f_lseek(&file, count + 14); f_read(&file, uMod.S3m.instruments[i].name, 28, &count); // Followed by "SCRS" if(uMod.S3m.instruments[i].loopEnd > uMod.S3m.instruments[i].length) uMod.S3m.instruments[i].loopEnd = uMod.S3m.instruments[i].length; } }
void load_mission(FILE *f, struct Mission *m) { int i; int o = 0; f_read(f, m->title, sizeof(m->title)); o += sizeof(m->title); f_read(f, m->description, sizeof(m->description)); o += sizeof(m->description); debug(D_NORMAL, "== MISSION ==\n"); debug(D_NORMAL, "t: %s\n", m->title); debug(D_NORMAL, "d: %s\n", m->description); R32(m, wallStyle); R32(m, floorStyle); R32(m, roomStyle); R32(m, exitStyle); R32(m, keyStyle); R32(m, doorStyle); R32(m, mapWidth); R32(m, mapHeight); R32(m, wallCount); R32(m, wallLength); R32(m, roomCount); R32(m, squareCount); R32(m, exitLeft); R32(m, exitTop); R32(m, exitRight); R32(m, exitBottom); R32(m, objectiveCount); debug(D_NORMAL, "number of objectives: %d\n", m->objectiveCount); for (i = 0; i < OBJECTIVE_MAX; i++) { load_mission_objective(f, &m->objectives[i]); } R32(m, baddieCount); for (i = 0; i < BADDIE_MAX; i++) { f_read32(f, &m->baddies[i], sizeof(int)); } R32(m, specialCount); for (i = 0; i < SPECIAL_MAX; i++) { f_read32(f, &m->specials[i], sizeof(int)); } R32(m, itemCount); for (i = 0; i < ITEMS_MAX; i++) { f_read32(f, &m->items[i], sizeof(int)); } for (i = 0; i < ITEMS_MAX; i++) { f_read32(f, &m->itemDensity[i], sizeof(int)); } R32(m, baddieDensity); R32(m, weaponSelection); f_read(f, m->song, sizeof(m->song)); f_read(f, m->map, sizeof(m->map)); R32(m, wallRange); R32(m, floorRange); R32(m, roomRange); R32(m, altRange); debug(D_VERBOSE, "number of baddies: %d\n", m->baddieCount); return; }
bool File::read(void* const data, const size_t bytes_to_read) { UINT bytes_read = 0; const auto result = f_read(&f, data, bytes_to_read, &bytes_read); return (result == FR_OK) && (bytes_read == bytes_to_read); }
void cmd_sdiotest(void) { uint32_t i = 0; FRESULT err = 0; bool format = false; chThdSleepMilliseconds(100); if (!sdioConnect ()) { sdioDebug (" FAIL\r\n "); return; } if (TRUE) { sdioDebug ("OK\r\n"); sdioDebug ("*** Card CSD content is: "); sdioDebug ("%X %X %X %X \r\n", (&SDCD1)->csd[3], (&SDCD1)->csd[2], (&SDCD1)->csd[1], (&SDCD1)->csd[0]); sdioDebug ("capacity = %d sectors of 512 bytes = %d Mo\r\n", SDCD1.capacity, SDCD1.capacity / 2048); sdioDebug ("Single aligned read..."); chThdSleepMilliseconds(100); if (sdcRead(&SDCD1, 0, inbuf, 1)) goto error; sdioDebug (" OK\r\n"); chThdSleepMilliseconds(100); sdioDebug ("Single unaligned read..."); chThdSleepMilliseconds(100); if (sdcRead(&SDCD1, 0, inbuf + 1, 1)) goto error; if (sdcRead(&SDCD1, 0, inbuf + 2, 1)) goto error; if (sdcRead(&SDCD1, 0, inbuf + 3, 1)) goto error; sdioDebug (" OK\r\n"); chThdSleepMilliseconds(100); sdioDebug ("Multiple aligned reads..."); chThdSleepMilliseconds(100); fillbuffers(0x55); /* fill reference buffer from SD card */ if (sdcRead(&SDCD1, 0, inbuf, SDC_BURST_SIZE)) goto error; for (i=0; i<1000; i++){ if (sdcRead(&SDCD1, 0, outbuf, SDC_BURST_SIZE)) goto error; if (memcmp(inbuf, outbuf, SDC_BURST_SIZE * MMCSD_BLOCK_SIZE) != 0) goto error; } sdioDebug (" OK\r\n"); chThdSleepMilliseconds(100); sdioDebug ("Multiple unaligned reads..."); chThdSleepMilliseconds(100); fillbuffers(0x55); /* fill reference buffer from SD card */ if (sdcRead(&SDCD1, 0, inbuf + 1, SDC_BURST_SIZE)) goto error; for (i=0; i<1000; i++){ if (sdcRead(&SDCD1, 0, outbuf + 1, SDC_BURST_SIZE)) goto error; if (memcmp(inbuf, outbuf, SDC_BURST_SIZE * MMCSD_BLOCK_SIZE) != 0) goto error; } sdioDebug (" OK\r\n"); chThdSleepMilliseconds(100); #if SDC_DATA_DESTRUCTIVE_TEST if (format) { sdioDebug ("Single aligned write..."); chThdSleepMilliseconds(100); fillbuffer(0xAA, inbuf); if (sdcWrite(&SDCD1, 0, inbuf, 1)) goto error; fillbuffer(0, outbuf); if (sdcRead(&SDCD1, 0, outbuf, 1)) goto error; if (memcmp(inbuf, outbuf, MMCSD_BLOCK_SIZE) != 0) goto error; sdioDebug (" OK\r\n"); sdioDebug ("Running badblocks at 0x10000 offset..."); chThdSleepMilliseconds(100); if(badblocks(0x10000, 0x11000, SDC_BURST_SIZE, 0xAA)) goto error; sdioDebug (" OK\r\n"); } else { } #endif /* !SDC_DATA_DESTRUCTIVE_TEST */ /** * Now perform some FS tests. */ DWORD clusters=0; FATFS *fsp=NULL; FIL FileObject; uint32_t bytes_written=0; uint32_t bytes_read=0; FILINFO fno ; #if _USE_LFN char lfn[_MAX_LFN + 1]; fno.lfname = lfn; fno.lfsize = sizeof lfn; #endif const uint8_t teststring[] = {"This is test file\r\n"} ; /* FS object.*/ static FATFS SDC_FS; #if SDC_DATA_DESTRUCTIVE_TEST if (format) { sdioDebug ("Formatting... "); chThdSleepMilliseconds(100); sdioDebug ("Register working area for filesystem... "); chThdSleepMilliseconds(100); err = f_mount(0, &SDC_FS); if (err != FR_OK){ goto error; } else{ sdioDebug ("OK\r\n"); } } if (format) { sdioDebug ("f_mkfs starting ... "); chThdSleepMilliseconds(100); err = f_mkfs (0,0,0); if (err != FR_OK){ goto error; } else { sdioDebug ("OK\r\n"); } } #endif /* SDC_DATA_DESTRUCTIVE_TEST */ sdioDebug ("get free space on filesystem... "); chThdSleepMilliseconds(100); err = f_getfree(NULL, &clusters, &fsp); if (err != FR_OK) goto error; sdioDebug ("OK\r\n"); sdioDebug ("FS: %lu free clusters, %lu sectors per cluster, %lu bytes free\r\n", clusters, (uint32_t)SDC_FS.csize, clusters * (uint32_t)SDC_FS.csize * (uint32_t)MMCSD_BLOCK_SIZE); sdioDebug ("Create file \"chtest.txt\"... "); chThdSleepMilliseconds(100); err = f_open(&FileObject, "chtest.txt", FA_WRITE | FA_OPEN_ALWAYS); if (err != FR_OK) { goto error; } sdioDebug ("OK\r\n"); sdioDebug ("Write some data in it... "); chThdSleepMilliseconds(100); err = f_write(&FileObject, teststring, sizeof(teststring), (void *)&bytes_written); if (err != FR_OK) { goto error; } else sdioDebug ("OK\r\n"); sdioDebug ("Close file \"chtest.txt\"... "); err = f_close(&FileObject); if (err != FR_OK) { goto error; } else sdioDebug ("OK\r\n"); sdioDebug ("Check file size \"chtest.txt\"... "); chThdSleepMilliseconds(10); err = f_stat("chtest.txt", &fno); chThdSleepMilliseconds(100); if (err != FR_OK) { goto error; } else { if (fno.fsize == sizeof(teststring)) { sdioDebug ("OK\r\n"); } else goto error; } sdioDebug ("Check file content \"chtest.txt\"... "); err = f_open(&FileObject, "chtest.txt", FA_READ | FA_OPEN_EXISTING); chThdSleepMilliseconds(100); if (err != FR_OK) { goto error; } uint8_t buf[sizeof(teststring)]; err = f_read(&FileObject, buf, sizeof(teststring), (void *)&bytes_read); if (err != FR_OK) { goto error; } else { if (memcmp(teststring, buf, sizeof(teststring)) != 0){ goto error; } else { sdioDebug ("OK\r\n"); } } { FILINFO fno; DIR dir; // char *fn; /* This function is assuming non-Unicode cfg. */ #if _USE_LFN char lfn[_MAX_LFN + 1]; fno.lfname = lfn; fno.lfsize = sizeof lfn; #endif const char *path = ""; FRESULT res =0; res = f_opendir(&dir, path); /* Open the directory */ if (res == FR_OK) { for (;;) { res = f_readdir(&dir, &fno); /* Read a directory item */ if (res != FR_OK || fno.fname[0] == 0) break; /* Break on error or end of dir */ if (fno.fname[0] == '.') continue; /* Ignore dot entry */ #if _USE_LFN // fn = fno.lfname; #else // fn = fno.fname; #endif /* It is a file. */ //chprintf(chp, "readdir %s/%s\r\n", path, fn); } } } sdioDebug ("Umount filesystem... "); f_mount(0, NULL); sdioDebug ("OK\r\n"); sdioDebug ("Disconnecting from SDIO..."); chThdSleepMilliseconds(100); if (!sdioDisconnect()) goto error; sdioDebug (" OK\r\n"); sdioDebug ("------------------------------------------------------\r\n"); sdioDebug ("All tests passed successfully.\r\n"); chThdSleepMilliseconds(100); sdioDisconnect(); return; } error: sdioDebug ("SDC error [%d] occurs\r\n", err); sdioDisconnect(); }
/* Function to do the read/write to USB Disk */ static void throughputTest(void) { FRESULT rc; /* Result code */ UINT br; f_mount(0, &fatFS); /* Register volume work area (never fails) */ rc = f_open(&fileObj, "test.bin", FA_READ); if (rc) { DEBUGOUT("Unable to open big_file.bin from USB Disk\r\n"); die(rc); } int frameReads; uint32_t readTimes[MAX_FRAME_READS]; Chip_TIMER_Enable(RUNTIME_TIMER); for(frameReads = 0; frameReads < MAX_FRAME_READS; ++frameReads) { RUNTIME_TIMER->TC = 0; /* Read a chunk of file */ rc = f_read(&fileObj, frameBuffer, FRAME_SIZE, &br); if(rc != FR_OK) { DEBUGOUT("Error reading from file\r\n"); die(rc); } else if(br != FRAME_SIZE) { break; } readTimes[frameReads] = RUNTIME_TIMER->TC; Board_UARTPutChar('.'); } f_close(&fileObj); uint64_t sum = 0; uint32_t min = UINT32_MAX; uint32_t max = 0; float ave; for(int i = 0; i < frameReads; ++i) { sum += readTimes[i]; if(readTimes[i] < min) min = readTimes[i]; if(readTimes[i] > max) max = readTimes[i]; } ave = (float)sum / (float)frameReads; printf("\n----------------------------\n"); printf("Test Results\n"); printf("----------------------------\n"); printf("\tFrames read: %d\n", frameReads); printf("\tFrame size: %.3fkB\n", (float)FRAME_SIZE / 1000.0); printf("\tMin time: %.3fus\n", (float)min * PCLK_US); printf("\tMax time: %.3fus\n", (float)max * PCLK_US); printf("\tAve time: %.3fus\n", (float)ave * PCLK_US); printf("\n----------------------------\n"); printf("All times\n"); printf("----------------------------\n"); for(int i = 0; i < frameReads; ++i) { printf("\t%02d: %.3fus\n", i, (float)readTimes[i] * PCLK_US); } printf("----------------------------\n\n"); DEBUGOUT("\r\nTest completed.\r\n"); USB_Host_SetDeviceConfiguration(FlashDisk_MS_Interface.Config.PortNumber, 0); }
/** * @brief draw the image after scaling it * @param hFile: pointer to the MJPEG file * @retval None */ static int _PlayMJPEG(FIL *hFile) { unsigned int NumBytesRead; char *ptr; int timeout = 0xFFFF; static int counter = 0; f_lseek(hFile, ImageOffset); t0 = GUI_GetTime(); s0 = hFile->fptr; if(VIDEO_Enlarge == 1) { GUI_JPEG_DrawEx(_GetData, hFile, 0, 0); } else { GUI_JPEG_DrawScaledEx(_GetData, hFile, 7, 2, 2, 3); } if(counter ++ > 20 ) { frame_average_size = (hFile->fptr - s0 + frame_average_size)/2; frame_average_period = (GUI_GetTime() - t0 + frame_average_period)/2; counter = 0; } if(frame_average_size != 0) frame_speed = frame_average_size / frame_average_period ; else frame_speed = 70; ImageOffset = hFile->fptr; while ( --timeout > 0 ) { f_lseek(hFile, ImageOffset - VIDEO_BUFFER_SIZE); f_read(hFile, (char *)_acVideoBuffer, VIDEO_BUFFER_SIZE, &NumBytesRead); /* Get image offset */ ptr = _acVideoBuffer; while (NumBytesRead --) { if((*ptr == 0xFF) && ((*(ptr + 1)) == M_SOI)) { ImageOffset -= (NumBytesRead + 1) ; return 0; } ptr++; } ImageOffset += 2 * VIDEO_BUFFER_SIZE; if (ImageOffset >= hFile->fsize) { return -1; } } return -1; }
//shows vcards void ram(void) { char filename[13]; uint8_t buf[MAXSIZE]; FRESULT res; UINT readbytes; FIL file; uint8_t key; int i,j=0,lines=0; char *beginline=buf; char help; selectFile(filename,"CRD"); lcdClear(); res=f_open(&file, (const char*)filename, FA_OPEN_EXISTING|FA_READ); res=f_read(&file, (char *)buf, MAXSIZE, &readbytes); for(i=0;i<readbytes;i++) { if(lines==7) { lines=0; lcdRefresh(); while(1) { key = getInput(); if( key == BTN_DOWN){ break; } } } if(buf[i]=='\n') { j=0; buf[i]=0; lcdPrintln(beginline); beginline=&buf[i+1]; lines++; } else if(j>13) { help=buf[i]; j=0; buf[i]=0; lcdPrintln(beginline); beginline=&buf[i]; buf[i]=help; lines++; } j++; } lcdRefresh(); while (1) { key = getInput(); if( key == BTN_LEFT ){ break; } } }
/* * 显示bmp图片, 24位真彩色 * 图片宽度和高度根据图片大小而定 */ void Lcd_show_bmp(unsigned short int x, unsigned short int y,unsigned char *pic_name) { int i, j, k; int width, height, l_width; BYTE red,green,blue; BITMAPFILEHEADER bitHead; BITMAPINFOHEADER bitInfoHead; WORD fileType; unsigned int read_num; unsigned char tmp_name[20]; sprintf((char*)tmp_name,"0:%s",pic_name); f_mount(0, &bmpfs[0]); BMP_DEBUG_PRINTF("file mount ok \r\n"); bmpres = f_open( &bmpfsrc , (char *)tmp_name, FA_OPEN_EXISTING | FA_READ); /*-------------------------------------------------------------------------------------------------------*/ if(bmpres == FR_OK) { BMP_DEBUG_PRINTF("Open file success\r\n"); /* 读取文件头信息 两个字节*/ f_read(&bmpfsrc,&fileType,sizeof(WORD),&read_num); /* 判断是不是bmp文件 "BM"*/ if(fileType != 0x4d42) { BMP_DEBUG_PRINTF("file is not .bmp file!\r\n"); return; } else { BMP_DEBUG_PRINTF("Ok this is .bmp file\r\n"); } /* 读取BMP文件头信息*/ f_read(&bmpfsrc,&bitHead,sizeof(tagBITMAPFILEHEADER),&read_num); showBmpHead(&bitHead); /* 读取位图信息头信息 */ f_read(&bmpfsrc,&bitInfoHead,sizeof(BITMAPINFOHEADER),&read_num); showBmpInforHead(&bitInfoHead); } else { BMP_DEBUG_PRINTF("file open fail!\r\n"); return; } /*-------------------------------------------------------------------------------------------------------*/ width = bitInfoHead.biWidth; height = bitInfoHead.biHeight; /* 计算位图的实际宽度并确保它为32的倍数 */ l_width = WIDTHBYTES(width* bitInfoHead.biBitCount); if(l_width > 960) { BMP_DEBUG_PRINTF("\n SORRY, PIC IS TOO BIG (<=320)\n"); return; } /* 设置Lcd Gram 扫描方向为: 右下角->左上角 */ Lcd_GramScan( 3 ); /* 开一个图片大小的窗口*/ LCD_OpenWindow(x, y, width, height); /* 判断是否是24bit真彩色图 */ if(bitInfoHead.biBitCount >= 24) { for(i=0;i< height; i++) { /* 读取一行bmp的数据到数组pColorData里面 */ #if 0 for(j=0; j< l_width; j++) { f_read(&bmpfsrc,pColorData+j,1,&read_num); } #elif 1 f_read(&bmpfsrc,pColorData,l_width/2,&read_num); f_read(&bmpfsrc,pColorData+l_width/2,l_width/2,&read_num); #else f_read(&bmpfsrc,pColorData,l_width,&read_num); #endif for(j=0; j<width; j++) //一行有效信息 { k = j*3; //一行中第K个像素的起点 red = pColorData[k+2]; green = pColorData[k+1]; blue = pColorData[k]; LCD_WR_Data(RGB24TORGB16(red,green,blue)); //写入LCD-GRAM } } } else { BMP_DEBUG_PRINTF("SORRY, THIS PIC IS NOT A 24BITS REAL COLOR"); return ; } f_close(&bmpfsrc); }
/** * @brief Files operations: Read/Write and compare * @param None * @retval None */ void MSC_File_Operations(void) { uint16_t bytesread; /* Register the file system object to the FatFs module */ if(f_mount(&USBH_fatfs, "", 0 ) != FR_OK ) { LCD_ErrLog("Cannot Initialize FatFs! \n"); } else { LCD_UsrLog ("INFO : FatFs Initialized \n"); if(f_open(&MyFile, "0:USBHost.txt",FA_CREATE_ALWAYS | FA_WRITE) != FR_OK) { LCD_ErrLog("Cannot Open 'USBHost.txt' file \n"); } else { LCD_UsrLog ("INFO : 'USBHost.txt' opened for write \n"); res= f_write (&MyFile, wtext, sizeof(wtext), (void *)&bytesWritten); f_close(&MyFile); if((bytesWritten == 0) || (res != FR_OK)) /*EOF or Error*/ { LCD_ErrLog("Cannot Write on the 'USBHost.txt' file \n"); } else { if(f_open(&MyFile, "0:USBHost.txt", FA_READ) != FR_OK) { LCD_ErrLog("Cannot Open 'USBHost.txt' file for read.\n"); } else { LCD_UsrLog ("INFO : Text written on the 'USBHost.txt' file \n"); res = f_read(&MyFile, rtext, sizeof(rtext), (void *)&bytesread); if((bytesread == 0) || (res != FR_OK)) /*EOF or Error*/ { LCD_ErrLog("Cannot Read from the 'USBHost.txt' file \n"); } else { LCD_UsrLog("Read Text : \n"); LCD_DbgLog((char *)rtext); LCD_DbgLog("\n"); } f_close(&MyFile); } /* Compare read data with the expected data */ if((bytesread == bytesWritten)) { LCD_UsrLog ("INFO : FatFs data compare SUCCES"); LCD_UsrLog("\n"); } else { LCD_ErrLog("FatFs data compare ERROR"); LCD_ErrLog("\n"); } } } } }
FUNCTION CODE old_Co_ReadFile ( Id c, /* in: existing collection */ TEXT *filespec, /* in: name of file to read */ CODE mode /* in: mode for the vm objs */ ) { struct SFILE f; union { struct PARHDR ph; /* standard header */ TEXT padding[300]; /* in case reading new file */ } headBuffer; CODE code; COUNT recsize; Id vm; TEXT record [STRINGSIZ+2]; BOOL archive; TEXT fullSpec[STRINGSIZ+1]; struct FSBLOCK fsblock; /* to dig out file name */ TEXT errstr[STRINGSIZ+1]; COUNT islash; #ifdef UNIX union { TEXT record [STRINGSIZ+1]; /* padding for long records */ struct ar_hdr header; /* the real archive header */ } hdrRecord; #endif code = f_opnspc (&f, 1, filespec, "", "", "res", F_READ); if (code != SUCCESS) { x_error(mode, "Unable to open resource file '%s'. %s.", "TAE-PFOPN", (uintptr_t)filespec, (uintptr_t)f.errmsg, 0); return (FAIL); } /* determine whether file is concatenated or archive format */ code = f_read (&f, record); if (code == SUCCESS && s_equal (record, AR_SENTINEL)) archive = TRUE; else { archive = FALSE; f_rewind (&f); /* re-start at beginning */ } /* read each Vm object from the file */ while (FOREVER) { if (archive) /* skip header */ { #ifdef UNIX code = f_read (&f, (TEXT *)&hdrRecord); /* read hdr or pad */ if (code == SUCCESS && hdrRecord.record[0] == EOS) code = f_read (&f, (TEXT *)&hdrRecord); /* skip EOF padding */ if (code == F_EOF) { code = SUCCESS; break; } else if (code != SUCCESS) { f_close(&f, F_KEEP); x_error (mode, "File '%s' not correctly formatted.", "TAE-RESFORMAT", (uintptr_t)filespec, 0, 0); return (FAIL); } #ifdef AIX s_bcopy (hdrRecord.header._ar_name.ar_name, fullSpec, sizeof(hdrRecord.header._ar_name.ar_name)); #else s_bcopy (hdrRecord.header.ar_name, fullSpec, sizeof(hdrRecord.header.ar_name)); #endif s_strip (fullSpec); /* remove trailing blanks */ islash = s_index (fullSpec, '/'); /* HP (and others?) */ if (islash >= 0) /* term with slash */ fullSpec[islash] = EOS; /* clip at slash */ f_crack (fullSpec, "", "", "", &fsblock, errstr); /* dig name */ #else x_error (mode, "File '%s' not correctly formatted.", "TAE-RESFORMAT", filespec, 0, 0); return (FAIL); #endif } code = f_bread (&f, (GENPTR)&headBuffer, sizeof (headBuffer), &recsize); if (code == F_EOF) { code = SUCCESS; /* normal end-of-file */ break; } else if (code == SUCCESS && s_equal (headBuffer.ph.sentinel, "<<new par-file>>")) { f_close(&f, F_KEEP); x_error(mode, "Resource file '%s' has already been converted.", "TAE-VNEWFORMAT", (uintptr_t)filespec, 0, 0); return (FAIL); } else if(code != SUCCESS || !s_equal(headBuffer.ph.sentinel, P_SENTINEL)) { f_close(&f, F_KEEP); x_error(mode, "Error reading resource file '%s'. %s.", "TAE-PFRD", (uintptr_t)filespec, (uintptr_t)f.errmsg, 0); return (FAIL); } vm = Vm_New (mode); /* create new vm object */ code = Vm_ReadVm ((struct VM_STRUCT *)vm, &f); /* read parblk records */ if (code != SUCCESS) break; /* x_error already called */ if (archive) old_Co_Add ((struct COLLECTION *)c, vm, fsblock.name, C_VM); else old_Co_Add ((struct COLLECTION *)c, vm, headBuffer.ph.filename, C_VM); } f_close (&f, F_KEEP); return (code); }
/** * @brief Start task * @param pvParameters not used * @retval None */ static void StartThread(void const *argument) { FRESULT res; /* FatFs function common result code */ uint32_t byteswritten, bytesread; /* File write/read counts */ uint8_t wtext[] = "This is STM32 working with FatFs"; /* File write buffer */ uint8_t rtext[100]; /* File read buffer */ /*##-1- Link the micro SD disk I/O driver ##################################*/ if(FATFS_LinkDriver(&SD_Driver, SDPath) == 0) { /*##-2- Register the file system object to the FatFs module ##############*/ if(f_mount(&SDFatFs, (TCHAR const*)SDPath, 0) != FR_OK) { /* FatFs Initialization Error */ Error_Handler(); } else { /*##-3- Create a FAT file system (format) on the logical drive #########*/ /* WARNING: Formatting the uSD card will delete all content on the device */ if(f_mkfs((TCHAR const*)SDPath, 0, 0) != FR_OK) { /* FatFs Format Error */ Error_Handler(); } else { /*##-4- Create and Open a new text file object with write access #####*/ if(f_open(&MyFile, "STM32.TXT", FA_CREATE_ALWAYS | FA_WRITE) != FR_OK) { /* 'STM32.TXT' file Open for write Error */ Error_Handler(); } else { /*##-5- Write data to the text file ################################*/ res = f_write(&MyFile, wtext, sizeof(wtext), (void *)&byteswritten); if((byteswritten == 0) || (res != FR_OK)) { /* 'STM32.TXT' file Write or EOF Error */ Error_Handler(); } else { /*##-6- Close the open text file #################################*/ f_close(&MyFile); /*##-7- Open the text file object with read access ###############*/ if(f_open(&MyFile, "STM32.TXT", FA_READ) != FR_OK) { /* 'STM32.TXT' file Open for read Error */ Error_Handler(); } else { /*##-8- Read data from the text file ###########################*/ res = f_read(&MyFile, rtext, sizeof(rtext), (UINT*)&bytesread); if((bytesread == 0) || (res != FR_OK)) { /* 'STM32.TXT' file Read or EOF Error */ Error_Handler(); } else { /*##-9- Close the open text file #############################*/ f_close(&MyFile); /*##-10- Compare read data with the expected data ############*/ if((bytesread != byteswritten)) { /* Read data is different from the expected data */ Error_Handler(); } else { /* Success of the demo: no error occurrence */ BSP_LED_On(LED1); } } } } } } } } /*##-11- Unlink the RAM disk I/O driver ####################################*/ FATFS_UnLinkDriver(SDPath); /* Infinite Loop */ for( ;; ) { } }
/** * @brief Main program * @param None * @retval None */ int main(void) { FRESULT res; /* FatFs function common result code */ uint32_t byteswritten, bytesread; /* File write/read counts */ uint8_t wtext[] = "This is STM32 working with FatFs"; /* File write buffer */ uint8_t rtext[100]; /* File read buffer */ /* STM32F4xx HAL library initialization: - Configure the Flash prefetch, instruction and Data caches - Configure the Systick to generate an interrupt each 1 msec - Set NVIC Group Priority to 4 - Global MSP (MCU Support Package) initialization */ HAL_Init(); /* Configure LED3 and LED4 */ BSP_LED_Init(LED3); BSP_LED_Init(LED4); /* Configure the system clock to 180 Mhz */ SystemClock_Config(); /*##-1- Link the RAM disk I/O driver #######################################*/ if(FATFS_LinkDriver(&SDRAMDISK_Driver, RAMDISKPath) == 0) { /*##-2- Register the file system object to the FatFs module ##############*/ if(f_mount(&RAMDISKFatFs, (TCHAR const*)RAMDISKPath, 0) != FR_OK) { /* FatFs Initialization Error */ Error_Handler(); } else { /*##-3- Create a FAT file system (format) on the logical drive #########*/ if(f_mkfs((TCHAR const*)RAMDISKPath, 0, 0) != FR_OK) { /* FatFs Format Error */ Error_Handler(); } else { /*##-4- Create and Open a new text file object with write access #####*/ if(f_open(&MyFile, "STM32.TXT", FA_CREATE_ALWAYS | FA_WRITE) != FR_OK) { /* 'STM32.TXT' file Open for write Error */ Error_Handler(); } else { /*##-5- Write data to the text file ################################*/ res = f_write(&MyFile, wtext, sizeof(wtext), (void *)&byteswritten); if((byteswritten == 0) || (res != FR_OK)) { /* 'STM32.TXT' file Write or EOF Error */ Error_Handler(); } else { /*##-6- Close the open text file #################################*/ f_close(&MyFile); /*##-7- Open the text file object with read access ###############*/ if(f_open(&MyFile, "STM32.TXT", FA_READ) != FR_OK) { /* 'STM32.TXT' file Open for read Error */ Error_Handler(); } else { /*##-8- Read data from the text file ###########################*/ res = f_read(&MyFile, rtext, sizeof(rtext), (void *)&bytesread); if((bytesread == 0) || (res != FR_OK)) { /* 'STM32.TXT' file Read or EOF Error */ Error_Handler(); } else { /*##-9- Close the open text file #############################*/ f_close(&MyFile); /*##-10- Compare read data with the expected data ############*/ if ((bytesread != byteswritten)) { /* Read data is different from the expected data */ Error_Handler(); } else { /* Success of the demo: no error occurrence */ BSP_LED_On(LED3); } } } } } } } } /*##-11- Unlink the RAM disk I/O driver ####################################*/ FATFS_UnLinkDriver(RAMDISKPath); /* Infinite loop */ while (1) { } }
/******************************************************************************* * Function Name : SD_Read * Description : Read from SD * Input : * String, length * Output : None * Return : None *******************************************************************************/ void SD_Read(char *file_data, int length) { unsigned int number; f_read(&file,file_data,length,&number); }