// Prepare to capturing: // + create folder // + chdir to it // + check if file already exist uint8_t sdc_prepare(void) { FRESULT res; res=f_mkdir_recursive(FDR_INFO.dir_name); if (res!=FR_OK && res!=FR_EXIST) return SDCP_MKDIR_ERR; f_chdir("/"); res=f_chdir(FDR_INFO.dir_name); if (res!=FR_OK) return SDCP_CHDIR_ERR; // check single file mode if (FDR_INFO.single_file) { res=open_file(); if (res==FR_EXIST) return SDCP_EXIST; else if (res!=FR_OK) return SDCP_OPEN_ERR; } return SDCP_OK; }
static void prvCreateDemoFileUsing_f_putc( void ) { unsigned char ucReturn; int iByte, iReturned; F_FILE *pxFile; char cFileName[ fsMAX_FILE_NAME_LEN ]; /* Obtain and print out the working directory. */ f_getcwd( cRAMBuffer, fsRAM_BUFFER_SIZE ); /* Create a sub directory. */ ucReturn = f_mkdir( pcDirectory1 ); configASSERT( ucReturn == F_NO_ERROR ); /* Move into the created sub-directory. */ ucReturn = f_chdir( pcDirectory1 ); configASSERT( ucReturn == F_NO_ERROR ); /* Obtain and print out the working directory. */ f_getcwd( cRAMBuffer, fsRAM_BUFFER_SIZE ); /* Create a subdirectory in the new directory. */ ucReturn = f_mkdir( pcDirectory2 ); configASSERT( ucReturn == F_NO_ERROR ); /* Move into the directory just created - now two directories down from the root. */ ucReturn = f_chdir( pcDirectory2 ); configASSERT( ucReturn == F_NO_ERROR ); /* Obtain and print out the working directory. */ f_getcwd( cRAMBuffer, fsRAM_BUFFER_SIZE ); configASSERT( strcmp( cRAMBuffer, pcFullPath ) == 0 ); /* Generate the file name. */ sprintf( cFileName, "%s.txt", pcDirectory2 ); /* Print out the file name and the directory into which the file is being written. */ pxFile = f_open( cFileName, "w" ); /* Create a file 1 byte at a time. The file is filled with incrementing ascii characters starting from '0'. */ for( iByte = 0; iByte < fsPUTC_FILE_SIZE; iByte++ ) { iReturned = f_putc( ( ( int ) '0' + iByte ), pxFile ); configASSERT( iReturned == ( ( int ) '0' + iByte ) ); } /* Finished so close the file. */ f_close( pxFile ); /* Move back to the root directory. */ ucReturn = f_chdir( "../.." ); configASSERT( ucReturn == F_NO_ERROR ); /* Obtain and print out the working directory. */ f_getcwd( cRAMBuffer, fsRAM_BUFFER_SIZE ); configASSERT( strcmp( cRAMBuffer, pcRoot ) == 0 ); }
bool TestExtProcess::test_shell_exec() { Variant output = f_shell_exec("echo hello"); VS(output, "hello\n"); string cur_cwd = Process::GetCurrentDirectory(); f_chdir("/tmp/"); VS(f_shell_exec("/bin/pwd"), "/tmp\n"); f_chdir(String(cur_cwd)); return Count(true); }
bool TestExtFile::test_is_dir() { f_mkdir("test/tmp_dir"); VERIFY(!f_is_dir("test/test_ext_file.txt")); VERIFY(f_is_dir("test/tmp_dir")); VERIFY(!f_is_dir("tmp_dir")); f_chdir("test"); VERIFY(!f_is_dir("test/tmp_dir")); VERIFY(f_is_dir("tmp_dir")); f_rmdir("test/tmp_dir"); f_chdir(".."); return Count(true); }
bool TestExtProcess::test_exec() { Variant output, ret; String last_line = f_exec("echo hello; echo world;", ref(output), ref(ret)); VS(output, CREATE_VECTOR2("hello", "world")); VS(last_line, "world"); VS(ret, 0); string cur_cwd = Process::GetCurrentDirectory(); f_chdir("/tmp/"); VS(f_exec("/bin/pwd"), "/tmp"); f_chdir(String(cur_cwd)); return Count(true); }
static int dlg_ActiveMainDialog(const osd_command_t *cmd) { int result = -1; f_chdir("/"); //destroy subdialog if exist if(pdlg_sub) { osd_DestroyDialog(hdlg_sub); hdlg_sub = 0; dlg_FreeDialog(pdlg_sub); pdlg_sub = 0; } if(!pdlg_main) { pdlg_main = dlg_CreateDialog(cmds_main); } if(pdlg_main) { hdlg_main = osd_ConstructDialog(pdlg_main); osd_SetActiveDialog(hdlg_main); result = 0; } return result; }
void Config_Read(void) { FRESULT res; res = Config_ReadSingle("\\", "config.txt"); if (res != FR_OK) { res = f_chdir("\\"); res = f_open(&Main_file, "config.txt", FA_WRITE | FA_CREATE_ALWAYS); if (res != FR_OK) { Main_activeLED = LEDS_RED; LEDs_ChangeLEDs(LEDS_ALL_LEDS, Main_activeLED); return ; } Config_WriteString_P(Config_default, &Main_file); f_close(&Main_file); } eeprom_read_block(UBX_buf, CONFIG_FNAME_ADDR, CONFIG_FNAME_LEN); if (UBX_buf[0] != 0 && UBX_buf[0] != 0xff) { res = Config_ReadSingle("\\config", UBX_buf); } }
static int dlg_StartProgram(const osd_command_t *cmd) { char *fname; osd_group_t *grp = osd_GetCurrentGroup(); if(grp == NULL) return -1; fname = (char *)(grp->items[0].v); f_chdir(fname); //destroy subdialog if exist if(pdlg_sub) { osd_DestroyDialog(hdlg_sub); hdlg_sub = 0; dlg_FreeDialog(pdlg_sub); pdlg_sub = 0; } //active programming dialog dlg_prog_time = 0; pdlg_sub = dlg_CreateProgDialog(); if(pdlg_sub) { hdlg_sub = osd_ConstructDialog(pdlg_sub); osd_SetActiveDialog(hdlg_sub); } //start programming hvp_prog(0, 0); return 0; }
static void fatfsCdCmd(UINT8 argc, const char *argv[]) { if (argc == 2 && (strcmp(argv[1], "-h") == 0)) { fatfsCdCmdUsage(); } else if (argc == 2) { FRESULT r = f_chdir(argv[1]); if (r == FR_OK) { UINT8 buf[PWD_MAX_LEN]; f_getcwd(buf, PWD_MAX_LEN); LOG("\t%s", buf); } else { fatfsConsoleError(r); } } else { fatfsCdCmdUsage(); } }
bool TestExtProcess::test_system() { g_context->obStart(); Variant ret; String last_line = f_system("echo hello; echo world;", ref(ret)); String output = g_context->obCopyContents(); g_context->obEnd(); VS(output, "hello\nworld\n"); VS(last_line, "world"); VS(ret, 0); string cur_cwd = Process::GetCurrentDirectory(); f_chdir("/tmp/"); VS(f_system("/bin/pwd"), "/tmp"); f_chdir(String(cur_cwd)); return Count(true); }
void MessageStorage::changeDirectory(char * dir) { module_debug_strg("chdir %s", dir); m_fr = f_chdir(dir); if(m_fr != FR_OK) module_debug_strg("chdir failed! %d", m_fr); }
static void prvVerifyDemoFileUsing_f_getc( void ) { unsigned char ucReturn; int iByte, iReturned; F_FILE *pxFile; char cFileName[ fsMAX_FILE_NAME_LEN ]; /* Move into the directory in which the file was created. */ ucReturn = f_chdir( pcFullPath ); configASSERT( ucReturn == F_NO_ERROR ); /* Obtain and print out the working directory. */ f_getcwd( cRAMBuffer, fsRAM_BUFFER_SIZE ); printf( "Back in directory %s\r\n", cRAMBuffer ); configASSERT( strcmp( cRAMBuffer, pcFullPath ) == 0 ); /* Generate the file name. */ sprintf( cFileName, "%s.txt", pcDirectory2 ); /* Print out the file name and the directory from which the file is being read. */ printf( "Reading file %s in %s\r\n", cFileName, cRAMBuffer ); /* This time the file is opened for reading. */ pxFile = f_open( cFileName, "r" ); /* Read the file 1 byte at a time. */ for( iByte = 0; iByte < fsPUTC_FILE_SIZE; iByte++ ) { iReturned = f_getc( pxFile ); configASSERT( iReturned == ( ( int ) '0' + iByte ) ); } /* Finished so close the file. */ f_close( pxFile ); /* Move back to the root directory. */ ucReturn = f_chdir( "../.." ); configASSERT( ucReturn == F_NO_ERROR ); /* Obtain and print out the working directory. */ f_getcwd( cRAMBuffer, fsRAM_BUFFER_SIZE ); printf( "Back in root directory %s\r\n", cRAMBuffer ); }
void badge_fahrplan(void) { f_chdir(FAHRPLAN_PATH); uint8_t oldpos = badge_load_fahrplan_pos(); uint8_t pos = oldpos; badge_browse_textfiles(FAHRPLAN_MENUFILE, &pos); if(oldpos != pos) { badge_save_fahrplan_pos(pos); } }
uint8_t menu_start(const char *path) { Finfo.lfname = Lfname; Finfo.lfsize = sizeof(Lfname); res = f_mount(0, &fatfs); if (res) { uart_puts_P("f_mount failed\r\n"); return; } res = f_chdir("0:/music"); if (res) { uart_puts_P("f_chdir failed\r\n"); return; } }
void OnChangeDir(nwazetMessageContext_t* nmc){ uint8_t res = (uint8_t) FR_OK; uint8_t isTextASCII = 0; uint16_t textLength = 0; const char* dirname = (const char*)GetStringReference(nmc->cmdContext, &textLength, &isTextASCII); if(dirname && isTextASCII){ res = fsCheckSuccess(__func__, "f_chdir", f_chdir(dirname), dirname); StartResponse(nmc, res, true); return; } res = FR_INVALID_NAME; fsCheckSuccess(__func__, "dirname", res, dirname); StartResponse(nmc, res, true); }
static bool switchToMainDir(bool isSd) { const char *mainDir = isSd ? "/luma" : "/rw/luma"; switch(f_chdir(mainDir)) { case FR_OK: return true; case FR_NO_PATH: return f_mkdir(mainDir) == FR_OK && switchToMainDir(isSd); default: return false; } }
uint8_t main_menu_show(uint8_t selected) { // first_visible = 0, weil das Menü so kurz ist. Sollte es // größer werden: Parameter aus main_menu empfangen und merken. uint8_t first_visible = 0; char const *const menu[] = { "Titelbild", "Super Hackio", "Fahrplan", "USB-Modus" }; f_chdir("/"); return (uint8_t) badge_menu(menu, ARRAY_SIZE(menu), &first_visible, selected); }
INT32 S2wCert_SearchFlash(char *ptr) { F_FILE *fd; if(!s2wappMainTaskCtxt->fsInit) { App_FsInit(); s2wappMainTaskCtxt->fsInit = TRUE; f_enterFS(); } f_chdir("certs"); fd = f_open(ptr, "r"); f_chdir(".."); if(fd) { f_close(fd); return -1; } else { return 0; } }
/** * Changes current directory * * \param char* ndir_chg - char[] with directory to change * \return TRUE - operation success * \return FALSE - operation failed */ BOOL SDDirChange(char* ndir_chg) { #if (_FS_RPATH < 1) return FALSE; #else fRes = f_chdir(ndir_chg); if(fRes != FR_OK) { errManager(); return FALSE; } return TRUE; #endif }
void delete_file(const TCHAR *dir, const TCHAR *file_name) { FATFS fs; DIR dirs; FRESULT res; res = f_mount(0,&fs); if (res != FR_OK) { printf("\r\n挂载文件系统失败,错误: %u",res); return; } res = f_opendir(&dirs,(const TCHAR*)"/"); res = f_chdir(dir); res = f_unlink((TCHAR *)file_name); f_mount(0,NULL); }
//--------------------------------------------------------------------+ // tinyusb callbacks //--------------------------------------------------------------------+ void tuh_msc_mounted_cb(uint8_t dev_addr) { puts("\na MassStorage device is mounted"); //------------- Disk Information -------------// // SCSI VendorID[8] & ProductID[16] from Inquiry Command uint8_t const* p_vendor = tuh_msc_get_vendor_name(dev_addr); uint8_t const* p_product = tuh_msc_get_product_name(dev_addr); for(uint8_t i=0; i<8; i++) putchar(p_vendor[i]); putchar(' '); for(uint8_t i=0; i<16; i++) putchar(p_product[i]); putchar('\n'); uint32_t last_lba, block_size; tuh_msc_get_capacity(dev_addr, &last_lba, &block_size); printf("Disk Size: %d MB\n", (last_lba+1)/ ((1024*1024)/block_size) ); printf("LBA 0-0x%X Block Size: %d\n", last_lba, block_size); //------------- file system (only 1 LUN support) -------------// uint8_t phy_disk = dev_addr-1; disk_initialize(phy_disk); if ( disk_is_ready(phy_disk) ) { if ( f_mount(phy_disk, &fatfs[phy_disk]) != FR_OK ) { puts("mount failed"); return; } puts("---------------------------------------------------------------------"); puts("- MASSSTORAGE CLASS CLI IS A IMMATURE CODE. DISK-WRITING COMMANDS"); puts("- SUCH AS cp(COPY), mkdir(MAKE DIRECTORY) ARE POTENTIAL TO DAMAGE"); puts("- YOUR USB THUMBDRIVE. USING THOSE COMMANDS ARE AT YOUR OWN RISK."); puts("- THE AUTHOR HAS NO RESPONSIBILITY WITH YOUR DEVICE NOR ITS DATA"); puts("---------------------------------------------------------------------"); f_chdrive(phy_disk); // change to newly mounted drive f_chdir("/"); // root as current dir cli_init(); } }
char *read_file(const TCHAR *dir,const TCHAR *file_name,int offset,int length) { FATFS fs; FIL file; FRESULT res; // DIR dirs; // FILINFO finfo; uint32_t re; res = f_mount(0,&fs); res = f_chdir(dir); res = f_open(&file,file_name,FA_READ); res = f_lseek (&file, offset); res = f_read(&file,buffer,length,&re); f_close(&file); f_mount(0,NULL); return buffer; }
static int dlg_ActiveSubDialog(const osd_command_t *cmd) { char *fname; osd_group_t *grp = osd_GetCurrentGroup(); if(grp == NULL) return -1; fname = (char *)(grp->items[0].v); f_chdir(fname); pdlg_sub = dlg_CreateDialog(cmds_sub); if(pdlg_sub) { osd_DestroyDialog(hdlg_main); hdlg_sub = osd_ConstructDialog(pdlg_sub); osd_SetActiveDialog(hdlg_sub); } return 0; }
void loadNextFile() { int res; char *dotPointer; do { res=f_readdir(&dir, &fileInfo); if (res) { die(4,res); } if(fileInfo.fname[0] == 0) break; dotPointer = strrchr(fileInfo.fname, '.'); } while(dotPointer == NULL || strcasecmp(dotPointer, ".mod")); f_chdir (MOD_PATH); if(fileInfo.fname[0] != 0) { f_open(&file, fileInfo.fname, FA_READ); message("Opened File: %s ",fileInfo.fname); loadMod(); message("Song name: [%s]\n",Mod.name); } }
void game_init() { // XXX better check those errors ! int res; f_mount(&fso,"",1); //mount now res = f_opendir(&dir, MOD_PATH); if (res != FR_OK) { message ("wtf no dir\n"); die(3,res); } res = f_chdir(MOD_PATH); if (res) { message ("wtf no dir\n"); die(2,res); } loadNextFile(); }
static portBASE_TYPE prvCDCommand( char *pcWriteBuffer, size_t xWriteBufferLen, const char *pcCommandString ) { const char *pcParameter; portBASE_TYPE xParameterStringLength; unsigned char ucReturned; size_t xStringLength; /* Obtain the parameter string. */ pcParameter = FreeRTOS_CLIGetParameter ( pcCommandString, /* The command string itself. */ 1, /* Return the first parameter. */ &xParameterStringLength /* Store the parameter string length. */ ); /* Sanity check something was returned. */ configASSERT( pcParameter ); /* Attempt to move to the requested directory. */ ucReturned = f_chdir( pcParameter ); if( ucReturned == F_NO_ERROR ) { sprintf( pcWriteBuffer, "In: " ); xStringLength = strlen( pcWriteBuffer ); f_getcwd( &( pcWriteBuffer[ xStringLength ] ), ( unsigned char ) ( xWriteBufferLen - xStringLength ) ); } else { sprintf( pcWriteBuffer, "Error" ); } strcat( pcWriteBuffer, cliNEW_LINE ); return pdFALSE; }
void menuUp1(uint8_t event) { FRESULT fr ; struct fileControl *fc = &FileControl ; static uint8_t mounted = 0 ; static uint32_t state ; static uint32_t firmwareAddress ; uint32_t i ; uint32_t width ; if (UpdateItem == UPDATE_TYPE_BOOTLOADER ) // Bootloader { TITLE( "UPDATE BOOT" ) ; } else { #ifdef PCBX9D if (UpdateItem == UPDATE_TYPE_SPORT_INT ) { TITLE( "UPDATE Int. XJT" ) ; } else { TITLE( "UPDATE Ext. SPort" ) ; } #endif #ifdef PCBSKY #ifndef REVX if (UpdateItem == UPDATE_TYPE_COPROCESSOR ) { TITLE( "UPDATE COPROC" ) ; } else { TITLE( "UPDATE SPort" ) ; } #else if (UpdateItem == UPDATE_TYPE_SPORT_EXT ) { TITLE( "UPDATE SPort" ) ; } #endif #endif } switch(event) { case EVT_ENTRY: state = UPDATE_NO_FILES ; if ( mounted == 0 ) { #if defined(PCBTARANIS) fr = f_mount(0, &g_FATFS_Obj) ; #else fr = f_mount(0, &g_FATFS) ; #endif #ifdef PCBX9D unlockFlash() ; #endif } else { fr = FR_OK ; } if ( fr == FR_OK) { mounted = 1 ; } if ( mounted ) { fr = f_chdir( (TCHAR *)"\\firmware" ) ; if ( fr == FR_OK ) { state = UPDATE_NO_FILES ; fc->index = 0 ; fr = f_opendir( &Dj, (TCHAR *) "." ) ; if ( fr == FR_OK ) { if ( (UpdateItem > 1 ) ) { fc->ext[0] = 'F' ; fc->ext[1] = 'R' ; fc->ext[2] = 'K' ; } else { fc->ext[0] = 'B' ; fc->ext[1] = 'I' ; fc->ext[2] = 'N' ; } fc->ext[3] = 0 ; fc->index = 0 ; fc->nameCount = fillNames( 0, fc ) ; fc->hpos = 0 ; fc->vpos = 0 ; if ( fc->nameCount ) { state = UPDATE_FILE_LIST ; } } } } break ; case EVT_KEY_FIRST(KEY_EXIT): if ( state < UPDATE_ACTION ) { chainMenu(menuUpdate) ; killEvents(event) ; } break ; } switch ( state ) { case UPDATE_NO_FILES : lcd_puts_Pleft( 4*FH, "\005No Files" ) ; lcd_outdez( 21*FW, 4*FH, mounted ) ; break ; case UPDATE_FILE_LIST : SportVerValid = 0 ; if ( fileList( event, &FileControl ) == 1 ) { state = UPDATE_CONFIRM ; } break ; case UPDATE_CONFIRM : if ( (UpdateItem > UPDATE_TYPE_BOOTLOADER ) ) { #ifdef PCBX9D if ( (UpdateItem == UPDATE_TYPE_SPORT_INT ) ) { lcd_puts_Pleft( 2*FH, "Flash Int. XJT from" ) ; } else { lcd_puts_Pleft( 2*FH, "Flash Ext.SP from" ) ; } SportVerValid = 0 ; #else #ifndef REVX if ( (UpdateItem == UPDATE_TYPE_COPROCESSOR ) ) { lcd_puts_Pleft( 2*FH, "Flash Co-Proc. from" ) ; } else { lcd_puts_Pleft( 2*FH, "Flash SPort from" ) ; } CoProcReady = 0 ; #else lcd_puts_Pleft( 2*FH, "Flash SPort from" ) ; #endif #endif } else { lcd_puts_Pleft( 2*FH, "Flash Bootloader from" ) ; } cpystr( cpystr( (uint8_t *)FlashFilename, (uint8_t *)"\\firmware\\" ), (uint8_t *)Filenames[fc->vpos] ) ; #if defined(PCBTARANIS) lcd_putsnAtt( 0, 4*FH, Filenames[fc->vpos], DISPLAY_CHAR_WIDTH, 0 ) ; #else lcd_putsnAtt0( 0, 4*FH, Filenames[fc->vpos], DISPLAY_CHAR_WIDTH, 0 ) ; #endif if ( event == EVT_KEY_LONG(KEY_MENU) ) { state = UPDATE_SELECTED ; } if ( event == EVT_KEY_LONG(KEY_EXIT) ) { state = UPDATE_FILE_LIST ; // Canceled } break ; case UPDATE_SELECTED : f_open( &FlashFile, FlashFilename, FA_READ ) ; f_read( &FlashFile, (BYTE *)FileData, 1024, &BlockCount ) ; i = 1 ; if (UpdateItem == UPDATE_TYPE_BOOTLOADER ) // Bootloader { i = validateFile( (uint32_t *) FileData ) ; } if ( i == 0 ) { state = UPDATE_INVALID ; } else { if (UpdateItem == UPDATE_TYPE_BOOTLOADER ) // Bootloader { #ifdef PCBX9D firmwareAddress = 0x08000000 ; #endif #ifdef PCBSKY firmwareAddress = 0x00400000 ; #endif } #ifdef PCBSKY #ifndef REVX else if (UpdateItem == UPDATE_TYPE_COPROCESSOR ) // Bootloader { firmwareAddress = 0x00000080 ; if ( check_ready() == 0 ) { CoProcReady = 1 ; } } #endif #endif else { // SPort update SportState = SPORT_START ; FirmwareSize = FileSize[fc->vpos] ; BlockInUse = 0 ; f_read( &FlashFile, (BYTE *)ExtraFileData, 1024, &XblockCount ) ; } BytesFlashed = 0 ; BlockOffset = 0 ; ByteEnd = 1024 ; state = UPDATE_ACTION ; } break ; case UPDATE_INVALID : lcd_puts_Pleft( 2*FH, "Invalid File" ) ; lcd_puts_Pleft( 4*FH, "Press EXIT" ) ; if ( event == EVT_KEY_FIRST(KEY_EXIT) ) { state = UPDATE_FILE_LIST ; // Canceled killEvents(event) ; } break ; case UPDATE_ACTION : // Do the flashing lcd_puts_Pleft( 3*FH, "Flashing" ) ; if (UpdateItem == UPDATE_TYPE_BOOTLOADER ) // Bootloader { width = ByteEnd >> 9 ; if ( BytesFlashed < ByteEnd ) { program( (uint32_t *)firmwareAddress, &((uint32_t *)FileData)[BlockOffset] ) ; // size is 256 bytes BlockOffset += 64 ; // 32-bit words (256 bytes) firmwareAddress += 256 ; BytesFlashed += 256 ; } else { if ( ByteEnd >= 32768 ) { state = UPDATE_COMPLETE ; } else { f_read( &FlashFile, (BYTE *)FileData, 1024, &BlockCount ) ; ByteEnd += 1024 ; BlockOffset = 0 ; } } } #ifdef PCBSKY #ifndef REVX else if (UpdateItem == UPDATE_TYPE_COPROCESSOR ) // CoProcessor
int main(void) { uint32_t data_counter=0; //used as data timestamp uint8_t deadly_flashes=0,system_state=0,repetition_counter=0; int16_t sensor_data, sensor_raw_data[3]={}; //used for handling data passed back from sensors int16_t sfe_sensor_ref_buff[2][3],sfe_sensor_ref_buff_old[2][3];//used to detect and fix I2C bus lockup RTC_t RTC_time; wave_stuffer Gyro_wav_stuffer={0,0},Accel_wav_stuffer={0,0};//Used to controlling wav file bit packing SystemInit(); //Sets up the clk setup_gpio(); //Initialised pins, and detects boot source DBGMCU_Config(DBGMCU_IWDG_STOP, ENABLE); //Watchdog stopped during JTAG halt if(RCC->CSR&RCC_CSR_IWDGRSTF) { //Watchdog reset, turn off RCC->CSR|=RCC_CSR_RMVF; //Reset the reset flags shutdown(); } SysTick_Configuration(); //Start up system timer at 100Hz for uSD card functionality Watchdog_Config(WATCHDOG_TIMEOUT); //Set the watchdog Watchdog_Reset(); //Reset watchdog as soon as possible incase it is still running at power on rtc_init(); //Real time clock initialise - (keeps time unchanged if set) Usarts_Init(); ISR_Config(); rprintfInit(__usart_send_char); //Printf over the bluetooth if(USB_SOURCE==bootsource) { Set_System(); //This actually just inits the storage layer Set_USBClock(); USB_Interrupts_Config(); USB_Init(); uint32_t nojack=0x000FFFFF; //Countdown timer - a few hundered ms of 0v on jack detect forces a shutdown while (bDeviceState != CONFIGURED) { //Wait for USB config - timeout causes shutdown if(Millis>10000 || !nojack) //No USB cable - shutdown (Charger pin will be set to open drain, cant be disabled without usb) shutdown(); if(GET_CHRG_STATE) //Jack detect resets the countdown nojack=0x0FFFFF; nojack--; Watchdog_Reset(); //Reset watchdog here, if we are stalled here the Millis timeout should catch us } USB_Configured_LED(); EXTI_ONOFF_EN(); //Enable the off interrupt - allow some time for debouncing while(1) { //If running off USB (mounted as mass storage), stay in this loop - dont turn on anything if(Millis%1000>500) //1Hz on/off flashing switch_leds_on(); //Flash the LED(s) else switch_leds_off(); Watchdog_Reset(); __WFI(); //Sleep until something arrives } } else { if(!GET_PWR_STATE) //Check here to make sure the power button is still pressed, if not, sleep shutdown(); //This means a glitch on the supply line, or a power glitch results in sleep EXTI_ONOFF_EN(); //Enable the off interrupt - allow some time for debouncing ADC_Configuration(); //At present this is purely here to detect low battery do { battery_voltage=Battery_Voltage;//Have to flush adc for some reason Delay(25000); } while(fabs(Battery_Voltage-battery_voltage)>0.01 || !battery_voltage); I2C_Config(); //Setup the I2C bus Sensors=detect_sensors(0); //Search for connected sensors if(battery_voltage<BATTERY_STARTUP_LIMIT) deadly_flashes=1; if(!(Sensors&(1<<FOREHEAD_ACCEL))) //Check for any missing sensors deadly_flashes=2; if(!(Sensors&(1<<(FOREHEAD_GYRO-1)))) deadly_flashes=3; if(!(Sensors&(1<<(SFE_1_ACCEL-1)))) deadly_flashes=4; if(!(Sensors&(1<<(SFE_1_MAGNO-1)))) deadly_flashes=5; if(!(Sensors&(1<<(SFE_1_GYRO-1)))) deadly_flashes=6; if(!(Sensors&(1<<(SFE_2_ACCEL-3)))) deadly_flashes=7; if(!(Sensors&(1<<(SFE_2_MAGNO-3)))) deadly_flashes=8; if(!(Sensors&(1<<(SFE_2_GYRO-3)))) deadly_flashes=9; if((f_err_code = f_mount(0, &FATFS_Obj)))Usart_Send_Str((char*)"FatFs mount error\r\n");//This should only error if internal error else if(!deadly_flashes){ //FATFS and the I2C initialised ok, try init the card, this also sets up the SPI1 if(!f_open(&FATFS_logfile,"time.txt",FA_OPEN_EXISTING | FA_READ | FA_WRITE)) {//Try and open a time file to get the system time if(!f_stat((const TCHAR *)"time.txt",&FATFS_info)) {//Get file info if(!FATFS_info.fsize) {//Empty file RTC_time.year=(FATFS_info.fdate>>9)+1980;//populate the time struct (FAT start==1980, RTC.year==0) RTC_time.month=(FATFS_info.fdate>>5)&0x000F; RTC_time.mday=FATFS_info.fdate&0x001F; RTC_time.hour=(FATFS_info.ftime>>11)&0x001F; RTC_time.min=(FATFS_info.ftime>>5)&0x003F; RTC_time.sec=(FATFS_info.ftime<<1)&0x003E; rtc_settime(&RTC_time); rprintfInit(__fat_print_char);//printf to the open file printf("RTC set to %d/%d/%d %d:%d:%d\n",RTC_time.mday,RTC_time.month,RTC_time.year,\ RTC_time.hour,RTC_time.min,RTC_time.sec); } } f_close(&FATFS_logfile);//Close the time.txt file } rtc_gettime(&RTC_time); //Get the RTC time and put a timestamp on the start of the file rprintfInit(__str_print_char); //Print to the string //timestamp name printf("%d-%02d-%02dT%02d-%02d-%02d",RTC_time.year,RTC_time.month,RTC_time.mday,RTC_time.hour,RTC_time.min,RTC_time.sec); rprintfInit(__usart_send_char); //Printf over the bluetooth f_err_code = f_mkdir(print_string); //Try to make a directory where the logfiles will live if(f_err_code) { printf("FatFs drive error %d\r\n",f_err_code); if(f_err_code==FR_DISK_ERR || f_err_code==FR_NOT_READY) Usart_Send_Str((char*)"No uSD card inserted?\r\n"); repetition_counter=1; } else f_err_code=f_chdir(print_string);//enter our new directory if(f_err_code) { if(!repetition_counter) printf("FatFs drive error entering direcotry %d\r\n",f_err_code); repetition_counter=1; } else { strcat(print_string,".csv"); f_err_code=f_open(&FATFS_logfile,print_string,FA_CREATE_ALWAYS | FA_WRITE);//Try to open the main 100sps csv logfile } if(f_err_code) { if(!repetition_counter) printf("FatFs drive error creating logfile %d\r\n",f_err_code); repetition_counter=1; } else { print_string[strlen(print_string)-4]=0x00; //Wipe the .csv off the string strcat(print_string,"_accel.wav"); f_err_code=f_open(&FATFS_wavfile_accel,print_string,FA_CREATE_ALWAYS | FA_WRITE);//Try to open the accel wav logfile } if(f_err_code) { if(!repetition_counter) printf("FatFs drive error creating accel wav file %d\r\n",f_err_code); repetition_counter=1; } else { print_string[strlen(print_string)-9]=0x00; //Wipe the accel.wav off the string strcat(print_string,"gyro.wav"); f_err_code=f_open(&FATFS_wavfile_gyro,print_string,FA_CREATE_ALWAYS | FA_WRITE);//Try to open the gyro wav logfile } if(f_err_code) { if(!repetition_counter) printf("FatFs drive error creating gyro wav file %d\r\n",f_err_code); } else { //We have a mounted card print_string[0]=0x00; //Wipe the string f_err_code=f_lseek(&FATFS_logfile, PRE_SIZE);// Pre-allocate clusters if (f_err_code || f_tell(&FATFS_logfile) != PRE_SIZE)// Check if the file size has been increased correctly Usart_Send_Str((char*)"Pre-Allocation error\r\n"); else { if((f_err_code=f_lseek(&FATFS_logfile, 0)))//Seek back to start of file to start writing Usart_Send_Str((char*)"Seek error\r\n"); else rprintfInit(__str_print_char);//Printf to the logfile } if(f_err_code) f_close(&FATFS_logfile);//Close the already opened file on error else file_opened=0x01;//So we know to close the file properly on shutdown - bit mask for the files if(!f_err_code) { f_err_code=f_lseek(&FATFS_wavfile_accel, PRE_SIZE);// Pre-allocate clusters if (f_err_code || f_tell(&FATFS_wavfile_accel) != PRE_SIZE)// Check if the file size has been increased correctly Usart_Send_Str((char*)"Pre-Allocation error\r\n"); else { if((f_err_code=f_lseek(&FATFS_wavfile_accel, 0)))//Seek back to start of file to start writing Usart_Send_Str((char*)"Seek error\r\n"); } if(f_err_code) f_close(&FATFS_wavfile_accel);//Close the already opened file on error else file_opened|=0x02;//So we know to close the file properly on shutdown - bit mask for the files } if(!f_err_code) { f_err_code=f_lseek(&FATFS_wavfile_gyro, PRE_SIZE);// Pre-allocate clusters if (f_err_code || f_tell(&FATFS_wavfile_gyro) != PRE_SIZE)// Check if the file size has been increased correctly Usart_Send_Str((char*)"Pre-Allocation error\r\n"); else { if((f_err_code=f_lseek(&FATFS_wavfile_gyro, 0)))//Seek back to start of file to start writing Usart_Send_Str((char*)"Seek error\r\n"); } if(f_err_code) f_close(&FATFS_wavfile_gyro);//Close the already opened file on error else file_opened|=0x04;//So we know to close the file properly on shutdown - bit mask for the files } } } repetition_counter=0; //Reset this here //We die, but flash out a number of flashes first if(f_err_code || deadly_flashes) { //There was an init error for(;deadly_flashes;deadly_flashes--) { RED_LED_ON; Delay(200000); RED_LED_OFF; Delay(200000); Watchdog_Reset(); } RED_LED_ON; Delay(400000); shutdown(); //Abort after a (further )single red flash } }
void edit_file(const TCHAR *dir,const TCHAR *write_file,char *write_data,uint32_t index) { FATFS fs; FIL file; FRESULT res; DIR dirs; uint32_t n_write=0x00; uint32_t n_written = 0x00; for(n_write=0;*write_data++!='\0';) { n_write++; } write_data=write_data-n_write-1; res = f_mount(0,&fs); if (res != FR_OK) { printf("\r\n挂载文件系统失败,错误代码: %u",res); return; } res = f_opendir(&dirs,(const TCHAR*)"/"); res = f_chdir(dir); res = f_open(&file,write_file,FA_READ | FA_WRITE); res = f_lseek (&file, index); if (res == FR_OK) { if(n_write<=512) { res = f_write(&file,write_data,n_write,&n_written); if ((res == FR_OK) && (n_written==n_write)) { f_close(&file); } else { printf("\r\n保存数据失败!"); printf("\r\n错误代码: %u",res); } } else { while(*write_data!='\0') { res = f_write(&file,write_data,512,&n_written); if ((res == FR_OK) && (n_written==512)) { f_close(&file); } else { printf("\r\n保存数据失败!"); printf("\r\n错误代码: %u",res); } write_data+=512; index+=512; res = f_open(&file,write_file,FA_READ | FA_WRITE); res = f_lseek (&file, index); } } } else { printf("\r\n打开文件失败,错误代码: %u",res); } f_mount(0,NULL); }
/* * File Select Menu */ int file_menu(unsigned int level, unsigned int select) { FRESULT f; unsigned int total,offset,num,i; unsigned char *items; BYTE *attrib; f=f_opendir(&dirs, "\0"); // current directory switch(f){ case FR_OK: total=0; offset=0; num=0; while((f_readdir(&dirs, &finfo) == FR_OK) && finfo.fname[0]){ total++; } break; case FR_INT_ERR: case FR_NOT_READY: default: return(-1); break; } f_readdir(&dirs, (FILINFO *)NULL); // rewind items=malloc(total*13); attrib=malloc(total*sizeof(BYTE)); for(i=0;i<total;i++){ f_readdir(&dirs, &finfo); memcpy(&items[i*13], finfo.fname, 13); attrib[i]=finfo.fattrib; } if(total>23){ frame(level,23,select); }else{ frame(level,total,select); } disp_files(level,&items[offset],total); MZ_disp(level*13+13,num+1,0x04); while(1){ if((z80_sts.status&S_FBTN)==0){ free(items); free(attrib); return(-1); } switch(get_key()){ case 0x08: // directory back MZ_disp(level*13+13,num+1,0x9a); f_chdir(".."); free(items); free(attrib); return(file_menu(level,select)); break; case 0x0d: // select MZ_disp(level*13+13,num+1,0x9a); if(attrib[offset+num]&AM_DIR){ f_chdir((TCHAR*)&items[(offset+num)*13]); free(items); free(attrib); return(file_menu(level,select)); }else{ memcpy(fname, &items[(offset+num)*13], 13); free(items); free(attrib); return(0); } break; case 0x1b: // escape select z80_sts.status&=~S_FBTN; break; case 0x1d: // back to menu MZ_disp(level*13+13,num+1,0x9a); free(items); free(attrib); return(999); break; case 0x1e: // up if(num>0){ MZ_disp(level*13+13,num,0x04); MZ_disp(level*13+13,num+1,0x9a); num--; }else{ if(offset>0){ offset--; disp_files(level,&items[offset*13],total); } } break; case 0x1f: // down if(total>23){ if(num<22){ MZ_disp(level*13+13,num+1,0x9a); MZ_disp(level*13+13,num+2,0x04); num++; }else{ if((num+offset)<(total-1)){ offset++; disp_files(level,&items[offset*13],total); } } }else{ if(num<(total-1)){ MZ_disp(level*13+13,num+1,0x9a); MZ_disp(level*13+13,num+2,0x04); num++; } } break; default: break; } } return(-1); }