/** * @brief Add the device disconnection message to the console and free * USB associated resources * @param None * @retval None */ void USBH_USR_DeviceDisconnected (void) { USB_Host_Application_Ready = 0; f_mount(0, NULL); }
/* StartTaskFATFS function */ void StartTaskFATFS(void const * argument) { /* USER CODE BEGIN StartTaskFATFS */ /* Infinite loop */ UINT count = 0; uint32_t i = 1; static FATFS fileSystem; static FIL testFile; FRESULT res = FR_OK; char buf[100]; sprintf(gbuf, "fat run"); //HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100); do{ osDelay(1000); // sprintf(SD_Path,"0:/\0"); res = f_mount(&fileSystem, SD_Path, 1); sprintf(gbuf, "fat mnt %i",res); osDelay(1000); //HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100); /*if(res == FR_NO_FILESYSTEM){ res = f_mkfs("", 0, 0); sprintf(gbuf, "fat mkfs %i",res); osDelay(1000); //HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100); res = f_mount(&fileSystem, SD_Path, 1); sprintf(gbuf, "fat mnt %i",res); osDelay(1000); //HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100); }*/ }while (res!= FR_OK); HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100); res = f_open(&testFile, "testfile.txt", FA_OPEN_ALWAYS | FA_READ |FA_WRITE ); sprintf(gbuf, "fat open %i",res); osDelay(1000); //HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100); /*uint16_t tmp = f_size(&testFile); f_lseek(&testFile, tmp); */ for(;;) { //if(i > 100000) vTaskDelete(TaskFATFSHandle); if(i%100 == 0){ sprintf(&gbuf[9], "fat wr %i", i); osDelay(1000); //HAL_UART_Transmit(&huart1,(uint8_t*)buf,strlen(buf),100); } memset(buf,0,100); sprintf(buf, "%lu\r\n", i++); res = f_write(&testFile, buf, strlen(buf), &count); if( res != FR_OK) break; f_sync(&testFile); //f_close(&testFile); osDelay(10); } /* USER CODE END StartTaskFATFS */ }
/** * @brief Demo application for IAP through USB mass storage. * @param None * @retval None */ void FW_UPGRADE_Process(void) { switch(Demo_State) { case DEMO_INIT: /* Register the file system object to the FatFs module */ if(f_mount(&USBH_fatfs, "", 0 ) != FR_OK ) { /* FatFs initialization fails */ /* Toggle LED3 and LED4 in infinite loop */ FatFs_Fail_Handler(); } /* TO DO */ // /* Flash Disk is write protected: Turn LED4 On and Toggle LED3 in infinite loop */ // if(USBH_MSC_Param.MSWriteProtect == DISK_WRITE_PROTECTED) // { // /* Turn LED4 On */ // BSP_LED_On(LED4); // /* Toggle LED3 in infinite loop */ // Fail_Handler(); // } /* Go to IAP menu */ Demo_State = DEMO_IAP; break; case DEMO_IAP: while(USBH_MSC_IsReady(&hUSBHost)) { /* Control BUFFER_SIZE value */ USBH_USR_BufferSizeControl(); /* Keep LED1 and LED3 Off when Device connected */ BSP_LED_Off(LED3); BSP_LED_Off(LED4); /* KEY Button pressed Delay */ IAP_UploadTimeout(); /* Writes Flash memory */ COMMAND_Download(); /* Check if KEY Button is already pressed */ if((UploadCondition == 0x01)) { /* Reads all flash memory */ COMMAND_Upload(); } else { /* Turn LED4 Off: Download Done */ BSP_LED_Off(LED4); /* Turn LED3 On: Waiting KEY button pressed */ BSP_LED_On(LED3); } /* Waiting KEY Button Released */ while((BSP_PB_GetState(BUTTON_KEY) == GPIO_PIN_RESET) && (Appli_state == APPLICATION_READY)) {} /* Waiting KEY Button Pressed */ while((BSP_PB_GetState(BUTTON_KEY) != GPIO_PIN_RESET) && (Appli_state == APPLICATION_READY)) {} /* Waiting KEY Button Released */ while((BSP_PB_GetState(BUTTON_KEY) == GPIO_PIN_RESET) && (Appli_state == APPLICATION_READY)) {} if(Appli_state == APPLICATION_READY) { /* Jump to user application code located in the internal Flash memory */ COMMAND_Jump(); } } break; default: break; } if(Appli_state == APPLICATION_DISCONNECT) { /* Toggle LED3: USB device disconnected */ BSP_LED_Toggle(LED4); HAL_Delay(100); } }
/** * @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"); } } } } }
/** *\brief This function mounts the devices.\n * * \param - driveNum - Drive number.\n * * \param - prt - Device pointer.\n * * \return none.\n * */ void HSMMCSDFsMount(unsigned int driveNum, void *ptr) { f_mount(driveNum, &g_sFatFs); fat_devices[0].dev = ptr; fat_devices[0].fs = &g_sFatFs; }
/* * ======== USBMSCHFatFsTiva_open ======== */ USBMSCHFatFs_Handle USBMSCHFatFsTiva_open(USBMSCHFatFs_Handle handle, unsigned char drv, USBMSCHFatFs_Params *params) { unsigned int key; DRESULT dresult; FRESULT fresult; USBMSCHFatFsTiva_Object *object = handle->object; USBMSCHFatFsTiva_HWAttrs const *hwAttrs = handle->hwAttrs; union { Task_Params taskParams; Semaphore_Params semParams; GateMutex_Params gateParams; Hwi_Params hwiParams; } paramsUnion; /* Determine if the device was already opened */ key = Hwi_disable(); if (object->driveNumber != DRIVE_NOT_MOUNTED) { Hwi_restore(key); return (NULL); } /* Mark as being used */ object->driveNumber = drv; Hwi_restore(key); /* Store the USBMSCHFatFs parameters */ if (params == NULL) { /* No params passed in, so use the defaults */ params = (USBMSCHFatFs_Params *) &USBMSCHFatFs_defaultParams; } /* Initialize the USB stack for host mode. */ USBStackModeSet(0, eUSBModeHost, NULL); /* Register host class drivers */ USBHCDRegisterDrivers(0, usbHCDDriverList, numHostClassDrivers); /* Open an instance of the MSC host driver */ object->MSCInstance = USBHMSCDriveOpen(0, USBMSCHFatFsTiva_cbMSCHandler); if (!(object->MSCInstance)) { Log_print0(Diags_USER1,"USBMSCHFatFs: Error initializing the MSC Host"); USBMSCHFatFsTiva_close(handle); return (NULL); } /* Create the Hwi object to service interrupts */ Hwi_Params_init(&(paramsUnion.hwiParams)); paramsUnion.hwiParams.priority = hwAttrs->intPriority; Hwi_construct(&(object->hwi), hwAttrs->intNum, USBMSCHFatFsTiva_hwiHandler, &(paramsUnion.hwiParams), NULL); /* Initialize USB power configuration */ USBHCDPowerConfigInit(0, USBHCD_VBUS_AUTO_HIGH | USBHCD_VBUS_FILTER); /* Enable the USB stack */ USBHCDInit(0, object->memPoolHCD, HCDMEMORYPOOLSIZE); /* RTOS primitives */ Semaphore_Params_init(&(paramsUnion.semParams)); paramsUnion.semParams.mode = Semaphore_Mode_BINARY; Semaphore_construct(&(object->semUSBConnected), 0, &(paramsUnion.semParams)); GateMutex_Params_init(&(paramsUnion.gateParams)); paramsUnion.gateParams.instance->name = "USB Library Access"; GateMutex_construct(&(object->gateUSBLibAccess), &(paramsUnion.gateParams)); paramsUnion.gateParams.instance->name = "USB Wait"; GateMutex_construct(&(object->gateUSBWait), &(paramsUnion.gateParams)); /* * Note that serviceUSBHost() should not be run until the USB Stack has been * initialized!! */ Task_Params_init(&(paramsUnion.taskParams)); /* * If serviceTaskStackPtr is null, then Task_construct performs a * Memory_alloc - requiring a Heap */ paramsUnion.taskParams.stack = params->serviceTaskStackPtr; /* * If service priority passed in is higher than what is configured by the * Task module, then use the highest priority available. */ if (Task_numPriorities - 1 < params->servicePriority) { paramsUnion.taskParams.priority = (Task_numPriorities - 1); } else { paramsUnion.taskParams.priority = params->servicePriority; } /* If no stack size is passed in, then use the default task stack size */ if (params->serviceTaskStackSize) { paramsUnion.taskParams.stackSize = params->serviceTaskStackSize; } else { paramsUnion.taskParams.stackSize = Task_defaultStackSize; } Task_construct(&(object->taskHCDMain),USBMSCHFatFsTiva_serviceUSBHost, &(paramsUnion.taskParams), NULL); /* Register the new disk_*() functions */ dresult = disk_register(drv, USBMSCHFatFsTiva_diskInitialize, USBMSCHFatFsTiva_diskStatus, USBMSCHFatFsTiva_diskRead, USBMSCHFatFsTiva_diskWrite, USBMSCHFatFsTiva_diskIOctl); /* Check for drive errors */ if (dresult != RES_OK) { Log_error0("USBMSCHFatFs: disk functions not registered"); USBMSCHFatFsTiva_close(handle); return (NULL); } /* Mount the FatFs (this function does not access the SDCard yet...) */ fresult = f_mount(drv, &(object->filesystem)); if (fresult != FR_OK) { Log_error1("USBMSCHFatFs: drive %d not mounted", drv); USBMSCHFatFsTiva_close(handle); return (NULL); } Log_print1(Diags_USER1, "USBMSCHFatFs: drive %d opened", drv); return (handle); }
/********************************************************************************************************************* ** Function name: main ** Descriptions: ** Input parameters: ** Output parameters: ** Returned value: ==OS_OK : 操作成功 ** !=OS_OK : 操作失败(包含出错信息) **-------------------------------------------------------------------------------------------------------------------- ** Created by: Fengliang ** Created Date: 2011-5-16 13:23:42 ** Test recorde: **-------------------------------------------------------------------------------------------------------------------- ** Modified by: ** Modified date: ** Test recorde: *********************************************************************************************************************/ int main(int argc, _TCHAR* argv[]) { char aWriteBuffer[] = "精诚服务,真诚永远!——源于China"; /* 文件内容 */ char aReadBuffer[1024]; FATFS fs[1]; /* Work area for logical drives */ FRESULT Status; /* 操作状态 */ FIL SrcFile, DstFile; /* file objects */ UINT ReadCounter, WriteCounter; /* File read counter */ /* * 1) Register work area for each volume (Always succeeds regardless of disk status) */ f_mount(0, &fs[0]); #if 0 f_mkfs(0, 1, 512); #endif /* * 2) 创建目录. */ f_mkdir("0:ChinaOS"); /* * 3) 打开文件 on the drive 0 */ Status = f_open(&SrcFile, "0:hello.txt", FA_OPEN_EXISTING | FA_READ); if (OS_OK != Status) { printf("Could not find the src file\n"); } Status = f_open(&DstFile, "0:ChinaOS中国操作系统.txt", FA_CREATE_ALWAYS | FA_WRITE); if (OS_OK != Status) { printf("Could not find the dest file\n"); } /* * 4) 复制文件数据. */ while (1) { Status = f_read(&SrcFile, aReadBuffer, sizeof(aReadBuffer), &ReadCounter); if (OS_OK != Status || ReadCounter == 0) { break; /* error or eof */ } /* Copy source to destination */ Status = f_write(&DstFile, aReadBuffer, ReadCounter, &WriteCounter); if (OS_OK != Status || WriteCounter < ReadCounter) { break; /* error or disk full */ } } /* * 5) Close open files */ f_close(&SrcFile); f_close(&DstFile); /* * 6) Unregister work area prior to discard it. */ f_unmount(0); return 0; }
/** * @brief USBH_USR_MSC_Application * Demo application for IAP thru USB mass storage * @param None * @retval Staus */ int USBH_USR_MSC_Application(void) { EXTI_InitTypeDef EXTI_InitStructure; switch (USBH_USR_ApplicationState) { case USH_USR_FS_INIT: /* Initialises the File System*/ if (f_mount( 0, &fatfs ) != FR_OK ) { /* Fatfs initialisation fails */ /* Toggle Red LED in infinite loop */ Fail_Handler(); return(-1); } /* Flash Disk is write protected: Set ON Blue LED and Toggle Red LED in infinite loop */ if (USBH_MSC_Param.MSWriteProtect == DISK_WRITE_PROTECTED) { /* Set ON Blue LED */ STM_EVAL_LEDOn(LED6); /* Toggle Red LED in infinite loop */ Fail_Handler(); } /* Go to IAP menu */ USBH_USR_ApplicationState = USH_USR_IAP; break; case USH_USR_IAP: TimingDelay = 300; UploadCondition = 0x01; /* Initialize User_Button on STM32F4-Discovery in the EXTI Mode ----------*/ STM_EVAL_PBInit(BUTTON_USER, BUTTON_MODE_EXTI); /* Configure Button EXTI line */ EXTI_InitStructure.EXTI_Line = USER_BUTTON_EXTI_LINE; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); /* Writes Flash memory */ COMMAND_DOWNLOAD(); /* Initialize User_Button on STM32F4-Discovery in the GPIO Mode ----------*/ STM_EVAL_PBInit(BUTTON_USER, BUTTON_MODE_GPIO); /* Check if User Button is already pressed */ if ((TimingDelay == 0x00) && (UploadCondition == 0x01)) { /* Reads all flash memory */ COMMAND_UPLOAD(); } else { /* Set Off Orange LED : Download Done */ STM_EVAL_LEDOff(LED3); /* Set ON Green LED: Waiting User button pressed */ STM_EVAL_LEDOn(LED4); } UploadCondition = 0x00; /* Waiting User Button Released */ while ((STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET) && (HCD_IsDeviceConnected(&USB_OTG_Core) == 1)) {} /* Waiting User Button Pressed */ while ((STM_EVAL_PBGetState(BUTTON_USER) == Bit_RESET) && (HCD_IsDeviceConnected(&USB_OTG_Core) == 1)) {} /* Waiting User Button Released */ while ((STM_EVAL_PBGetState(BUTTON_USER) == Bit_SET) && (HCD_IsDeviceConnected(&USB_OTG_Core) == 1)) {} /* Jumps to user application code located in the internal Flash memory */ COMMAND_JUMP(); break; default: break; } return(0); }
/******************************************************************************* * Function Name : main * Description : Main program. * Input : None * Output : None * Return : None *******************************************************************************/ int SD_Test(void) { u16 i; FIL file; char data[512]; UINT number=0; char *s="hello,lightjpu\n"; //Init_Device(); //RTC_Start(); SPI_Configuration(); res = f_mount(0, &fs); //res = f_mkfs(0,0,0); // if(res!=FR_OK) // { // while(1); // } res = f_open(&file, "data.txt", FA_CREATE_ALWAYS | FA_READ | FA_WRITE); if(res!=FR_OK) { while(1); } for(i=0;i<512;i++) { data[i] = 0x38; } res = f_write(&file, data, 512, &number); if(res!=FR_OK) { while(1); } while(1) { //if(fgets(data, sizeof(data), &file)==NULL) //{ break; //} //prints(data); } f_close(&file); // write_time = Time_GetUnixTime(); res = f_open(&file, "331.txt", FA_CREATE_ALWAYS | FA_WRITE); for(i=0;i<3;i++) { res = f_write(&file, s, 14, &br); if(br<14) //判断是否磁盘写满 { break; } } // write_time = Time_GetUnixTime() - write_time; f_close(&file); SD_PWR_OFF(); while(1) { /* if(TimeDisplay) { current_time = Time_GetUnixTime(); time_now = Time_GetCalendarTime(); USART_SendData(USART1, 0x0c); while(USART_GetFlagStatus(USART1, USART_FLAG_TC)==RESET); printf("\r\nUNIX时间:%d", current_time); printf("\t当前时间:%d-%d-%d %d %02d:%02d:%02d\t", time_now.tm_year, \ time_now.tm_mon+1, time_now.tm_mday, time_now.tm_wday+1,\ time_now.tm_hour, time_now.tm_min, time_now.tm_sec); TimeDisplay = 0; } */ } }
/** * @brief IAP Read all flash memory. * @param None * @retval None */ void COMMAND_Upload(void) { __IO uint32_t address = APPLICATION_ADDRESS; __IO uint32_t counterread = 0x00; uint32_t tmpcounter = 0x00, indexoffset = 0x00; FlagStatus readoutstatus = SET; uint16_t byteswritten; /* Get the read out protection status */ readoutstatus = FLASH_If_ReadOutProtectionStatus(); if(readoutstatus == RESET) { /* Remove UPLOAD file if it exists on flash disk */ f_unlink(UPLOAD_FILENAME); /* Init written byte counter */ indexoffset = (APPLICATION_ADDRESS - USER_FLASH_STARTADDRESS); /* Open binary file to write on it */ if(( Appli_state == APPLICATION_READY) && (f_open(&MyFile, UPLOAD_FILENAME, FA_CREATE_ALWAYS | FA_WRITE) == FR_OK)) { /* Upload On Going: Turn LED4 On and LED3 Off */ BSP_LED_On(LED4); BSP_LED_Off(LED3); /* Read flash memory */ while ((indexoffset < USER_FLASH_SIZE) && ( Appli_state == APPLICATION_READY)) { for(counterread = 0; counterread < BUFFER_SIZE; counterread++) { /* Check the read bytes versus the end of flash */ if(indexoffset + counterread < USER_FLASH_SIZE) { tmpcounter = counterread; RAM_Buf[tmpcounter] = (*(uint8_t*)(address++)); } /* In this case all flash was read */ else { break; } } /* Write buffer to file */ f_write (&MyFile, RAM_Buf, BUFFER_SIZE, (void *)&byteswritten); /* Number of byte written */ indexoffset = indexoffset + counterread; } /* Turn LED1 On: Upload Done */ BSP_LED_Off(LED4); BSP_LED_Off(LED2); BSP_LED_On(LED1); /* Close file and filesystem */ f_close(&MyFile); f_mount(0, 0, 0); } /* Keep These LEDS OFF when Device connected */ BSP_LED_Off(LED2); BSP_LED_Off(LED3); } else { /* Message ROP active: Turn LED2 On and Toggle LED3 in infinite loop */ BSP_LED_On(LED2); Fail_Handler(); } }
/*----------------------------------------------------------------------------*/ u8 device_init(void) { usb_sd_dev_toc=0; device_online = get_device_online_status(); if(playpoint_time.last_device != device_active) { write_playtime(&playpoint_time); } if (device_active & device_online) ///<当前需要活动的设备在线 { flush_all_msg(); ///<清空全部消息 stop_decode(); ///<停止解码 #if FILE_ENCRYPTION password_start(0); #endif #ifdef SYS_GPIO_SEL_FUNC if( gpio_sel_func){ return 0xff; } #endif if (device_active == BIT(USB_DISK)) { if (usb_host_emuerate_devcie(win_buffer)) ///<USB MASS STORAGE 枚举 { #ifdef SYS_GPIO_SEL_FUNC if( gpio_sel_func){ return 0xff; } #endif f_init(win_buffer, (u16)usb_otp_read, get_usb_device_pkt_size()); ///<枚举成功后 初始化文件系统参数 } else { return 0xff; ///<枚举失败 } } else if (device_active == BIT(SDMMC)) { if (init_sd()) ///<sd 卡鉴定 { #ifdef SYS_GPIO_SEL_FUNC if( gpio_sel_func){ return 0xff; } #endif f_init(win_buffer, (u16)sdmmc_otp_read, 1);//get_usb_device_pkt_size()); ///<鉴定成功后 初始化文件系统参数 } else { return 0xff; ///<鉴定失败 } } } #ifdef SYS_GPIO_SEL_FUNC if( gpio_sel_func){ return 0xff; } #endif if (!f_mount()) ///<文件系统初始化 { #ifdef SYS_GPIO_SEL_FUNC if( gpio_sel_func){ return 0xff; } #endif fs_ext_setting(file_type); #ifdef SYS_GPIO_SEL_FUNC if( gpio_sel_func){ return 0xff; } #endif set_playpoint_info(read_playpoint_info(device_active)); #ifdef SYS_GPIO_SEL_FUNC if( gpio_sel_func){ return 0xff; } #endif fs_scan_disk(); #ifdef SYS_GPIO_SEL_FUNC if( gpio_sel_func){ return 0xff; } #endif playpoint_filenum = get_scan_filenumber(); //根据对应设备的起始簇找出有断点的文件号 /**/ usb_sd_dev_toc=1; #ifdef DISABLE_USB_SD_BP_PLAY playpoint_filenum=0; #endif if(0 == playpoint_filenum) { if(given_file_number) given_file_number = 1; } if (fs_msg.fileTotal == 0) { return 0xfe; } #if ((USE_DEVICE == MEMORY_STYLE)&&(FAT_MEMORY)) check_reserve_sector(device_active); #endif return 0; } else { //无有效设备 return 0xff; } }
/** * Mount a new fatfs. * @param mode mount flags. * @param param contains optional mount parameters. * @param parm_len length of param string. * @param[out] sb Returns the superblock of the new mount. * @return error code, -errno. */ static int fatfs_mount(const char * source, uint32_t mode, const char * parm, int parm_len, struct fs_superblock ** sb) { static dev_t fatfs_vdev_minor; struct fatfs_sb * fatfs_sb = NULL; vnode_t * vndev; char pdrv; int err, retval = 0; /* Get device vnode */ err = lookup_vnode(&vndev, curproc->croot, source, 0); if (err) { #ifdef configFATFS_DEBUG KERROR(KERROR_DEBUG, "fatfs source not found\n"); #endif return err; } if (!S_ISBLK(vndev->vn_mode)) return -ENOTBLK; /* Allocate superblock */ fatfs_sb = kzalloc(sizeof(struct fatfs_sb)); if (!fatfs_sb) return -ENOMEM; fs_fildes_set(&fatfs_sb->ff_devfile, vndev, O_RDWR); fatfs_sb->sb.vdev_id = DEV_MMTODEV(VDEV_MJNR_FATFS, fatfs_vdev_minor++); /* Insert sb to fatfs_sb_arr lookup array */ fatfs_sb_arr[DEV_MINOR(fatfs_sb->sb.vdev_id)] = fatfs_sb; /* Mount */ pdrv = (char)DEV_MINOR(fatfs_sb->sb.vdev_id); err = f_mount(&fatfs_sb->ff_fs, 0); if (err) { #ifdef configFATFS_DEBUG KERROR(KERROR_DEBUG, "Can't init a work area for FAT (%d)\n", err); #endif retval = fresult2errno(err); goto fail; } #ifdef configFATFS_DEBUG KERROR(KERROR_DEBUG, "Initialized a work area for FAT\n"); #endif #if (_FS_NOFSINFO == 0) /* Commit full scan of free clusters */ DWORD nclst; f_getfree(&fatfs_sb->ff_fs, &nclst); #endif /* Init super block */ fs_init_superblock(&fatfs_sb->sb, &fatfs_fs); /* TODO Detect if target dev is rdonly */ fatfs_sb->sb.mode_flags = mode; fatfs_sb->sb.root = create_root(fatfs_sb); fatfs_sb->sb.sb_dev = vndev; fatfs_sb->sb.sb_hashseed = fatfs_sb->sb.vdev_id; /* Function pointers to superblock methods */ fatfs_sb->sb.get_vnode = NULL; /* Not implemented for FAT. */ fatfs_sb->sb.delete_vnode = fatfs_delete_vnode; fatfs_sb->sb.umount = NULL; if (!fatfs_sb->sb.root) { KERROR(KERROR_ERR, "Root of fatfs not found\n"); return -EIO; } fs_insert_superblock(&fatfs_fs, &fatfs_sb->sb); fail: if (retval) { fatfs_sb_arr[DEV_MINOR(fatfs_sb->sb.vdev_id)] = NULL; kfree(fatfs_sb); } *sb = &fatfs_sb->sb; return retval; }
//挂载磁盘 u8 mf_mount(u8 drv) { return f_mount(drv,&fs[drv]); }
/** * @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 the system clock to 168 MHz */ SystemClock_Config(); /* Configure LED1 and LED3 */ BSP_LED_Init(LED1); BSP_LED_Init(LED3); /*##-1- Link the RAM disk I/O driver #######################################*/ if(FATFS_LinkDriver(&SRAMDISK_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) { 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)) /* EOF or Error */ { /* '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(RAMDISKPath); /* Infinite loop */ while (1) { } }
static msg_t ThreadFatFSWorker(void *arg) { (void)arg; Thread* p; chRegSetThreadName("fatfsWorker"); while (!chThdShouldTerminate()) { /* Wait for msg with work to do. */ p = chMsgWait(); struct wrapper_msg_base* msg = (struct wrapper_msg_base*) chMsgGet(p); msg->result = FR_INVALID_PARAMETER; switch(msg->action) { case eTERMINATE: { break; } #if HAS_MOUNT case eFMOUNT: { const struct wrapper_msg_vBYTEpFATFS* exmsg = \ (const struct wrapper_msg_vBYTEpFATFS*) msg; msg->result = f_mount(exmsg->byte, exmsg->fatfsp); break; } #endif /* HAS_MOUNT */ #if HAS_OPEN case eFOPEN: { const struct wrapper_msg_pFILpTCHARvBYTE* exmsg = \ (const struct wrapper_msg_pFILpTCHARvBYTE*) msg; msg->result = f_open(exmsg->filep, exmsg->string, exmsg->byte); break; } #endif /* HAS_OPEN */ #if HAS_READ case eFREAD: { const struct wrapper_msg_pFILpVOIDvUINTpUINT* exmsg = \ (const struct wrapper_msg_pFILpVOIDvUINTpUINT*) msg; msg->result = f_read(exmsg->filep, exmsg->voidp, exmsg->uint, exmsg->uintp); break; } #endif /* HAS_READ */ #if HAS_WRITE case eFWRITE: { const struct wrapper_msg_pFILpVOIDvUINTpUINT* exmsg = \ (const struct wrapper_msg_pFILpVOIDvUINTpUINT*) msg; msg->result = f_write(exmsg->filep, exmsg->voidp, exmsg->uint, exmsg->uintp); break; } #endif /* HAD_WRITE */ #if HAS_SYNC case eFSYNC: { const struct wrapper_msg_pFIL* exmsg = \ (const struct wrapper_msg_pFIL*) msg; msg->result = f_sync(exmsg->filep); break; } #endif /* HAS_SYNC */ #if HAS_CHDRIVE case eFCHDRIVE: { const struct wrapper_msg_vBYTE* exmsg = \ (const struct wrapper_msg_vBYTE*) msg; msg->result = f_chdrive(exmsg->byte); break; } #endif #if HAS_CHDIR case eFCHDIR: { const struct wrapper_msg_pTCHAR* exmsg = \ (const struct wrapper_msg_pTCHAR*) msg; msg->result = f_chdir(exmsg->string); break; } #endif /* HAS_CHDIR */ #if HAS_GETCWD case eFGETCWD: { const struct wrapper_msg_pTCHARvUINT* exmsg = \ (const struct wrapper_msg_pTCHARvUINT*) msg; msg->result = f_getcwd(exmsg->string, exmsg->uint); break; } #endif #if HAS_LSEEK case eFLSEEK: { const struct wrapper_msg_pFILvDWORD* exmsg = \ (const struct wrapper_msg_pFILvDWORD*) msg; msg->result = f_lseek(exmsg->filep, exmsg->dword); break; } #endif /* HAS_LSEEK */ #if HAS_CLOSE case eFCLOSE: { const struct wrapper_msg_pFIL* exmsg = \ (const struct wrapper_msg_pFIL*) msg; msg->result = f_close(exmsg->filep); break; } #endif /* HAS_CLOSE */ #if HAS_OPENDIR case eFOPENDIR: { const struct wrapper_msg_pDIRpTCHAR* exmsg = \ (const struct wrapper_msg_pDIRpTCHAR*) msg; msg->result = f_opendir(exmsg->dirp, exmsg->string); break; } #endif /* HAD_OPENDIR */ #if HAS_READDIR case eFREADDIR: { const struct wrapper_msg_pDIRpFILINFO* exmsg = \ (const struct wrapper_msg_pDIRpFILINFO*) msg; msg->result = f_readdir(exmsg->dirp, exmsg->filinfop); break; } #endif /* HAS_READDIR */ #if HAS_STAT case eFSTAT: { const struct wrapper_msg_pTCHARpFILINFO* exmsg = \ (const struct wrapper_msg_pTCHARpFILINFO*) msg; msg->result = f_stat(exmsg->string, exmsg->filinfop); break; } #endif /* HAS_STAT */ #if HAS_GETFREE case eFGETFREE: { const struct wrapper_msg_pTCHARpDWORDppFATFS* exmsg = \ (const struct wrapper_msg_pTCHARpDWORDppFATFS*) msg; msg->result = f_getfree(exmsg->string, exmsg->dwordp, exmsg->fatfspp); break; } #endif /* HAS_GETFREE */ #if HAS_TRUNCATE case eFTRUNCATE: { const struct wrapper_msg_pFIL* exmsg = \ (const struct wrapper_msg_pFIL*) msg; msg->result = f_truncate(exmsg->filep); break; } #endif /* HAS_TRUNCATE */ #if HAS_UNLINK case eFUNLINK: { const struct wrapper_msg_pTCHAR* exmsg = \ (const struct wrapper_msg_pTCHAR*) msg; msg->result = f_unlink(exmsg->string); break; } #endif /* HAS_UNLINK */ #if HAS_MKDIR case eFMKDIR: { const struct wrapper_msg_pTCHAR* exmsg = \ (const struct wrapper_msg_pTCHAR*) msg; msg->result = f_mkdir(exmsg->string); break; } #endif /* HAS_MKDIR */ #if HAS_CHMOD case eFCHMOD: { const struct wrapper_msg_pTCHARvBYTEvBYTE* exmsg = \ (const struct wrapper_msg_pTCHARvBYTEvBYTE*) msg; msg->result = f_chmod(exmsg->string, exmsg->byte1, exmsg->byte2); break; } #endif /* HAS_CHMOD */ #if HAS_UTIME case eFUTIME: { const struct wrapper_msg_pTCHARpFILINFO* exmsg = \ (const struct wrapper_msg_pTCHARpFILINFO*) msg; msg->result = f_utime(exmsg->string, exmsg->filinfop); break; } #endif /* HAD_UTIME */ #if HAS_RENAME case eFRENAME: { const struct wrapper_msg_pTCHARpTCHAR* exmsg = \ (const struct wrapper_msg_pTCHARpTCHAR*) msg; msg->result = f_rename(exmsg->string1, exmsg->string2); break; } #endif /* HAS_RENAME */ #if HAS_MKFS case eFMKFS: { const struct wrapper_msg_vBYTEvBYTEvUINT* exmsg = \ (const struct wrapper_msg_vBYTEvBYTEvUINT*) msg; msg->result = f_mkfs(exmsg->byte1, exmsg->byte2, exmsg->uint); break; } #endif /* HAS_MKFS */ #if HAS_FDISK case eFFDISK: { const struct wrapper_msg_vBYTEpDWORDpVOID* exmsg = \ (const struct wrapper_msg_vBYTEpDWORDpVOID*) msg; msg->result = f_fdisk(exmsg->byte, exmsg->dwordp, exmsg->voidp); break; } #endif /* HAS_FDISK */ #if HAS_GETS case eFGETS: { struct wrapper_msg_pTCHARvINTpFILpTCHAR* exmsg = \ (struct wrapper_msg_pTCHARvINTpFILpTCHAR*) msg; exmsg->string2 = f_gets(exmsg->string, exmsg->n, exmsg->filep); break; } #endif /* HAS_GETS */ #if HAS_PUTC case eFPUTC: { const struct wrapper_msg_vTCHARpFIL* exmsg = \ (const struct wrapper_msg_vTCHARpFIL*) msg; msg->result = f_putc(exmsg->tchar, exmsg->filep); break; } #endif /* HAS_PUTC */ #if HAS_PUTS case eFPUTS: { const struct wrapper_msg_pTCHARpFIL* exmsg = \ (const struct wrapper_msg_pTCHARpFIL*) msg; msg->result = f_puts(exmsg->string, exmsg->filep); break; } #endif /* HAS_PUTS */ } /* Done, release msg again. */ chMsgRelease(p, 0); } return 0; }
int _main( int argc, char *argv[] ) { //BSS is in DATA section so IOS doesnt touch it, we need to manually clear it //dbgprintf("memset32(%08x, 0, %08x)\n", &__bss_start, &__bss_end - &__bss_start); memset32(&__bss_start, 0, &__bss_end - &__bss_start); sync_after_write(&__bss_start, &__bss_end - &__bss_start); s32 ret = 0; u32 HID_Thread = 0, DI_Thread = 0; u8 MessageHeap[0x10]; //u32 MessageQueue=0xFFFFFFFF; BootStatus(0, 0, 0); thread_set_priority( 0, 0x79 ); // do not remove this, this waits for FS to be ready! thread_set_priority( 0, 0x50 ); thread_set_priority( 0, 0x79 ); //MessageQueue = ES_Init( MessageHeap ); ES_Init( MessageHeap ); BootStatus(1, 0, 0); #ifndef NINTENDONT_USB BootStatus(2, 0, 0); ret = SDHCInit(); if(!ret) { dbgprintf("SD:SDHCInit() failed:%d\r\n", ret ); BootStatusError(-2, ret); mdelay(2000); Shutdown(); } #endif BootStatus(3, 0, 0); fatfs = (FATFS*)malloca( sizeof(FATFS), 32 ); s32 res = f_mount( 0, fatfs ); if( res != FR_OK ) { dbgprintf("ES:f_mount() failed:%d\r\n", res ); BootStatusError(-3, res); mdelay(2000); Shutdown(); } BootStatus(4, 0, 0); BootStatus(5, 0, 0); int MountFail = 0; s32 fres = -1; FIL fp; while(fres != FR_OK) { fres = f_open(&fp, "/bladie", FA_READ|FA_OPEN_EXISTING); switch(fres) { case FR_OK: f_close(&fp); case FR_NO_PATH: case FR_NO_FILE: { fres = FR_OK; } break; default: case FR_DISK_ERR: { f_mount(0, NULL); //unmount drive todo: retry could never work MountFail++; if(MountFail == 10) { BootStatusError(-5, fres); mdelay(2000); Shutdown(); } mdelay(5); } break; } if(STATUS_ERROR == -7) { // FS check timed out on PPC side dbgprintf("FS check timed out\r\n"); mdelay(3000); Shutdown(); } } #ifndef NINTENDONT_USB s_size = 512; s_cnt = fatfs->n_fatent * fatfs->csize; #endif BootStatus(6, s_size, s_cnt); #ifdef NINTENDONT_USB s32 r = LoadModules(55); //dbgprintf("ES:ES_LoadModules(%d):%d\r\n", 55, r ); if( r < 0 ) { BootStatusError(-6, r); mdelay(2000); Shutdown(); } #endif BootStatus(7, s_size, s_cnt); ConfigInit(); if (ConfigGetConfig(NIN_CFG_LOG)) SDisInit = 1; // Looks okay after threading fix dbgprintf("Game path: %s\r\n", ConfigGetGamePath()); BootStatus(8, s_size, s_cnt); memset32((void*)0x13002800, 0, 0x30); sync_after_write((void*)0x13002800, 0x30); memset32((void*)0x13160000, 0, 0x20); sync_after_write((void*)0x13160000, 0x20); memset32((void*)0x13026500, 0, 0x100); sync_after_write((void*)0x13026500, 0x100); bool UseHID = ConfigGetConfig(NIN_CFG_HID); if( UseHID ) { ret = HIDInit(); if(ret < 0 ) { dbgprintf("ES:HIDInit() failed\r\n" ); BootStatusError(-8, ret); mdelay(2000); Shutdown(); } write32(0x13003004, 0); sync_after_write((void*)0x13003004, 0x20); HID_Thread = thread_create(HID_Run, NULL, HID_ThreadStack, 0x400, 0x78, 1); thread_continue(HID_Thread); } BootStatus(9, s_size, s_cnt); DIRegister(); DI_Thread = thread_create(DIReadThread, NULL, DI_ThreadStack, 0x400, 0x78, 1); thread_continue(DI_Thread); DIinit(true); BootStatus(10, s_size, s_cnt); GCAMInit(); EXIInit(); ret = Check_Cheats(); if(ret < 0 ) { dbgprintf("Check_Cheats failed\r\n" ); BootStatusError(-10, ret); mdelay(4000); Shutdown(); } BootStatus(11, s_size, s_cnt); bool PatchSI = !ConfigGetConfig(NIN_CFG_NATIVE_SI); if (PatchSI) SIInit(); StreamInit(); PatchInit(); //This bit seems to be different on japanese consoles u32 ori_ppcspeed = read32(HW_PPCSPEED); if((ConfigGetGameID() & 0xFF) == 'J') set32(HW_PPCSPEED, (1<<17)); else clear32(HW_PPCSPEED, (1<<17)); //write32( 0x1860, 0xdeadbeef ); // Clear OSReport area //Tell PPC side we are ready! cc_ahbMemFlush(1); mdelay(1000); BootStatus(0xdeadbeef, s_size, s_cnt); u32 Now = read32(HW_TIMER); u32 PADTimer = Now; u32 DiscChangeTimer = Now; u32 ResetTimer = Now; #ifdef NINTENDONT_USB u32 USBReadTimer = Now; #endif u32 Reset = 0; bool SaveCard = false; if( ConfigGetConfig(NIN_CFG_LED) ) { set32(HW_GPIO_ENABLE, GPIO_SLOT_LED); clear32(HW_GPIO_DIR, GPIO_SLOT_LED); clear32(HW_GPIO_OWNER, GPIO_SLOT_LED); } EnableAHBProt(-1); //disable AHBPROT write32(0xd8006a0, 0x30000004), mask32(0xd8006a8, 0, 2); //widescreen fix while (1) { _ahbMemFlush(0); //Check this. Purpose is to send another interrupt if wasn't processed /*if (((read32(0x14) != 0) || (read32(0x13026514) != 0)) && (read32(HW_ARMIRQFLAG) & (1 << 30)) == 0) { write32(HW_IPC_ARMCTRL, (1 << 0) | (1 << 4)); //throw irq }*/ #ifdef PATCHALL if (EXI_IRQ == true) { if(EXICheckTimer()) EXIInterrupt(); } #endif if ((PatchSI) && (SI_IRQ != 0)) { if (((read32(HW_TIMER) - PADTimer) > 7910) || (SI_IRQ & 0x2)) // about 240 times a second { SIInterrupt(); PADTimer = read32(HW_TIMER); } } if(DI_IRQ == true) { if(DI_CallbackMsg.result == 0) DIInterrupt(); } else if(SaveCard == true) /* DI IRQ indicates we might read async, so dont write at the same time */ { if((read32(HW_TIMER) - Now) / 1898437 > 2) /* after 3 second earliest */ { EXISaveCard(); SaveCard = false; } } #ifdef NINTENDONT_USB else if((read32(HW_TIMER) - USBReadTimer) / 1898437 > 9) /* Read random sector after about 10 seconds */ { DI_CallbackMsg.result = -1; sync_after_write(&DI_CallbackMsg, 0x20); IOS_IoctlAsync( DI_Handle, 2, NULL, 0, NULL, 0, DI_MessageQueue, &DI_CallbackMsg ); while(DI_CallbackMsg.result) { udelay(10); //wait for other threads BTUpdateRegisters(); } USBReadTimer = read32(HW_TIMER); } #endif udelay(10); //wait for other threads //Baten Kaitos save hax /*if( read32(0) == 0x474B4245 ) { if( read32( 0x0073E640 ) == 0xFFFFFFFF ) { write32( 0x0073E640, 0 ); } }*/ if ( DiscChangeIRQ == 1 ) { DiscChangeTimer = read32(HW_TIMER); DiscChangeIRQ = 2; } else if ( DiscChangeIRQ == 2 ) { if ( (read32(HW_TIMER) - DiscChangeTimer ) > 2 * 243000000 / 128) { //dbgprintf("DIP:IRQ mon!\r\n"); set32( DI_SSTATUS, 0x3A ); sync_after_write((void*)DI_SSTATUS, 4); DIInterrupt(); DiscChangeIRQ = 0; } } _ahbMemFlush(1); DIUpdateRegisters(); #ifdef PATCHALL EXIUpdateRegistersNEW(); GCAMUpdateRegisters(); BTUpdateRegisters(); #endif StreamUpdateRegisters(); CheckOSReport(); if(EXICheckCard()) { Now = read32(HW_TIMER); SaveCard = true; } if (PatchSI) { SIUpdateRegisters(); if (read32(DIP_IMM) == 0x1DEA) { DIFinishAsync(); break; } if (read32(DIP_IMM) == 0x3DEA) { if (Reset == 0) { dbgprintf("Fake Reset IRQ\n"); write32(EXI2DATA, 0x2); // Reset irq write32(HW_IPC_ARMCTRL, (1 << 0) | (1 << 4)); //throw irq Reset = 1; } } else if (Reset == 1) { write32(EXI2DATA, 0x10000); // send pressed ResetTimer = read32(HW_TIMER); Reset = 2; } /* The cleanup is not connected to the button press */ if (Reset == 2) { if ((read32(HW_TIMER) - ResetTimer) / 949219 > 0) //free after half a second { write32(EXI2DATA, 0); // done, clear write32(DIP_IMM, 0); Reset = 0; } } } if(read32(DIP_IMM) == 0x4DEA) PatchGame(); CheckPatchPrs(); if(read32(HW_GPIO_IN) & GPIO_POWER) { DIFinishAsync(); #ifdef PATCHALL BTE_Shutdown(); #endif Shutdown(); } //sync_before_read( (void*)0x1860, 0x20 ); //if( read32(0x1860) != 0xdeadbeef ) //{ // if( read32(0x1860) != 0 ) // { // dbgprintf( (char*)(P2C(read32(0x1860))), // (char*)(P2C(read32(0x1864))), // (char*)(P2C(read32(0x1868))), // (char*)(P2C(read32(0x186C))), // (char*)(P2C(read32(0x1870))), // (char*)(P2C(read32(0x1874))) // ); // } // write32(0x1860, 0xdeadbeef); // sync_after_write( (void*)0x1860, 0x20 ); //} cc_ahbMemFlush(1); } if( UseHID ) { /* we're done reading inputs */ thread_cancel(HID_Thread, 0); } IOS_Close(DI_Handle); //close game thread_cancel(DI_Thread, 0); DIUnregister(); write32( DIP_IMM, 0 ); /* reset time */ while(1) { if(read32(DIP_IMM) == 0x2DEA) break; wait_for_ppc(1); } if( ConfigGetConfig(NIN_CFG_LED) ) clear32(HW_GPIO_OUT, GPIO_SLOT_LED); if( ConfigGetConfig(NIN_CFG_MEMCARDEMU) ) EXIShutdown(); if (ConfigGetConfig(NIN_CFG_LOG)) closeLog(); #ifdef PATCHALL BTE_Shutdown(); #endif //unmount FAT device f_mount(0, NULL); #ifndef NINTENDONT_USB SDHCShutdown(); #endif //make sure we set that back to the original write32(HW_PPCSPEED, ori_ppcspeed); IOSBoot((char*)0x13003020, 0, read32(0x13003000)); return 0; }
//**************************************************************************** // //! Main function //! //! \param none //! //! //! \return None. // //**************************************************************************** void main() { FIL fp; FATFS fs; FRESULT res; DIR dir; WORD Size; // // Initialize Board configurations // BoardInit(); // // Muxing for Enabling UART_TX and UART_RX. // PinMuxConfig(); // // Set the SD card clock as output pin // MAP_PinDirModeSet(PIN_07,PIN_DIR_MODE_OUT); // // Initialising the Terminal. // InitTerm(); // // Clearing the Terminal. // ClearTerm(); // // Display the Banner // Message("\n\n\n\r"); Message("\t\t ********************************************\n\r"); Message("\t\t CC3200 SDHost Fatfs Demo Application \n\r"); Message("\t\t ********************************************\n\r"); Message("\n\n\n\r"); // // Enable MMCHS // MAP_PRCMPeripheralClkEnable(PRCM_SDHOST,PRCM_RUN_MODE_CLK); // // Reset MMCHS // MAP_PRCMPeripheralReset(PRCM_SDHOST); // // Configure MMCHS // MAP_SDHostInit(SDHOST_BASE); // // Configure card clock // MAP_SDHostSetExpClk(SDHOST_BASE,MAP_PRCMPeripheralClockGet(PRCM_SDHOST),15000000); f_mount(0,&fs); res = f_opendir(&dir,"/"); if( res == FR_OK) { Message("Opening root directory.................... [ok]\n\n\r"); Message("/\n\r"); ListDirectory(&dir); } else { Message("Opening root directory.................... [Failed]\n\n\r"); } Message("\n\rReading user file...\n\r"); res = f_open(&fp,USERFILE,FA_READ); if(res == FR_OK) { f_read(&fp,pBuffer,100,&Size); Report("Read : %d Bytes\n\n\r",Size); Report("%s",pBuffer); f_close(&fp); } else { Report("Failed to open %s\n\r",USERFILE); } Message("\n\n\rWriting system file...\n\r"); res = f_open(&fp,SYSFILE,FA_CREATE_ALWAYS|FA_WRITE); if(res == FR_OK) { f_write(&fp,SYSTEXT,sizeof(SYSTEXT),&Size); Report("Wrote : %d Bytes",Size); res = f_close(&fp); } else { Message("Failed to create a new file\n\r"); } while(1) { } }
/** * @brief IAP Read all flash memory. * @param None * @retval None */ void COMMAND_UPLOAD(void) { __IO uint32_t address = APPLICATION_ADDRESS; __IO uint32_t counterread = 0x00; uint32_t tmpcounter = 0x00, indexoffset = 0x00; FlagStatus readoutstatus = SET; uint16_t bytesWritten; /* Get the read out protection status */ readoutstatus = FLASH_If_ReadOutProtectionStatus(); if (readoutstatus == RESET) { /* Remove UPLOAD file if exist on flash disk */ f_unlink (UPLOAD_FILENAME); /* Init written byte counter */ indexoffset = (APPLICATION_ADDRESS - USER_FLASH_STARTADDRESS); /* Open binary file to write on it */ if ((HCD_IsDeviceConnected(&USB_OTG_Core) == 1) && (f_open(&file, UPLOAD_FILENAME, FA_CREATE_ALWAYS | FA_WRITE) == FR_OK)) { /* Read flash memory */ while ((indexoffset != USER_FLASH_SIZE) && (HCD_IsDeviceConnected(&USB_OTG_Core) == 1)) { for (counterread = 0; counterread < BUFFER_SIZE; counterread++) { /* Check the read bytes versus the end of flash */ if (indexoffset + counterread != USER_FLASH_SIZE) { tmpcounter = counterread; RAM_Buf[tmpcounter] = (*(uint8_t*)(address++)); } /* In this case all flash was read */ else { break; } } /* Write buffer to file */ f_write (&file, RAM_Buf, BUFFER_SIZE, (void *)&bytesWritten); /* Number of byte written */ indexoffset = indexoffset + counterread; } /* Set Green LED ON: Upload Done */ STM_EVAL_LEDOn(LED3); /* Close file and filesystem */ f_close (&file); f_mount(0, NULL); } } else { /* Message ROP active: Toggle Red LED in infinite loop */ Fail_Handler(); } }
/** * @brief processes the tftp request on port 69 * @param pkt_buf: pointer on received pbuf * @param ip_addr: pointer on source IP address * @param port: pointer on source udp port * @retval None */ void process_tftp_request(struct pbuf *pkt_buf, struct ip_addr *addr, u16_t port) { tftp_opcode op = tftp_decode_op(pkt_buf->payload); char FileName[30]; struct udp_pcb *upcb; err_t err; /* create new UDP PCB structure */ upcb = udp_new(); if (!upcb) { /* Error creating PCB. Out of Memory */ return; } /* bind to port 0 to receive next available free port */ /* NOTE: This is how TFTP works. There is a UDP PCB for the standard port * 69 which al transactions begin communication on, however all subsequent * transactions for a given "stream" occur on another port! */ err = udp_bind(upcb, IP_ADDR_ANY, 0); if (err != ERR_OK) { /* Unable to bind to port */ return; } switch (op) { case TFTP_RRQ:/* TFTP RRQ (read request) */ { /* Read the name of the file asked by the client to be sent from the SD card */ tftp_extract_filename(FileName, pkt_buf->payload); /* could not open filesystem */ if (f_mount(0, &filesystem) != FR_OK) { return; } /* could not open the selected directory */ if (f_opendir(&dir_1, "/") != FR_OK) { return; } /* Start the TFTP read mode*/ tftp_process_read(upcb, addr, port, FileName); break; } case TFTP_WRQ: /* TFTP WRQ (write request) */ { /* Read the name of the file asked by the client to be received and writen in the SD card */ tftp_extract_filename(FileName, pkt_buf->payload); /* Could not open filesystem */ if (f_mount(0, &filesystem) != FR_OK) { return; } /* If Could not open the selected directory */ if (f_opendir(&dir_2, "/") != FR_OK) { return; } /* Start the TFTP write mode*/ tftp_process_write(upcb, addr, port, FileName); break; } default: /* TFTP unknown request op */ /* send generic access violation message */ tftp_send_error_message(upcb, addr, port, TFTP_ERR_ACCESS_VIOLATION); udp_remove(upcb); break; } }
/** * @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(LED1); } } } } } } /* Unlink the USB disk I/O driver */ FATFS_UnLinkDriver(USBDISKPath); }
int main() { // DeInit NVIC and SCBNVIC NVIC_DeInit(); NVIC_SCBDeInit(); /* Configure the NVIC Preemption Priority Bits: * two (2) bits of preemption priority, six (6) bits of sub-priority. * Since the Number of Bits used for Priority Levels is five (5), so the * actual bit number of sub-priority is three (3) */ NVIC_SetPriorityGrouping(0x05); NVIC_SetVTOR(0x00000000); #ifdef UARTDEBUG uart_init(); #endif BlockDevInit(); #ifdef UARTDEBUG if (1) { U32 size; BlockDevGetSize(&size); DBG("Found SD card of size %d", size); BlockDevGetBlockLength(&size); DBG("block length %d", size); } #endif if (bootloader_button_pressed() || (user_code_present() == 0)) { DBG("entering bootloader"); init_usb_msc_device(); for (;usb_msc_not_ejected();) USBHwISR(); DBG("usb ejected, rebooting"); USBHwConnect(FALSE); spi_close(); } else { if ((r = f_mount(0, &fatfs)) == FR_OK) { if ((r = f_open(&f, "/firmware.bin", FA_READ | FA_OPEN_EXISTING)) == FR_OK) { unsigned int fs = f_size(&f); DBG("found firmware.bin with %u bytes", fs); if ((fs > 0) && (fs <= USER_FLASH_SIZE)) { U8 buffer[FLASH_BUF_SIZE]; for (unsigned int i = 0; i < fs; i += FLASH_BUF_SIZE) { unsigned int j = FLASH_BUF_SIZE; if (i + j > fs) j = fs - i; DBG("writing %d-%d", i, i+j); if ((r = f_read(&f, buffer, j, &j)) == FR_OK) { // pad last block to a full sector size while (j < FLASH_BUF_SIZE) { buffer[j++] = 0xFF; } write_flash((unsigned int *) (USER_FLASH_START + i), (char *) &buffer, j); } else { DBG("read failed: %d", r); i = fs; } } r = f_close(&f); r = f_unlink("/firmware.bck"); r = f_rename("/firmware.bin", "/firmware.bck"); } } else { DBG("open \"/firmware.bin\" failed: %d", r); } #ifdef GENERATE_FIRMWARE_CUR if (f_open(&f, "/firmware.bck", FA_READ | FA_OPEN_EXISTING)) { f_close(&f); } else { // no firmware.bck, generate one! if (f_open(&f, "/firmware.bck", FA_WRITE | FA_CREATE_NEW) == FR_OK) { U8 *flash = (U8 *) USER_FLASH_START; f_close(&f); } } #endif // elm-chan's fatfs doesn't have an unmount function // f_umount(&fatfs); } else { DBG("mount failed: %d", r); } spi_close(); if (user_code_present()) { DBG("starting user code..."); execute_user_code(); } else { DBG("user code invalid, rebooting"); } } NVIC_SystemReset(); }
// Init FS uint8_t sdc_init(void) { return (f_mount(&FatFs,"",0) == FR_OK) ? SDCI_OK : SDCI_MOUNT_ERR; }
/** * @brief Main program * @param None * @retval None */ int main(void) { FRESULT res1, res2; /* FatFs function common result codes */ uint32_t byteswritten1, byteswritten2; /* File write counts */ uint32_t bytesread1, bytesread2; /* File read counts */ uint8_t wtext[] = "This is STM32 working with FatFs"; /* File write buffer */ uint8_t rtext1[100], rtext2[100]; /* File read buffers */ /* 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 the system clock to 175 MHz */ SystemClock_Config(); /* Initialize Mfx for SD detection */ BSP_IO_Init(); /* Configure LED1 and LED3 */ BSP_LED_Init(LED1); BSP_LED_Init(LED3); /*##-1- Link the disk I/O drivers ##########################################*/ if((FATFS_LinkDriver(&SDRAMDISK_Driver, RAMpath) == 0) && (FATFS_LinkDriver(&SD_Driver, SDpath) == 0)) { /*##-2- Register the file system object to the FatFs module ##############*/ res1 = f_mount(&RAMFatFs, (TCHAR const*)RAMpath, 0); res2 = f_mount(&SDFatFs, (TCHAR const*)SDpath, 0); if((res1 != FR_OK) || (res2 != FR_OK)) { /* FatFs Initialization Error */ Error_Handler(); } else { /*##-3- Create a FAT file system (format) on the logical drives ########*/ /* WARNING: Formatting the uSD card will delete all content on the device */ res1 = f_mkfs((TCHAR const*)RAMpath, 0, 0); res2 = f_mkfs((TCHAR const*)SDpath, 0, 0); if((res1 != FR_OK) || (res2 != FR_OK)) { /* FatFs Format Error */ Error_Handler(); } else { /*##-4- Create and Open new text file objects with write access ######*/ res1 = f_open(&RAMFile, "0:STM32.TXT", FA_CREATE_ALWAYS | FA_WRITE); res2 = f_open(&SDFile, "1:STM32.TXT", FA_CREATE_ALWAYS | FA_WRITE); if((res1 != FR_OK) || (res2 != FR_OK)) { /* 'STM32.TXT' file Open for write Error */ Error_Handler(); } else { /*##-5- Write data to the text files ###############################*/ res1 = f_write(&RAMFile, wtext, sizeof(wtext), (void *)&byteswritten1); res2 = f_write(&SDFile, wtext, sizeof(wtext), (void *)&byteswritten2); if((byteswritten1 == 0) || (byteswritten2 == 0) || (res1 != FR_OK) || (res2 != FR_OK)) { /* 'STM32.TXT' file write Error */ Error_Handler(); } else { /*##-6- Close the open text files ################################*/ f_close(&RAMFile); f_close(&SDFile); /*##-7- Open the text files object with read access ##############*/ res1 = f_open(&RAMFile, "0:STM32.TXT", FA_READ); res2 = f_open(&SDFile, "1:STM32.TXT", FA_READ); if((res1 != FR_OK) || (res2 != FR_OK)) { /* 'STM32.TXT' file Open for read Error */ Error_Handler(); } else { /*##-8- Read data from the text files ##########################*/ res1 = f_read(&RAMFile, rtext1, sizeof(rtext1), (UINT*)&bytesread1); res2 = f_read(&SDFile, rtext2, sizeof(rtext2), (UINT*)&bytesread2); if((res1 != FR_OK) || (res2 != FR_OK)) { /* 'STM32.TXT' file Read or EOF Error */ Error_Handler(); } else { /*##-9- Close the open text files ############################*/ f_close(&RAMFile); f_close(&SDFile); /*##-10- Compare read data with the expected data ############*/ if((bytesread1 != byteswritten1) || (bytesread2 != byteswritten2)) { /* 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 disk I/O drivers #######################################*/ FATFS_UnLinkDriver(RAMpath); FATFS_UnLinkDriver(SDpath); /* Infinite loop */ while (1) { } }
static void flash_to_udisk(void) { FRESULT result; FATFS fs; FIL file; DIR DirInf; uint32_t bw; uint8_t ucErr; char write_buf_374[1024]; char file_name_buf[20]; char tmp[10]; memset(write_buf_374, 0, 1024); memset(file_name_buf, 0, 20); memset(tmp, 0, 10); strcat(file_name_buf, "/"); sprintf(tmp, "%d", conf->id); strcat(file_name_buf, tmp); strcat(file_name_buf, ".TXT"); CH374_DISEN; result = f_mount(0, &fs); if (result != FR_OK){ printf("FileSystem Mounted Failed (%d)\r\n", result); return; } result = f_opendir(&DirInf, "/"); if (result != FR_OK){ printf("Open Root Directory Error (%d)\r\n", result); return; } result = f_open(&file, conf->file_name, FA_OPEN_ALWAYS | FA_READ); if(result !=FR_OK){ printf("open error \n\r"); return; } CH374_EN; ucErr = ch374_CreateFile(file_name_buf); /* 新建文件并打开,如果文件已经存在则先删除后再新建 */ StopIfError(ucErr); ch374_ModifyFileDate(atoi(t_now->year), atoi(t_now->month), atoi(t_now->day)); StopIfError(ucErr); memset(write_buf_374, 0, 1024); //file.fptr < file.fsize while(1){ if(file.fsize - file.fptr < sizeof(write_buf_374)){ CH374_DISEN; result = f_read(&file, write_buf_374, file.fsize - file.fptr, &bw); if(result !=FR_OK) printf("open error : %d \n\r",result); CH374_EN; ucErr = ch374_WriteFile((uint8_t *)write_buf_374, sizeof(write_buf_374)); /* 写数据到U_DISK文件 */ StopIfError(ucErr); memset(write_buf_374, 0, 1024); break; }else{ CH374_DISEN; result = f_read(&file, write_buf_374, sizeof(write_buf_374), &bw); //从flash中读到缓冲区 if(result !=FR_OK) printf("open error : %d \n\r",result); CH374_EN; ucErr = ch374_WriteFile((uint8_t *)write_buf_374, sizeof(write_buf_374)); /* 写数据到U_DISK文件 */ StopIfError(ucErr); memset(write_buf_374, 0, 1024); } } ucErr = ch374_CloseFile(); StopIfError(ucErr); CH374_DISEN; f_close(&file); f_mount(0, NULL); CH374_EN; }
/*! \brief Main function. Execution starts here. */ int main(void) { #if SAMD21 || SAML21 system_init(); #else sysclk_init(); board_init(); #endif irq_initialize_vectors(); cpu_irq_enable(); // Initialize the sleep manager sleepmgr_init(); ui_init(); // Start USB host stack uhc_start(); // The USB management is entirely managed by interrupts. // As a consequence, the user application does only have : // - to play with the power modes // - to create a file on each new LUN connected while (true) { //sleepmgr_enter_sleep(); if (main_usb_sof_counter > 2000) { main_usb_sof_counter = 0; volatile uint8_t lun; FRESULT res; for (lun = LUN_ID_USB; (lun < LUN_ID_USB + uhi_msc_mem_get_lun()) && (lun < MAX_DRIVE); lun++) { // Check if LUN has been already tested if (TEST_OK == lun_states[lun] || TEST_ERROR == lun_states[lun]) { continue; } // Mount drive memset(&fs, 0, sizeof(FATFS)); res = f_mount(lun, &fs); if (FR_INVALID_DRIVE == res) { // LUN is not present lun_states[lun] = TEST_NO_PRESENT; continue; } // Create a test file on the disk test_file_name[0] = lun + '0'; res = f_open(&file_object, (char const *)test_file_name, FA_CREATE_ALWAYS | FA_WRITE); if (res == FR_NOT_READY) { // LUN not ready lun_states[lun] = TEST_NO_PRESENT; f_close(&file_object); continue; } if (res != FR_OK) { // LUN test error lun_states[lun] = TEST_ERROR; f_close(&file_object); continue; } // Write to test file f_puts(MSG_TEST, &file_object); // LUN test OK lun_states[lun] = TEST_OK; f_close(&file_object); } if (main_count_states(TEST_NO_PRESENT) == MAX_DRIVE) { ui_test_finish(false); // Test fail } else if (MAX_DRIVE != main_count_states(TEST_NULL)) { if (main_count_states(TEST_ERROR)) { ui_test_finish(false); // Test fail } else if (main_count_states(TEST_OK)) { ui_test_flag_reset(); ui_test_finish(true); // Test OK } } else { ui_test_flag_reset(); } } } }
/** * @brief Manages MSC Menu Process. * @param None * @retval None */ void MSC_MenuProcess(void) { switch(demo.msc_state) { case APPLI_MSC_IDLE: Demo_SelectItem(MSC_main_menu, 0); demo.msc_state = APPLI_MSC_WAIT; demo.select = 0; break; case APPLI_MSC_WAIT: if(demo.select != prev_select) { prev_select = demo.select; Demo_SelectItem(MSC_main_menu, demo.select & 0x7F); /* Handle select item */ if(demo.select & 0x80) { demo.select &= 0x7F; switch(demo.select) { case 0: demo.msc_state = APPLI_MSC_FILE_OPERATIONS; break; case 1: demo.msc_state = APPLI_MSC_EXPLORER; break; case 2: /* Return */ demo.state = DEMO_IDLE; demo.select = 0; LCD_UsrLogY("> MSC application closed.\n"); f_mount(0,0,0); break; default: break; } } } break; case APPLI_MSC_FILE_OPERATIONS: /* Read and Write File Here */ if(Appli_HS_state == APPLICATION_HS_READY) { MSC_File_Operations(); } demo.msc_state = APPLI_MSC_WAIT; break; case APPLI_MSC_EXPLORER: /* Display disk content */ if(Appli_HS_state == APPLICATION_HS_READY) { Explore_Disk("0:/", 1); } demo.msc_state = APPLI_MSC_WAIT; break; default: break; } }
int main(void) { static DWORD per_sec = 0; InitializeBoard(); // Initialize application specific hardware PowerONGSM(TRUE); Initialization(); //................File System Initialisation...................// while(disk_status(MMC_DRIVE)); //Wait untill SD card is inserted if(!(disk_status(MMC_DRIVE) ))//& STA_NODISK)) //if SD card is inserted { // disk inserted so initialise it if (disk_initialize(MMC_DRIVE) == 0) //if SD card initialize { if (f_mount(MMC_DRIVE, &fatfs[MMC_DRIVE]) == FR_OK) { uc_Flag_SDInit = TRUE; //succefully initialise sd card //if file system initialize properly } else { Reset(); } } else { Reset(); } } InitConnection(); //functional initialization gateway device sensors,etc while(1) { ClrWdt(); if(ReadADC==TRUE) { Sample_Flag++; ReadADC=FALSE; ADC_Read_Value=AnalogData*3.3/1024; Toatal_Value=Toatal_Value+ADC_Read_Value; if(ADC_Read_Value<min) { min=ADC_Read_Value; } else if(ADC_Read_Value>max) { max=ADC_Read_Value; } } if((Sample_Flag>=600) && (uc_HTTP_DONE==TRUE)) { heartbeat++; value=Toatal_Value/Sample_Flag; if(uc_GPRS_Done==FALSE) { GPRSFailed++; } uc_GPRS_Done=FALSE; Sample_Flag=0; min=0; max=0; Toatal_Value=0; sendData=TRUE; POST_DATA=SEND_DATA; uc_HTTP_DONE=FALSE; } if(sendData==TRUE) { switch(POST_DATA) { case GATE_HEARTBEAT: { if(url_build==FALSE) { Transmit_Gateway_Heartbeat(); url_build=TRUE; uc_GPRS_Done=FALSE; } SendURL((METHOD) POST); if(uc_GPRS_Done==TRUE) { POST_DATA=SENS_HEARTBEAT; url_build=FALSE; } break; } case SENS_HEARTBEAT: { if(url_build==FALSE) { Transmit_Sensor_Heartbeat(); url_build=TRUE; uc_GPRS_Done=FALSE; } SendURL((METHOD) POST); if(uc_GPRS_Done==TRUE) { url_build=FALSE; sendData=FALSE; uc_HTTP_DONE=TRUE; POST_DATA=10; } break; } case SEND_DATA: { if(url_build==FALSE) { Transmit_Analog_Data(value); url_build=TRUE; uc_GPRS_Done=FALSE; // GetTimeStamp(); //time=t_day; } SendURL((METHOD)POST); if(uc_GPRS_Done==TRUE) { if(heartbeat>=5) { heartbeat=0; POST_DATA=GATE_HEARTBEAT; url_build=FALSE; } else { POST_DATA=10; url_build=FALSE; sendData=FALSE; uc_HTTP_DONE=TRUE; // GetTimeStamp(); //time1=t_day; asm("NOP"); } } break; } default: break; } } if(TickGet() - per_sec >= TICK_SECOND/2ul) // Blink LED0 (right most one) every half second. { per_sec = TickGet(); LED4_IO ^= 1; //internal heartbit LED HRTBIT_LED_IO ^=1; //pannel heartbit LED } if((uc_GSMRestart==TRUE) || ((uc_GPRSFailed == TRUE) && (uc_GPRSTried == TRUE))) { PowerONGSM(FALSE); DelayMs(200); uc_GSMRestart=3; PowerONGSM(TRUE); uc_GPRSFailed=FALSE; uc_GPRSTried=FALSE; } } }
bmp_error_t bmpSaveScreenshot(const char* filename) { DSTATUS stat; bmp_error_t error = BMP_ERROR_NONE; bmp_header_t header; bmp_infoheader_t infoHeader; uint32_t lcdWidth, lcdHeight, x, y, bgra32; UINT bytesWritten; uint16_t rgb565, eof; uint8_t r, g, b; // Create a new file (Crossworks only) stat = disk_initialize(0); if (stat & STA_NOINIT) { return BMP_ERROR_SDINITFAIL; } if (stat & STA_NODISK) { return BMP_ERROR_SDINITFAIL; } if (stat == 0) { // SD card sucessfully initialised DSTATUS stat; DWORD p2; WORD w1; BYTE res, b1; DIR dir; // Try to mount drive res = f_mount(0, &Fatfs[0]); if (res != FR_OK) { return BMP_ERROR_SDINITFAIL; } if (res == FR_OK) { // Create a file (overwriting any existing file!) if(f_open(&bmpSDFile, filename, FA_READ | FA_WRITE | FA_CREATE_ALWAYS)!=FR_OK) { return BMP_ERROR_UNABLETOCREATEFILE; } } } lcdWidth = lcdGetWidth(); lcdHeight = lcdGetHeight(); // Create header header.type = 0x4d42; // 'BM' header.size = (lcdWidth * lcdHeight * 3) + sizeof(header) + sizeof(infoHeader); // File size in bytes header.reserved1 = 0; header.reserved2 = 0; header.offset = 0x36; // Offset in bytes to the image data // Create infoheader infoHeader.size = sizeof(infoHeader); infoHeader.width = lcdWidth; infoHeader.height = lcdHeight; infoHeader.planes = 1; infoHeader.bits = 24; infoHeader.compression = BMP_COMPRESSION_NONE; infoHeader.imagesize = (lcdWidth * lcdHeight * 3) + 2; // 3 bytes per pixel + 2 bytes for EOF infoHeader.xresolution = 0x0B12; infoHeader.yresolution = 0x0B12; infoHeader.ncolours = 0; infoHeader.importantcolours = 0; // Write header to disk f_write(&bmpSDFile, &header.type, sizeof(header.type), &bytesWritten); f_write(&bmpSDFile, &header.size, sizeof(header.size), &bytesWritten); f_write(&bmpSDFile, &header.reserved1, sizeof(header.reserved1), &bytesWritten); f_write(&bmpSDFile, &header.reserved2, sizeof(header.reserved2), &bytesWritten); f_write(&bmpSDFile, &header.offset, sizeof(header.offset), &bytesWritten); f_write(&bmpSDFile, &infoHeader.size, sizeof(infoHeader.size), &bytesWritten); f_write(&bmpSDFile, &infoHeader.width, sizeof(infoHeader.width), &bytesWritten); f_write(&bmpSDFile, &infoHeader.height, sizeof(infoHeader.height), &bytesWritten); f_write(&bmpSDFile, &infoHeader.planes, sizeof(infoHeader.planes), &bytesWritten); f_write(&bmpSDFile, &infoHeader.bits, sizeof(infoHeader.bits), &bytesWritten); f_write(&bmpSDFile, &infoHeader.compression, sizeof(infoHeader.compression), &bytesWritten); f_write(&bmpSDFile, &infoHeader.imagesize, sizeof(infoHeader.imagesize), &bytesWritten); f_write(&bmpSDFile, &infoHeader.xresolution, sizeof(infoHeader.xresolution), &bytesWritten); f_write(&bmpSDFile, &infoHeader.yresolution, sizeof(infoHeader.yresolution), &bytesWritten); f_write(&bmpSDFile, &infoHeader.ncolours, sizeof(infoHeader.ncolours), &bytesWritten); f_write(&bmpSDFile, &infoHeader.importantcolours, sizeof(infoHeader.importantcolours), &bytesWritten); // Write image data to disk (starting from bottom row) for (y = lcdHeight; y != 0; y--) { for (x = 0; x < lcdWidth; x++) { rgb565 = lcdGetPixel(x, y - 1); // Get RGB565 pixel bgra32 = colorsRGB565toBGRA32(rgb565); // Convert RGB565 to 24-bit color r = (bgra32 & 0x00FF0000) >> 16; g = (bgra32 & 0x0000FF00) >> 8; b = (bgra32 & 0x000000FF); f_write(&bmpSDFile, &b, 1, &bytesWritten); // Write RGB data f_write(&bmpSDFile, &g, 1, &bytesWritten); f_write(&bmpSDFile, &r, 1, &bytesWritten); } } // Write EOF (2 bytes) eof = 0x0000; f_write(&bmpSDFile, &eof, 2, &bytesWritten); // Close the file f_close(&bmpSDFile); // Return OK signal return BMP_ERROR_NONE; }
/** * \brief Application entry point. * * \return Unused (ANSI-C compatibility). */ int main(void) { char test_file_name[] = "0:sd_mmc_test.txt"; Ctrl_status status; FRESULT res; FATFS fs; FIL file_object; const usart_serial_options_t usart_serial_options = { .baudrate = CONF_TEST_BAUDRATE, .charlength = CONF_TEST_CHARLENGTH, .paritytype = CONF_TEST_PARITY, .stopbits = CONF_TEST_STOPBITS, }; irq_initialize_vectors(); cpu_irq_enable(); sysclk_init(); board_init(); stdio_serial_init(CONF_TEST_USART, &usart_serial_options); /* Initialize SD MMC stack */ sd_mmc_init(); printf("\x0C\n\r-- SD/MMC/SDIO Card Example on FatFs --\n\r"); printf("-- Compiled: %s %s --\n\r", __DATE__, __TIME__); while (1) { printf("Please plug an SD, MMC or SDIO card in slot.\n\r"); /* Wait card present and ready */ do { status = sd_mmc_test_unit_ready(0); if (CTRL_FAIL == status) { printf("Card install FAIL\n\r"); printf("Please unplug and re-plug the card.\n\r"); while (CTRL_NO_PRESENT != sd_mmc_check(0)) { } } } while (CTRL_GOOD != status); printf("Mount disk (f_mount)...\r\n"); memset(&fs, 0, sizeof(FATFS)); res = f_mount(LUN_ID_SD_MMC_0_MEM, &fs); if (FR_INVALID_DRIVE == res) { printf("[FAIL] res %d\r\n", res); goto main_end_of_test; } printf("[OK]\r\n"); printf("Create a file (f_open)...\r\n"); test_file_name[0] = LUN_ID_SD_MMC_0_MEM + '0'; res = f_open(&file_object, (char const *)test_file_name, FA_CREATE_ALWAYS | FA_WRITE); if (res != FR_OK) { printf("[FAIL] res %d\r\n", res); goto main_end_of_test; } printf("[OK]\r\n"); printf("Write to test file (f_puts)...\r\n"); if (0 == f_puts("Test SD/MMC stack\n", &file_object)) { f_close(&file_object); printf("[FAIL]\r\n"); goto main_end_of_test; } printf("[OK]\r\n"); f_close(&file_object); printf("Test successfull.\n\r"); main_end_of_test: printf("Please unplug the card.\n\r"); while (CTRL_NO_PRESENT != sd_mmc_check(0)) { } } }
int notmain (void) { FRESULT rc; /* Result code */ DIR dir; /* Directory object */ FILINFO fno; /* File information object */ UINT br ; bcm2835_uart_begin(); f_mount(0, &Fatfs); /* Register volume work area (never fails) */ #if 1 printf("\r\nOpen an existing file (rainbowcircle.ild).\r\n"); rc = f_open(&Fil, "rainbowcircle.ild", FA_READ); if (rc) die(rc); for (;;) { uint32_t i1 = bcm2835_st_read(); rc = f_read(&Fil, Buff, 20, &br); /* Read a chunk of file */ uint32_t i2 = bcm2835_st_read(); if (rc || !br) break; /* Error or end of file */ printf("br [%d] i2-i1 [%d]\n", br, (int)(i2-i1)); } if (rc) die(rc); printf("\r\nClose the file.\r\n"); rc = f_close(&Fil); if (rc) die(rc); #endif #if 0 printf("\r\nCreate a new file (hello.txt).\r\n"); rc = f_open(&Fil, "HELLO.TXT", FA_WRITE | FA_CREATE_ALWAYS); if (rc) die(rc); printf("\r\nWrite a text data. (Hello world!)\r\n"); rc = f_write(&Fil, "Hello world!\r\n", 14, &bw); if (rc) die(rc); printf("%u bytes written.\r\n", bw); printf("\r\nClose the file.\r\n"); rc = f_close(&Fil); if (rc) die(rc); #endif printf("\r\nOpen root directory.\r\n"); rc = f_opendir(&dir, ""); if (rc) die(rc); char filename_buf[32]; printf("\r\nDirectory listing...\r\n"); for (;;) { fno.lfname = filename_buf; fno.lfsize = sizeof(filename_buf); rc = f_readdir(&dir, &fno); /* Read a directory item */ if (rc || !fno.fname[0]) break; /* Error or end of dir */ if (fno.fattrib & AM_DIR) printf(" <dir> %s\r\n", fno.fname); else { char * fn = *fno.lfname ? fno.lfname : fno.fname; printf("%8lu %s\r\n", fno.fsize, (char *) fn); } } if (rc) die(rc); printf("\nTest completed.\n"); die(0); return 0; }