Exemple #1
0
void bootloader(void)
{
	FSFILE* file;

	USBInitialize(0);

	if (!FSInit())
	{
		// File system failed - pretty much DISKmount didn't work
		AT45D_FormatFS();
		if (!FSInit())
		{
			error(ERR_FS_INIT);
		}
	}

	while (1)
	{
		USBTasks();
		BlinkBlueLED();

		// User Application USB tasks
		if ((USBDeviceState < CONFIGURED_STATE) || (USBSuspendControl == 1))
		{
			// do nothing
		}
		else
		{
			BlinkGreenLED();
			MSDTasks();
		}
		if (_T1IF)
		{
			_T1IF = 0;

			// check for MSD activity...
			if (MDD_AT45D_Write_Activity)
			{
				MDD_AT45D_Write_Activity = 0;
			}
			else
			{
				file = FSfopen("image.hex", "r");
				if (file != NULL)
				{
					file_flash(file);
					FSfclose(file);
					FSremove("image.hex");
					//AT45D_FormatFS();
					return;
				}
			}
		}
	}
}
/*
 *	Load boot code from a saved core image, a boot file or from
 *	first sector of disk drive A:
 */
int boot(void)
{
    //register int fd;
    FSFILE *fd;
    puts("\r\nBooting...\r\n");
    /*
    	if (l_flag) {
    		return(load_core());
    	}

    	if (x_flag) {
    		return(load_file(xfn));
    	}
     */
    FSInit();
    if ((fd = FSfopen("drivea.cpm", "R")) == NULL) {
        printf("file disks/drivea.cpm");
        puts("\r\n");
        FSfclose(fd);
        return(1);
    }
    if (FSfread((char *) ram, 1, 128,fd) != 128) {
        printf("file disks/drivea.cpm");
        puts("\r\n");
        FSfclose(fd);
        return(1);
    }

    FSfclose(fd);
    return(0);
}
/*
 *	Read a file into the memory of the emulated CPU.
 *	The following file formats are supported:
 *
 *		binary images with Mostek header
 *		Intel hex
 */
int load_file(char *s) {
    char fn[LENCMD];
    BYTE fileb[5];
    register char *pfn = fn;
    //	int fd;
    FSFILE *fd;
    if (!FSInit()) printf("Can't Init FS\n\r");
    while (isspace((int) *s))
        s++;
    while (*s != ',' && *s != '\n' && *s != '\0' && *s != '\r')
        *pfn++ = *s++;
    *pfn = '\0';
    if (strlen(fn) == 0) {
        puts("no input file given");
        return (1);
    }
    if ((fd = FSfopen(fn, "R")) == NULL) {
        printf("can't open file %s\n", fn);
        return (1);
    }
    if (*s == ',')
        wrk_ram = ram +exatoi(++s);
    else
        wrk_ram = NULL;
    FSfread((char *) fileb, 5, 1, fd); /*	read first 5 bytes of file */

    if (*fileb == (BYTE) 0xff) { /* Mostek header ? */
        FSfseek(fd, 0l, 0);
        return (load_mos(fd, fn));
    } else {
        close(fd);
        return (load_hex(fn));
    }

}
int mount_sd_fat(const char *path)
{
    int result = -1;

    // get command and client
    void* pClient = malloc(sizeof(FSClient));
    void* pCmd = malloc(sizeof(FSCmdBlock));

    if(!pClient || !pCmd) {
        // just in case free if not 0
        if(pClient)
            free(pClient);
        if(pCmd)
            free(pCmd);
        return -2;
    }

    FSInit();
    FSInitCmdBlock(pCmd);
    FSAddClient(pClient, -1);

    char *mountPath = NULL;

    if(MountFS(pClient, pCmd, &mountPath) == 0) {
        result = sd_fat_add_device(path, mountPath, pClient, pCmd);
        free(mountPath);
    }

    return result;
}
Exemple #5
0
void Initialize(){
	DrawString(TOP_SCREEN,  " INITIALIZE... ", 0, 240-8, WHITE, BLACK);
	if(FSInit()){
		DrawString(TOP_SCREEN,  " LOADING...    ", 0, 240-8, WHITE, BLACK);
	}else{
		DrawString(TOP_SCREEN,  " ERROR!        ", 0, 240-8, RED, BLACK);
	}
	LoadPack();
	//Console Stuff
	memset(TOP_SCREEN, 0x00, 0x46500);
	memset(TOP_SCREEN2, 0x00, 0x46500);
	ConsoleSetXY(15, 15);
	ConsoleSetWH(370, 160);
	ConsoleSetBorderColor(BLUE);
	ConsoleSetTextColor(WHITE);
	ConsoleSetBackgroundColor(BLACK);
	ConsoleSetSpecialColor(BLUE);
	ConsoleSetSpacing(2);
	ConsoleSetBorderWidth(3);
	//Check that the data is installed
	f_mkdir ("rxTools");
	f_mkdir ("rxTools/nand");
	InstallConfigData();
	
	SplashScreen();
	for(int i = 0; i < 0x333333*6; i++){
		u32 pad = GetInput();
		if(pad & BUTTON_R1 && i > 0x333333) goto rxTools_boot;
	}
    rxModeQuickBoot();
	rxTools_boot:
	memset(TOP_SCREEN, 0x00, 0x46500);
	memset(TOP_SCREEN2, 0x00, 0x46500);
}
int FileSystemInit(void)
{
    #if defined STACK_USE_MPFS2
        MPFSInit();
    #elif defined STACK_USE_MDD 
        return FSInit();
    #endif
    
    return TRUE;
}
Exemple #7
0
// called at startup to initialise the telemetry log system
void log_init(void)
{
//	init_dataflash(); // this should now be getting device specific called from lower layers via FSInit()
	if (!FSInit())
	{
#ifdef USE_AT45D_FLASH
		AT45D_FormatFS();
#elif (WIN == 1) || (NIX == 1)
#else
#warning No Mass Storage Device Format Function Defined
#endif // USE_AT45D_FLASH
		if (!FSInit())
		{
			printf("File system initialisation failed\r\n");
			return;
		}
	}
	printf("File system initalised\r\n");
}
Exemple #8
0
// @breif  Main routine surely.
int main(void) {

	FSInit();
	CFW_getSystemVersion();
	if (cfw_bootGUI==true) //If gui autoboot is enabled or L is held, show the ui //L held not working
	{
		DrawClearScreenAll();
		//MENU
		while (true)
		{
			//DRAW GUI
			if (menu_idx == MENU_ITEMS - 1)
			{
				sprintf(str, "/3ds/PastaCFW/UI/%c/menu6.bin", cfw_theme);
				DrawBottomSplash(str);
				sprintf(str, "/3ds/PastaCFW/UI/%c/creditsTOP.bin", cfw_theme);
				DrawTopSplash(str);
				TOP_Current = 0;
			}
			else
			{
				sprintf(str, "/3ds/PastaCFW/UI/%c/menu0.bin", cfw_theme);
				str[23] = menu_idx + 48;
				DrawBottomSplash(str); //BOTTOM SCREEN
				if (TOP_Current == 0){
					sprintf(str, "/3ds/PastaCFW/UI/%c/menuTOP.bin", cfw_theme);
					DrawTopSplash(str); //TOP SCREEN
					TOP_Current = 1;
				}
			}
			//MENU CONTROLS
			u32 pad_state = HidWaitForInput();
			if ((pad_state & BUTTON_RIGHT || pad_state & BUTTON_DOWN) && menu_idx != MENU_ITEMS - 1) menu_idx++; //MOVE RIGHT/DOWN (It depends on the theme)
			else if ((pad_state & BUTTON_LEFT || pad_state & BUTTON_UP) && menu_idx != 0)menu_idx--; //MOVE LEFT/UP (It depends on the theme)
			else if (pad_state & BUTTON_A)//SELECT
			{
				if (menu_idx == 0){ CFW_Boot(); break; }//BOOT CFW
				else if (menu_idx == 1)break; //REBOOT
				else if (menu_idx == 2)CFW_NandDumper(); //NAND DUMPER
				else if (menu_idx == 4)CFW_ARM9Dumper(); //ARM9 RAM DUMPER
				else if (menu_idx == 5)CFW_Settings(); //SETTINGS
			}
			else if (pad_state & BUTTON_START && pad_state & BUTTON_SELECT) //POWER OFF
			{
				i2cWriteRegister(I2C_DEV_MCU, 0x20, (u8)(1 << 0)); //As seen on 3dbrew
				while (1);
			}
		}
	}
	else CFW_Boot(); //else directly boot the cfw
	if (firmlaunch == true && cfw_enablefirmlaunch) FirmLaunch();

	// return control to FIRM ARM9 code (performs firmlaunch)
	return 0;
}
Exemple #9
0
static bool HardwareInit(DEV_ID DevId)
{
	switch(DevId)
	{
		case DEV_ID_SD:
			if(!IsCardLink())
			{
				return FALSE;
			}
			FSDeInit(DEV_ID_SD);
			if(SdCardInit())	
			{
				return FALSE;
			}
			if(!FSInit(DEV_ID_SD))
			{
				return FALSE;
			}
			return TRUE;
		case DEV_ID_USB:
			Usb2SetDetectMode(1, 0);
			UsbSetCurrentPort(UDISK_PORT_NUM);
			if(!IsUDiskLink())
			{
				return FALSE;
			}
			FSDeInit(DEV_ID_SD);
			FSDeInit(DEV_ID_USB);
			if(!HostStorInit())
			{
				return FALSE;
			}
			if(!FSInit(DEV_ID_USB))
			{
				return FALSE;
			}
			return TRUE;
		default:
			break;
	}
	return FALSE;
}
Exemple #10
0
// *--------------------------------------------------------------------------------*
int main(){
	UINT16 Count=0;
	
    mJTAGPortEnable(0);							// JTAG des-habilitado
	SYSTEMConfigPerformance(GetSystemClock()); 	// Activa pre-cache.-
	
	LED1_OUTPUT();
	LED2_OUTPUT();
	INTEnableSystemMultiVectoredInt();
	deviceAttached = FALSE;
    //Initialize the stack
    USBInitialize(0);
    
	while(1){
		//USB stack process function
        USBTasks();
		if(++Count==0){
			LED1_TOGGLE();
		}
        //if thumbdrive is plugged in
        if(USBHostMSDSCSIMediaDetect()){
            deviceAttached = TRUE;
            LED1_OFF();
            //now a device is attached
            //See if the device is attached and in the right format
            if(FSInit()){
                //Opening a file in mode "w" will create the file if it doesn't
                //  exist.  If the file does exist it will delete the old file
                //  and create a new one that is blank.
                myFile = FSfopen("test.txt","w");

                //Write some data to the new file.
                FSfwrite("This is a test.",1,15,myFile);                

                //Always make sure to close the file so that the data gets
                //  written to the drive.
                FSfclose(myFile);

                //Just sit here until the device is removed.
                while(deviceAttached == TRUE){
                    USBTasks();
                    if(++Count==0){
						LED2_TOGGLE();
					}
                }
                LED2_OFF();
            }
        }
	}
}
Exemple #11
0
/************************************************************************
Function: void MonitorDriveMedia( void )

Precondition: None

Overview: This function calls the background tasks necessary to support
          USB Host operation.  Upon initial insertion of the media, it
          initializes the file system support and reads the volume label.
          Upon removal of the media, the volume label is marked invalid.

Input: None

Output: None
*************************************************************************/
void MonitorDriveMedia(void)
{
    BYTE        mediaPresentNow;
    BYTE        mountTries;
    SearchRec   searchRecord;

        #if defined ENABLE_USB_MSD_DEMO

    // Call to USBTasks() is assumed to be done in the main. If not you can
    // call it here.
    //USBTasks();	
    mediaPresentNow = USBHostMSDSCSIMediaDetect();
        #elif defined ENABLE_SD_MSD_DEMO
    mediaPresentNow = MDD_MediaDetect();
        #endif
    if(mediaPresentNow != mediaPresent)
    {
        if(mediaPresentNow)
        {
            mountTries = 10;
            while(!FSInit() && mountTries--);
            if(!mountTries)
            {
                //UART2PrintString("APP: Could not mount media\r\n");
                mediaPresent = FALSE;
            }
            else
            {
                mediaPresent = TRUE;

                // Find the volume label.  We need to do this here while we are at the
                // root directory.
                if(!FindFirst("*.*", ATTR_VOLUME, &searchRecord))
                {
                    strcpy(volume.label, searchRecord.filename);
                    volume.valid = TRUE;
                }
            }
        }
        else
        {
            mediaPresent = FALSE;
            volume.valid = FALSE;
        }
    }
}
Exemple #12
0
int main()
{
    //Clock init  M=43, N1,2 = 2 == 39.61MIPS
    PLLFBD = 43;
    CLKDIVbits.PLLPOST = 0; // N1 = 2
    CLKDIVbits.PLLPRE = 0; // N2 = 2
    OSCTUN = 0;
    RCONbits.SWDTEN = 0;

    __builtin_write_OSCCONH(0x01); // Initiate Clock Switch to Primary (3?)

    __builtin_write_OSCCONL(0x01); // Start clock switching

    while (OSCCONbits.COSC != 0b001); // Wait for Clock switch to occur

    while (OSCCONbits.LOCK != 1) {
    };
    //End of clock init.
    
    initPins();
    
    Uart2Init(115200L, InterruptRoutine);

//    Uart2PrintChar('S');
    while (!SD_IN);
    
    // initialize the file system, open the file, read the file and send in chunks
    FSInit();

    FSFILE * openFile = FSfopen("send.txt", FS_READ);

    char toSend[512];
    int n;
    while (n = FSfread(toSend, 1, 512, openFile)) {
        Uart2SendBytes(toSend, n);
    }
    FSfclose(openFile);

    // turn on amber LED
    TRISAbits.TRISA4 = 0;
    LATAbits.LATA4 = 1;
    
    while (1);
}
void sdCardTest() {
    FSFILE * pointer;
    char sendBuffer[] = "This is test string 1";

    // Wait in while loop until the physical media device like SD card, CF card or
    // USB memory device is detected in the software...
    while (!MDD_SDSPI_MediaDetect());
    // Initialize the file system library & the physical media device
    while (!FSInit());
    // Create a file
    pointer = FSfopen ("FILE1.TXT", "w");
    if (pointer == NULL)
    while(1);
    // Write 21 1-byte objects from sendBuffer into the file
    if (FSfwrite (sendBuffer, 1, 21, pointer) != 21)
    while(1);
    // Close the file
    if (FSfclose (pointer))
    while(1);

}
Exemple #14
0
void vdoa_test(void)
{
    uint8_t *buffer = malloc(IMG_WIDTH * IMG_HEIGHT * 1.5 + 0x1000);
	/*the VDOA file is extracted from VPU decoder in tiled frame mode*/
	uint8_t readfile[] = "vdoa_in.yuv";
    int count, err;
    int fin = 0;

    if (buffer == NULL)
        return;

    hdmi_1080P60_video_output(1, 0);
    if (FSInit(NULL, bufy, maxdevices, maxhandles, maxcaches) != SUCCESS) {
        err = -1;
        return;
    }

    FSDriveInit(DeviceNum);
    SetCWDHandle(DeviceNum);

    print_media_fat_info(DeviceNum);

    if ((fin = Fopen(readfile, (uint8_t *) "r")) < 0) {
        printf("cannot open file %s!\n", readfile);
        return;
    }

    buffer = (uint8_t *) (((uint32_t) buffer + 0xFFF) & 0xFFFFF000);

    set_card_access_mode(1, 0);
    
    count = Fread(fin, (uint8_t *) buffer, IMG_WIDTH * IMG_HEIGHT * 1.5);

    vdoa_clear_interrupt();
    vdoa_setup(IMG_WIDTH, IMG_HEIGHT, IMG_WIDTH, IMG_WIDTH, 0, 0, 16, 0);
    vdoa_start((uint32_t) buffer, IMG_WIDTH * IMG_HEIGHT, IPU2_CH23_EBA0, IMG_WIDTH * 1088);

    while (!vdoa_check_tx_eot()) ;
    Fclose(fin);
}
Exemple #15
0
//**************************************************************************************
//*** asCARD_Mount
//***
//*** 
//**************************************************************************************
int asCARD_Mount()
{
	// changed default behaviour
/*
	if(asCARD_Detect())
	{
*/		
		if(FSInit())
		{
			gCardState|=CARD_MOUNTED;
			return 1;
		}
		else
		{
			gCardState&=~CARD_MOUNTED;
			return 0;
		}
/*		
	}
	else
		return 0;
*/	
}
Exemple #16
0
uint8_t fsmanMountSD(uint8_t * result_code){
    
    uint8_t ret=0;
    
    MEDIA_INFORMATION  *mediainfo = MDD_MediaInitialize();
    
    if(mediainfo->errorCode != MEDIA_NO_ERROR){
        __debug("MDD media init failed");
    }
    
    if(MDD_MediaDetect() == 0){
        __debug("MDD media detect failed");
        return 0;
    }
    
    if(FSInit() == 0){
        __debug("FSInit failed");
        return 0;
    }

    return 1;
       
}
Exemple #17
0
/*=====================================================================================================================
 * Parameters: void
 *
 * Return: void
 *
 * Description: 
 *===================================================================================================================*/
void FSIO_Task(void)
{
    switch(CardState)
    {
    //------------------------------------------------------------------------------------------------------------------
    case cInitState:
         OSStartTimer(&CardInitTimer);
         CardState = eCardWaitState;
         _DioWritePin(cDioPin_SD_CardLed, 1);
        break;
    //------------------------------------------------------------------------------------------------------------------
    case eCardInitialize:
        // card is inserted, initialize card
        if(cFalse != MDD_MediaDetect())
        {
            if (cFalse != FSInit())
            {
                // init OK
                _set_sd_card_present(1);
                _DioWritePin(cDioPin_SD_CardLed, 0);
                // load device configuration
                Devconfig_LoadConfig();
                App_Statemachine_SD_CardCallback(cCallbackCtrlOK);

                CardState = eCardInserted;
            }
            else
            {
                // init error
                _set_sd_card_present(0);
                _DioWritePin(cDioPin_SD_CardLed, 1);

                CardState = eCardNotPresent;
            }
        }
        else
        {
            _set_sd_card_present(0);
            CardState = eCardNotPresent;
        }
        break;
    //-----------------------------------------------------------------------------------------------------------------
    case eCardInserted:
        if(cDioCardInsertsed != _DioReadPinFiltered(cDioPin_SD_CardPresent))
        {
            _set_sd_card_present(0);
            _DioWritePin(cDioPin_SD_CardLed, 1);
            App_Statemachine_SD_CardCallback(cCallbackCtrlNOK);

            CardState = eCardNotPresent;
        }
        break;
    //-------------------------------------------------------------------------------------------------------------------
    case eCardNotPresent:
        // wait card inserted
        if(cDioCardInsertsed == _DioReadPinFiltered(cDioPin_SD_CardPresent))
        {
            CardState = eCardInitialize;
        }
        break;
    //------------------------------------------------------------------------------------------------------------------
    case eCardWaitState:
        if(cFalse != OSIsTimerElapsed(&CardInitTimer, cFSIO_DioInitTime_ms/(cOsTimerTickUs/1000UL)))
        {
            // wait some time before start polling card state
            CardState = eCardNotPresent;
        }
        break;
    //-------------------------------------------------------------------------------------------------------------------
    default:
        _assert(cFalse);
        CardState = eCardNotPresent;
        break;
    }
}
Exemple #18
0
void _start() 
{
    /* Load a good stack */
    asm(
        "lis %r1, 0x1ab5 ;"
        "ori %r1, %r1, 0xd138 ;"
    );

	/* Get a handle to coreinit.rpl */
	uint32_t coreinit_h;
	OSDynLoad_Acquire("coreinit.rpl", &coreinit_h);

	/* Memory allocation and FS functions */
	void* (*OSAllocFromSystem)(uint32_t size, int align);
	int (*FSInit)();
	int (*FSAddClient)(void *client, int unk1);
	int (*FSInitCmdBlock)(void *cmd);
	int (*FSOpenDir)(void *client, void *cmd, char *path, uint32_t *dir_handle, int unk1);
	int (*FSReadDir)(void *client, void *cmd, uint32_t dir_handle, void *buffer, int unk1);
	
	int (*FSGetMountSource)(void *client, void *cmd, int type, mount_source *source, int unk1);
	int (*FSMount)(void *client, void *cmd, mount_source *source, char *mountpath, uint32_t pathlength, int unk1);
	int (*FSOpenFile)(void *client, void *cmd, char *filepath, char *amode, uint32_t *file_handle, int unk1);
	int (*FSReadFile)(void *client, void *cmd, void *buffer, uint32_t size, uint32_t length, uint32_t file_handle, int unk1, int unk2);

	OSDynLoad_FindExport(coreinit_h, 0, "OSAllocFromSystem", &OSAllocFromSystem);
	OSDynLoad_FindExport(coreinit_h, 0, "FSInit", &FSInit);
	OSDynLoad_FindExport(coreinit_h, 0, "FSAddClient", &FSAddClient);
	OSDynLoad_FindExport(coreinit_h, 0, "FSInitCmdBlock", &FSInitCmdBlock);
	OSDynLoad_FindExport(coreinit_h, 0, "FSOpenDir", &FSOpenDir);
	OSDynLoad_FindExport(coreinit_h, 0, "FSReadDir", &FSReadDir);

	OSDynLoad_FindExport(coreinit_h, 0, "FSGetMountSource", &FSGetMountSource);
	OSDynLoad_FindExport(coreinit_h, 0, "FSMount", &FSMount);
	OSDynLoad_FindExport(coreinit_h, 0, "FSOpenFile", &FSOpenFile);
	OSDynLoad_FindExport(coreinit_h, 0, "FSReadFile", &FSReadFile);

	FSInit();

	/* Set up the client and command blocks */
	void *client = OSAllocFromSystem(0x1700, 0x20);
	void *cmd = OSAllocFromSystem(0xA80, 0x20);
	if (!(client && cmd)) OSFatal("Failed to allocate client and command block");

	FSAddClient(client, 0);
	FSInitCmdBlock(cmd);

	// todo: check permissions and throw exception if no mounting permissions available

	// OSLockMutex - Probably not. It's a single thread, nothing else can access this, Cross-F does this here
	mount_source m_source; // allocate mount source

	int ms_result = FSGetMountSource(client, cmd, 0, &m_source, 0); // type 0 = external device

	if(ms_result != 0) {
		char buf[256];
		__os_snprintf(buf, 256, "FSGetMountSource returned error code %d", ms_result);
		OSFatal(buf);
	}

	char mountPath[128]; // usually /vol/external01
	int m_result = FSMount(client, cmd, &m_source, mountPath, sizeof(mountPath), -1); 

	if(m_result != 0) {
		char buf[256];
		__os_snprintf(buf, 256, "FSMount returned error code %d", m_result);
		OSFatal(buf);
	}
	// OSUnlockMutex

	char defaultMountPath[] = "/vol/external01";

	if(!strcmp(mountPath, defaultMountPath)) {
		char buf[256];
		__os_snprintf(buf, 256, "FSMount returned nonstandard mount path: %s", mountPath);
		OSFatal(buf);
	}

	uint32_t file_handle;
	int open_result = FSOpenFile(client, cmd, "/vol/external01/SMASHD.txt", "r", &file_handle, 0);

	if(open_result != 0) {
		char buf[256];
		__os_snprintf(buf, 256, "FSOpenFile returned error code %d", open_result);
		OSFatal(buf);
	}

	uint32_t *file_buffer = OSAllocFromSystem(0x200, 0x20);
	int read_result = FSReadFile(client, cmd, file_buffer, 1, 25, file_handle, 0, -1); // todo: is size correct? one char one byte; read whole file, not just a few bytes

	if(read_result != 0) {
		char buf[256];
		__os_snprintf(buf, 256, "FSReadFile returned error code %d", read_result);
		OSFatal(buf);
	}

	char *message = (char*)&file_buffer[25];
	OSFatal(message);
}
/*
*************************************************************************
* FUNCTION NAME : voLoggerTask
*
* DESCRIPTION : Handles the temperatur logging to sd card.
*
* INPUT : None
*
* OUTPUT : None
*
* NOTE :
*
*************************************************************************
*/
void voLoggerTask(void)
{
    static enLoggerStateType senLoggerState= INIT;
    static enLoggerStateType senLoggerPrevState= INIT;
    static FSFILE *sLogFilePtr = NULL;
    static s8 ss8CurrentTMP=0;
    CETYPE errorCode;




    switch (senLoggerState)
    {
    /*
     * Init the sd card, goes to wait for card if no card is in socket.
     * if error ocured goes to error state, this is not implemented yet!
     */
    case INIT:



        if (CARD_AVAILIBLE)
        {
            if (FSInit())
                senLoggerState = DELAYINIT;
            else
                senLoggerState = ERROR;
        }
        else
        {
            senLoggerPrevState = senLoggerState;
            senLoggerState = WAIT_FOR_CARD;
        }


        break;
    /*
     * Load delay and goes to wait1sec state.
     */
    case DELAYINIT:

        DISABLE_INTERRUPTS(mu16LoggerDelay = ONE_SEC_DELAY );
        senLoggerState = WAIT1S;

        break;
    /*
     * delay for 1 sec.
     */
    case WAIT1S:

        if (!mu16LoggerDelay)
            senLoggerState = STARTAD;

        break;

    /*
     * Start ADC sampling
     */
    case STARTAD:

        AD1CHS = TMP_S;
        AD1CON1bits.SAMP = 1;

        senLoggerState = BUSYAD;
        break;

    /*
     * Wait until sampling is completed.
     */
    case BUSYAD:

        if (AD1CON1bits.DONE)
            senLoggerState = STORE;
        break;

    /*
     * Rechecks that the sd card is in the socket, if so the adc value is
     * first run thrue a recursive filther then converted to degrees,
     * and added to sd card.
     */
    case STORE:

        if (CARD_AVAILIBLE)
        {
            ss8CurrentTMP = ((u32)330*u16RecursiveFilther() - 51200)/1024;

            sLogFilePtr = FSfopen(LOG_FILENAME,APPEND);

            if (sLogFilePtr != NULL)
            {
                FSfprintf(sLogFilePtr,"%x-%x-%x %x:%x:%x    %d \r\n",
                          munTime.u8Year,
                          munTime.u8Month,
                          munTime.u8Day,
                          munTime.u8Hr,
                          munTime.u8Min,
                          munTime.u8Sec,
                          ss8CurrentTMP);

                if (FSfclose(sLogFilePtr) < 0)
                    senLoggerState = ERROR;
                else
                    senLoggerState = DELAYINIT;
            }
            else
                senLoggerState = ERROR;
        }
        else
        {
            senLoggerPrevState = senLoggerState;
            senLoggerState = WAIT_FOR_CARD;
        }


        break;
    /*
     * error handling should be inplemented here #todo
    */
    case ERROR:

        errorCode = FSerror();



        senLoggerState = INIT;

        break;

    case WAIT_FOR_CARD:

        if (CARD_AVAILIBLE)
            senLoggerState = INIT;


        break;

    default:

        senLoggerState = INIT;

        break;

    }
}
Exemple #20
0
int main (void)
{

    FSFILE * pointer;
    char path[30];
    char count = 30;
    char * pointer2;
    int gh;
    BYTE write_array[512];
    for(gh=0; gh<512; gh++)
        if(gh%8)
            write_array[gh]='a';
        else
            write_array[gh]='b';
    DWORD first_sector;
    BYTE test_array[512];
    /* OFB_init();
     OFB_push(write_array);
     calc_checksum(write_array);
     while(1);*/
    SearchRec rec;
    pointer=NULL;
    unsigned char attributes;
    unsigned char size = 0, i;
    PLLFBD =38;
    CLKDIVbits.PLLPOST=0;
    CLKDIVbits.PLLPRE=0;
    __builtin_write_OSCCONH(0b011);
    __builtin_write_OSCCONL(0b01);
    while (OSCCONbits.COSC != 0b011);	// Wait for Clock switch to occur
    while(OSCCONbits.LOCK != 1) {};
    UART2Init();
    //printf("stuipd thing");
    //TRISD=0x0FF;
    //setting up pins to show on usb debugger
    TRISDbits.TRISD6=1;
    TRISAbits.TRISA7=0;
    TRISAbits.TRISA6=0;
    TRISAbits.TRISA5=0;
    TRISAbits.TRISA4=0;
    //LATA=1;
    //_LATA4=1;
    //_RA7=1;
    //_LATA6=1;

    //_LATA5=1;
    //_LATA7=1;

    //printf("they should be on now");
    //while(1);
    //LATAbits.LATA7=0;
    //TRISB=0xFFFF;
    //AD1PCFGLbits.PCFG1=1;

#ifdef TESTOVERFLOWBUFFER
#ifdef __DEBUG
    printf("Starting test of overflow buffer");

    unsigned char ofbtestin[SECTORSIZE];
    unsigned char ofbtestout[SECTORSIZE];
    OFB_init();
    int ofbi,ofbj,ofbk,result;
    char num=0;
    printf("Starting insertion test\r\n");
    for(ofbj=0; ofbj<=OVERFLOWBUFFERDEPTH; ofbj++)
    {
        for(ofbi=0; ofbi<SECTORSIZE; ofbi++)
            ofbtestin[ofbi]=num+48;
        printf("Size of Buffer: %d\r\n",OFB_getSize());
        printf("Result of Insertion: %d\r\n",OFB_push(ofbtestin));
        printf("New Size: %d\r\n",OFB_getSize());
        num++;
    }
    printf("Starting retrieval test\r\n");
    for(ofbj=0; ofbj<=OVERFLOWBUFFERDEPTH; ofbj++)
    {
        printf("Size of Buffer: %d\r\n",OFB_getSize());
        result=OFB_read_tail(ofbtestout);
        printf("result of read: %d\r\n",result);
        printf("343rd entry in array: %c\r\n",ofbtestout[342]);
        /*for(i=0;i<SECTORSIZE;i++)
        {
        	printf("%d",ofbtestout[i]);
        	while(UART2IsEmpty());
        }*/
        //printf("\r\n");
        result=OFB_pop();
        printf("Result of Pop: %d\r\n",result);
    }
    while(1);
#endif
#endif

    //Service_Spi();
#ifdef __DEBUG
    printf("Clock Switch Complete, Waiting For Media\r\n");
#endif
    //waits for a card to be inserted
    while (!MDD_MediaDetect());


#ifdef __DEBUG
    printf("Media Found, Waiting for FSinit\r\n");
#endif
    // Initialize the library
    while (!FSInit());
    char temp;
    int character_count,remove_success;
    character_count=0;
    // Create a file
    printf("starting up\r\n");
    remove_success=FSremove("WRITE.TXT");
    printf("Removal of prev: %d\r\n",remove_success);
    pointer = FSfopen ("WRITE.TXT", "w");

    if (pointer == NULL)
    {
#ifdef __DEBUG
        printf("File open failed\r\n");
#endif
        while(1);
    }
    //FSfseek(pointer,0,SEEK_SET);
    //set_First_Sector(first_sector);
    //FSfwrite("greetings",1,9,pointer);
    printf("waiting for operation\r\n");
    //FSfwrite("greetings",1,9,pointer);
    //allocate_size(38769,pointer);
    DWORD sizeinbytes;
    //need to convert from number of sectors to number of bytes and allocate that much space
    sizeinbytes=(DWORD)FILESIZE*(DWORD)512;
    //sizeinbytes=3774873*(DWORD)512;
    allocate_size(sizeinbytes,pointer,FALSE);
    FSfseek(pointer,0,SEEK_SET);
    first_sector=get_First_Sector(pointer);
    set_First_Sector(first_sector);
    DWORD erasure;
    OFB_init();
    for(erasure=0; erasure<FILESIZE; erasure++)
    {
        MDD_SDSPI_SectorWrite(first_sector, write_array,FALSE);
        first_sector++;
        if(erasure%100==0)
            printf("%lu\r",erasure);
    }
    int bleh;

    FSfclose(pointer);
    //MDD_ShutdownMedia();
    printf("done with file allocation\r\n");
#ifdef DMAON
#else
#endif

    //while(UART2IsEmpty());
    //temp=UART2GetChar();
    //write_array[character_count]=temp;
    //character_count++;
    while(1)
    {
        Service_Spi();
    }
    /*while(temp!='+')
    {
    	if(character_count<512)
    	{
    		if(!UART2IsEmpty())
    		{
    			temp=UART2GetChar();
    			write_array[character_count]=temp;
    			character_count++;
    			//printf("%08d\r",character_count);
    		}
    	}
    	else
    	{
    	FSfwrite(write_array,1,character_count, pointer);
    	character_count=0;
    	}
    }*/
    //FSfwrite(write_array,1,character_count, pointer);
    //FSfwrite(sendBuffer,1,21, pointer);
    unsigned int buffer[512];
    char buffersign;
    //bufferreturn(buffer);
    while(1)
    {
        /*buffersign=bufferreturn(buffer);
        if(buffersign==1)
        {
         //FSfwrite(buffer,1,512,pointer);
        }*/
        if(!PORTDbits.RD6)
        {
            DMA0CONbits.CHEN=0;
            //FSfclose(pointer);
            DMA0CONbits.CHEN=0;
            printf("done with operations\r\n");
            MDD_ShutdownMedia();
            while(1) {}
        }
    }
    while(1);
}
int main (void)
{

   FSFILE * pointer=NULL;
   DWORD first_sector;
   BYTE test_array[512];
   SearchRec rec;
   pointer=NULL;
   unsigned char attributes;
   unsigned char size = 0, i;
   PLLFBD =38;
   CLKDIVbits.PLLPOST=0;
   CLKDIVbits.PLLPRE=0;
   __builtin_write_OSCCONH(0b011);
   __builtin_write_OSCCONL(0b01);
	while (OSCCONbits.COSC != 0b011);	// Wait for Clock switch to occur	
	while(OSCCONbits.LOCK != 1) {};
	UART2Init();
	printf("starting Integration test\r\n");
	//DataEEInit();
	int id=0;
	id=Get_ID_Code();
	printf("ID: %u\r\n",id);
	OFB_init(id);
	Increment_ID_Code();
	#ifdef __DEBUG
		printf("Clock Switch Complete, Waiting For Media\r\n");
	#endif
	//waits for a card to be inserted
   while (!MDD_MediaDetect());
	#ifdef __DEBUG
		printf("Media Found, Waiting for FSinit\r\n");
	#endif
   // Initialize the library
   while (!FSInit());
   char filename[9];
   sprintf(filename,"%05d.bin",id);
   // Create a file
   printf("filename will be: %s\r\n",filename);
   while(pointer==NULL)
   {
   		pointer = FSfopen (filename, "w");
   }
   #ifdef __DEBUG
   	printf("File Has been opened\r\n");
   #endif		
	
	while(1)
	{
		Service_Spi(pointer);
	}	
	//printf("stuipd thing");
	//TRISD=0x0FF;
	//setting up pins to show on usb debugger
	TRISDbits.TRISD6=1;
	TRISAbits.TRISA7=0;
	TRISAbits.TRISA6=0;
	TRISAbits.TRISA5=0;
	TRISAbits.TRISA4=0;
	TRISGbits.TRISG0=0;
	AD1PCFGLbits.PCFG0=1;	
	//LATA=1;
	//_LATA4=1;
	//_RA7=1;
	//_LATA6=1;
	
	//_LATA5=1;
	//_LATA7=1;
	
	//printf("they should be on now");
	//while(1);
	//LATAbits.LATA7=0;
	//TRISB=0xFFFF;
	//AD1PCFGLbits.PCFG1=1;	
	//Service_Spi();
	/*#ifdef __DEBUG
		printf("Clock Switch Complete, Waiting For Media\r\n");
	#endif
	//waits for a card to be inserted
   while (!MDD_MediaDetect());
   
   
	#ifdef __DEBUG
		printf("Media Found, Waiting for FSinit\r\n");
	#endif
   // Initialize the library
   while (!FSInit());
	char temp;
	int character_count,remove_success;
	character_count=0;
   // Create a file
   printf("starting up\r\n");
   remove_success=FSremove("WRITE.TXT");
   printf("Removal of prev: %d\r\n",remove_success);
   pointer = FSfopen ("WRITE.TXT", "w");

   if (pointer == NULL)
   {
	   #ifdef __DEBUG
	   	printf("File open failed\r\n");
	   #endif
      while(1);
   }   

   printf("waiting for operation\r\n");
   printf("in file resize_test\r\n");
   
   
   DWORD sizeinbytes;
   //need to convert from number of sectors to number of bytes and allocate that much space
   sizeinbytes=(DWORD)FILESIZE*(DWORD)512;
   printf("Chew Fat: %lu\r\nChew Fat Sectors: %d\r\n",CHEW_FAT_SIZE,CHEW_FAT_SIZE_IN_SECTORS);
   //sizeinbytes=3774873*(DWORD)512;
   //allocate_size(sizeinbytes,pointer,FALSE);
   //FSfclose(pointer);*/
   /*FILEallocate_multiple_clusters(pointer,24);
   FAT_print_cluster_chain(pointer->cluster, pointer->dsk);
   FILEallocate_multiple_clusters(pointer,24);
   FAT_print_cluster_chain(pointer->cluster, pointer->dsk);
   int numclus,numcount;
   //DWORD clusttemp;
   printf("First CLuster in main: %lu\r\n",get_First_Sector(pointer));
   for (numclus=0;numclus<48;numclus++)
   {
		for(numcount=0;numcount<512;numcount++)
		{
		   test_array[numcount]=numclus+48;
		}
		MDD_SDSPI_SectorWrite(get_First_Sector(pointer)+numclus,test_array,FALSE);
	}*/
   //FILEallocate_multiple_clusters(pointer,24);
   //FILEallocate_multiple_clusters(pointer,24);
   //FILEallocate_multiple_clusters(pointer,CHEW_FAT_SIZE_IN_SECTORS);
   //FSfclose(pointer);
   //FILEallocate_multiple_clusters(pointer,4096);
   //FSfclose(pointer);
   //FILEallocate_multiple_clusters(pointer,1024);
   //FILEallocate_multiple_clusters(pointer,1024);
   
   //FSfseek(pointer,0,SEEK_SET);
   first_sector=get_First_Sector(pointer);
   set_First_Sector(first_sector);
   DWORD erasure;
   OFB_init(0x1f1f);
   //FSfclose(pointer);
   //MDD_ShutdownMedia();
   printf("done with file allocation\r\n");
   #ifdef DMAON
   #else
   #endif
      
      //while(UART2IsEmpty());
      //temp=UART2GetChar();
      //write_array[character_count]=temp;
      //character_count++;
    while(1)
    {
	    Service_Spi(pointer);
	}
}
Exemple #22
0
int Initialize()
{
	char str[100];
	char strl[100];
	char strr[100];
	char tmp[256];
	wchar_t wtmp[256];
	int r;

	preloadStringsA();

	DrawString(BOT_SCREEN, strings[STR_INITIALIZING], FONT_WIDTH, SCREEN_HEIGHT-FONT_HEIGHT, WHITE, BLACK);

	if(FSInit()){
		DrawString(BOT_SCREEN, strings[STR_LOADING], BOT_SCREEN_WIDTH/2, SCREEN_HEIGHT-FONT_HEIGHT, WHITE, BLACK);
	}else{
		DrawString(BOT_SCREEN, strings[STR_FAILED], BOT_SCREEN_WIDTH/2, SCREEN_HEIGHT-FONT_HEIGHT, RED, BLACK);
		return 1;
	}

	LoadFont();
	if (fontLoaded){
		swprintf(wtmp, sizeof(wtmp)/sizeof(wtmp[0]), strings[STR_ERROR_OPENING], fontpath);
		DrawString(BOT_SCREEN, wtmp, FONT_WIDTH, SCREEN_HEIGHT-FONT_HEIGHT*2, RED, BLACK);
	}else{
		preloadStringsU();
	}

	//Console Stuff
	ConsoleSetXY(15, 20);
	ConsoleSetWH(BOT_SCREEN_WIDTH-30, SCREEN_HEIGHT-80);
	ConsoleSetBorderColor(BLUE);
	ConsoleSetTextColor(RGB(0, 141, 197));
	ConsoleSetBackgroundColor(TRANSPARENT);
	ConsoleSetSpecialColor(BLUE);
	ConsoleSetSpacing(2);
	ConsoleSetBorderWidth(3);
	//Check that the data is installed
	f_mkdir("rxTools");
	f_mkdir("rxTools/nand");
	InstallConfigData();
	readCfg();

	if (fontLoaded)
		cfgs[CFG_LANG].val.s = cfgLang;
	r = loadStrings();
	if (r) {
		sprintf(tmp, "%s/%s", langPath, cfgs[CFG_LANG].val.s);
		swprintf(wtmp, sizeof(wtmp)/sizeof(wtmp[0]), strings[STR_ERROR_OPENING], tmp);
		DrawString(BOT_SCREEN, wtmp, FONT_WIDTH, SCREEN_HEIGHT-FONT_HEIGHT*3, RED, BLACK);
	}
	sprintf(str, "/rxTools/Theme/%u/TOP.bin", cfgs[CFG_THEME].val.i);
	sprintf(strl, "/rxTools/Theme/%u/TOPL.bin", cfgs[CFG_THEME].val.i);
	sprintf(strr, "/rxTools/Theme/%u/TOPR.bin", cfgs[CFG_THEME].val.i);
	if (cfgs[CFG_3D].val.i)
		DrawTopSplash(str, strl, strr);
	else
		DrawTopSplash(str, str, str);

	if (!cfgs[CFG_GUI].val.i)
	{
		if(cfgs[CFG_SILENT].val.i)
		{
			sprintf(str, "/rxTools/Theme/%u/boot.bin", cfgs[CFG_THEME].val.i);
			DrawBottomSplash(str);

			for (int i = 0; i < 0x333333 * 2; i++){
				uint32_t pad = GetInput();
				if (pad & BUTTON_R1 && i > 0x333333) goto rxTools_boot;
			}
		}
		else
		{
			ConsoleInit();
			ConsoleSetTitle(strings[STR_AUTOBOOT]);
			print(strings[STR_HOLD_BUTTON_ACTION], strings[STR_BUTTON_R], strings[STR_OPEN_MENU]);
			ConsoleShow();

			for (int i = 0; i < 0x333333 * 6; i++){
				uint32_t pad = GetInput();
				if (pad & BUTTON_R1 && i > 0x333333) goto rxTools_boot;
			}
		}
		rxMode(1);
	}
rxTools_boot:
	sprintf(str, "/rxTools/Theme/%u/TOP.bin", cfgs[CFG_THEME].val.i);
	sprintf(strl, "/rxTools/Theme/%u/TOPL.bin", cfgs[CFG_THEME].val.i);
	sprintf(strr, "/rxTools/Theme/%u/TOPR.bin", cfgs[CFG_THEME].val.i);
	if (cfgs[CFG_3D].val.i)
		DrawTopSplash(str, strl, strr);
	else
		DrawTopSplash(str, str, str);

	return 0;
}
Exemple #23
0
__attribute__((section(".text.start"), noreturn)) void _start()
{
	static const TCHAR fontPath[] = _T("") SYS_PATH "/" FONT_NAME;
	void *fontBuf;
	UINT btr, br;
	int r;
	FIL f;

	// Enable TMIO IRQ
	*(volatile uint32_t *)0x10001000 = 0x00010000;

	preloadStringsA();

	
	if (!FSInit()) {
		DrawString(BOT_SCREEN, strings[STR_FAILED],
			BOT_SCREEN_WIDTH / 2, SCREEN_HEIGHT - FONT_HEIGHT, RED, BLACK);
		while (1);
	}

	
	set_loglevel(ll_info);
	log(ll_info, "Initializing rxTools...");
	

	setConsole();

	fontIsLoaded = 0;
	r = f_open(&f, fontPath, FA_READ);
	if (r == FR_OK) {
		btr = f_size(&f);
		fontBuf = __builtin_alloca(btr);
		r = f_read(&f, fontBuf, btr, &br);
		if (r == FR_OK)
			fontIsLoaded = 1;

		f_close(&f);
		fontaddr = fontBuf;
	}

	if (fontIsLoaded)
		preloadStringsU();
	else
		warn(L"Failed to load " FONT_NAME ": %d\n", r);

	if (getMpInfo() == MPINFO_KTR)
    {
        r = initN3DSKeys();
        if (r != FR_OK) {
            warn(L"Failed to load keys for N3DS\n"
            "  Code: %d\n"
            "  RxMode will not boot. Please\n"
            "  include key_0x16.bin and\n"
            "  key_0x1B.bin at the root of your\n"
            "  SD card.\n", r);
            InputWait();
            goto postinstall;
        }
    }


	install();
	postinstall:
	readCfg();

	log(ll_info, "Done...");

	r = loadStrings();
	if (r)
		warn(L"Failed to load strings: %d\n", r);

	drawTop();

	//Default boot check
	if (cfgs[CFG_DEFAULT].val.i && HID_STATE & BUTTON_L1)
		{
			if(cfgs[CFG_DEFAULT].val.i == 3) PastaMode();
			else rxMode(cfgs[CFG_DEFAULT].val.i - 1);
		}

	if (sysver < 7) {
		r = initKeyX();
		if (r != FR_OK)
			warn(L"Failed to load key X for slot 0x25\n"
				"  Code: %d\n"
				"  If your firmware version is less\n"
				"  than 7.X, some titles decryption\n"
				"  will fail, and some EmuNANDs\n"
				"  will not boot.\n", r);
	}

	if (warned) {
		warn(strings[STR_PRESS_BUTTON_ACTION],
			strings[STR_BUTTON_A], strings[STR_CONTINUE]);
		WaitForButton(BUTTON_A);
	}

	OpenAnimation();
	mainLoop();
}
Exemple #24
0
int main(void)
{
    int  value;
    int junk;
    millisec = 0;
    value = SYSTEMConfigWaitStatesAndPB( GetSystemClock() );

    // Enable the cache for the best performance
    CheKseg0CacheOn();

    //Setupt input for inteface button JF8 (RA01) (0x02)
    TRISASET = 0x02;
    //RED LED - JF9 (RA04)  (0x10)
    TRISACLR = 0x10;
    ODCACLR = 0x10;
    LATASET = 0x10;
    //Green LED -JF7 (RE9)  (0x200)
    TRISECLR = 0x200;
    ODCECLR = 0x200;
    LATESET = 0x200;
    //Setupt Input for DataFlag Button - JF10 - RA5 0x20
    TRISASET = 0x20;
    //Setup Output for Clutch Hold (Launch) JE1 RD14 0x4000
    //This function is active low, driving the FET on the PDU
    TRISDCLR = 0x4000;
    ODCDCLR = 0x4000;
    LATDSET = 0x4000; //Default state is high (off)

    CAN1Init();//CAN1 ACCL 500kbs
    CAN2Init();//Motec 1mbs
    DelayInit();

    initUART2(); // GPS UART
    prevButton1 = 0;
    prevButton2 = 0;
    millisec = 0;

   // Configure Timer 2 to request a real-time interrupt once per millisecond.
   // The period of Timer 2 is (16 * 5000)/(80 MHz) = 1 ms.
   OpenTimer2(T2_ON | T2_IDLE_CON | T2_SOURCE_INT | T2_PS_1_16 | T2_GATE_OFF, 5000);

   // Configure the CPU to respond to Timer 2's interrupt requests.
   INTEnableSystemMultiVectoredInt();
   INTSetVectorPriority(INT_TIMER_2_VECTOR, INT_PRIORITY_LEVEL_2);
   INTClearFlag(INT_T2);
   INTEnable(INT_T2, INT_ENABLED);

   //UART GPS Interrupts
   INTSetVectorPriority(INT_UART_2_VECTOR ,INT_PRIORITY_LEVEL_1); //Make sure UART interrupt is top priority
   INTClearFlag(INT_U2RX);
   INTEnable(INT_U2RX, INT_ENABLED);


    value = OSCCON;
    while (!(value & 0x00000020))
    {
        value = OSCCON;    // Wait for PLL lock to stabilize
    }

    deviceAttached = FALSE;

    //Initialize the stack
    USBInitialize(0);

    shouldLog = FALSE;
    shouldStop = FALSE;
    //count = 0;
    angularRateInfoRec = FALSE;
    accelerationSensorRec = FALSE;
    HRaccelerationSensorRec = FALSE;

       //init tim er 3 to convert adc at 100hz
    OpenTimer3(T3_ON|T3_PS_1_256|T3_SOURCE_INT, 1562);

    //initialize i2c for the psoc
    initI2CPSoC();
    
    state = wait;
    logNum = 0;

    initI2CEEPROM();
    short addy = 0x0000;
    BYTE num = 0x00;
    logNum = readEEPROM(addy);
    if(logNum >= 0xEF)  //Address stored in EEPROM  if greater than 0xEF reset to zero, limited to a single byte with current code configuration
    {
        writeEEPROM(addy, 0x00);
    }
    char GroupString[550];//Group Names (Line1)
    char UnitString[550];//Units (line2)
    char ParamString[650];//Paramater Names (line3)
    sprintf(GroupString,"Time,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Accelerometer,Engine,Engine,Engine,Engine,Engine,Engine,Engine,Engine,Engine,Engine,Drivetrain,Drivetrain,Electrical,Drivetrain,Drivetrain,Drivetrain,Drivetrain,Engine,Engine,Engine,Engine,Electrical,Electrical,Electrical,Electrical,Electrical,Electrical,Suspension,Suspension,Suspension,Suspension,Suspension,Drivetrain,Driver\n");
    sprintf(UnitString,"ms,deg/s,deg/s,deg/s,m/s^2,m/s^2,m/s^2,m/s^2,m/s^2,m/s^2,rpm,%,kpa,degF,degF,lambda,psi,degF,na,na,psi,psi,V,mph,mph,mph,mph,s,gal,degF,degBTDC,mV,mV,mV,mV,mV,mV,mV,mV,mV,mV,mV,mV,\n");
    sprintf(ParamString, "Millisec,pitch(deg/sec),roll(deg/sec),yaw(deg/sec),lat(m/s^2),long(m/s^2),vert(m/s^2),latHR(m/s^2),longHR(m/s^2),vertHR(m/s^2),rpm,tps(percent),MAP(kpa),AT(degF),ect(degF),lambda,fuel pres,egt(degF),launch,neutral,brake pres,brake pres filtered,BattVolt(V),ld speed(mph), lg speed(mph),rd speed(mph),rg speed(mph),run time(s),fuel used,Oil Temp (deg F), Ignition Adv (degBTDC),Overall Consumption(mV),Overall Production(mV),Fuel Pump(mV),Fuel Injector(mV),Ignition(mV),Vref(mV),Back Left(mV),Back Right(mV),Front Left(mV),Front Right(mV),Steering Angle(mV),Brake Temp(mV),Data Flag,GPRMC,Time,Valid,Lat,N/S,Long,E/W,Speed,Course,Date,Variation,E/W\n");

    LATACLR = 0x10; //Turn on Red LED
   // LATECLR = 0x200;

    UARTSendString(UART2,PMTK_HOT_RESTART);
    int i = 0;
    while(!UARTTransmissionHasCompleted(UART2)){
        i++;
    }

    while(1)
    {
        GPSDataRead();
        GPSSentenceParse();
        ClutchHold(); //This function handles the venting direction of the clutch actuator
        DataFlagFunc(); //This function handles the updates of the data flag variable
        //USB stack process function
        USBTasks();

        switch(state){
            case wait:
                USBTasks();
                millisec = 0;
                if(CheckLogStateChange() == 1){ //start the transition from wait to log
                    state = startLog;
                }
                break;
            case startLog:
                //if thumbdrive is plugged in
                if(USBHostMSDSCSIMediaDetect())
                {
                    deviceAttached = TRUE;
                    //now a device is attached
                    //See if the device is attached and in the right format
                    if(FSInit())
                    {
                        //Opening a file in mode "w" will create the file if it doesn't
                        //  exist.  If the file does exist it will delete the old file
                        //  and create a new one that is blank.
                        logNum = readEEPROM(addy);
                        sprintf(nameString, "test%d.csv", logNum);
                        myFile = FSfopen(nameString,"w");
                        FSfwrite(GroupString,1,strlen(GroupString),myFile);
                        FSfwrite(UnitString,1,strlen(UnitString),myFile);
                        FSfwrite(ParamString,1, strlen(ParamString),myFile);
                        millisec = 0;
                        //LATDSET = 0x4000; //Send sync pulse (aeroprobe)
                       // while(millisec < 1000){} //Wait 1s then move to log, the aeroprobe ADC waits 1s.
                            state = log;
                        LATECLR = 0x200; //Turn on Green
                        LATASET = 0x10; //Turn off Red
                    }
                }
                break;
            case log:
                //This uses MOTEC as the master timer.  Data is only written to the USB after all the motec Data is received
                if(motec0Read && motec1Read && motec2Read && motec3Read && motec4Read && motec5Read){
                    WriteToUSB();
                }
                else{}//Wait for motec data to write the next row
                if(CheckLogStateChange() == 2){ //Start the transition from log to wait
                    state = stopLog;
                }
                if(millisec > 2000){
                    LATDCLR = 0x4000; //After 2 seconds pass no need to keep output high
                }
                //Add a function to check for a flag button and set a variable
                break;
            case stopLog:
                //Always make sure to close the file so that the data gets written to the drive.
                FSfwrite("endFile", 1, 7, myFile);
                FSfclose(myFile);
                state = wait;
                logNum++;
                writeEEPROM(addy, logNum);
                LATACLR = 0x10; //Turn on Red
                LATESET = 0x200; //Turn off Green
                break;
            default:
                state = wait;
                break;
        }


        //CAN Handlers
        CANRxMessageBuffer* CAN1RxMessage = CAN1RxMsgProcess();
        if(CAN1RxMessage){
            WriteAccelData(CAN1RxMessage); //Accel is on CAN 1
        }
        CANRxMessageBuffer* CAN2RxMessage = CAN2RxMsgProcess();
        if(CAN2RxMessage){
            writeCan2Msg(CAN2RxMessage); //Motec is on CAN 2
        }
    }
    return 0;
}
Exemple #25
0
int Initialize()
{
	char str[100];
	char strl[100];
	char strr[100];
	char tmp[256];
	wchar_t wtmp[256];
	int r;

	preloadStringsA();

	//Show error if FSInit is not successfull
	if (!FSInit()){
		DrawString(BOT_SCREEN, strings[STR_FAILED], BOT_SCREEN_WIDTH / 2, SCREEN_HEIGHT - FONT_HEIGHT, RED, BLACK);
		return 1;
	}

	/* Set log level here for code debug/trace */
	/*
	set_loglevel(ll_info);
	log(ll_info, "Initializing rxTools...");
	*/

	//Load the font
	LoadFont();
	if (fontLoaded){
		swprintf(wtmp, sizeof(wtmp) / sizeof(wtmp[0]), strings[STR_ERROR_OPENING], fontpath);
		DrawString(BOT_SCREEN, wtmp, FONT_WIDTH, SCREEN_HEIGHT - FONT_HEIGHT * 2, RED, BLACK);
	}
	else{
		preloadStringsU();
	}

	//Console Stuff
	ConsoleSetXY(15, 20);
	ConsoleSetWH(BOT_SCREEN_WIDTH - 30, SCREEN_HEIGHT - 80);
	ConsoleSetBorderColor(BLUE);
	ConsoleSetTextColor(RGB(0, 141, 197));
	ConsoleSetBackgroundColor(TRANSPARENT);
	ConsoleSetSpecialColor(BLUE);
	ConsoleSetSpacing(2);
	ConsoleSetBorderWidth(3);
	//Check that the data is installed
	f_mkdir("rxTools");
	f_mkdir("rxTools/nand");
	InstallConfigData();
	readCfg();

	//Load strings
	if (fontLoaded)
		cfgs[CFG_LANG].val.s = cfgLang;
	r = loadStrings();
	if (r) {
		sprintf(tmp, "%s/%s", langPath, cfgs[CFG_LANG].val.s);
		swprintf(wtmp, sizeof(wtmp) / sizeof(wtmp[0]), strings[STR_ERROR_OPENING], tmp);
		DrawString(BOT_SCREEN, wtmp, FONT_WIDTH, SCREEN_HEIGHT - FONT_HEIGHT * 3, RED, BLACK);
	}

	//Draw the top screen splash
	sprintf(str, "/rxTools/Theme/%u/TOP.bin", cfgs[CFG_THEME].val.i);
	sprintf(strl, "/rxTools/Theme/%u/TOPL.bin", cfgs[CFG_THEME].val.i);
	sprintf(strr, "/rxTools/Theme/%u/TOPR.bin", cfgs[CFG_THEME].val.i);
	if (cfgs[CFG_3D].val.i)
		DrawTopSplash(str, strl, strr);
	else
		DrawTopSplash(str, str, str);

	//If the GUI is not forced, show it only if L is hold, else directly boot rxMode (sys or emu)
	if (!cfgs[CFG_GUI].val.i)
	{
		if ((~HID_STATE) & BUTTON_L1) return 0;

		if (cfgs[CFG_ABSYSN].val.i) rxMode(0);
		else rxMode(1);
	}

	return 0; //Boot rxTools menu
}
Exemple #26
0
/* *****************************************************************************
 * Dynamic RPL loading to memory
 * ****************************************************************************/
static int LoadRPLToMemory(s_rpx_rpl *rpl_entry)
{
    if ((int)bss_ptr != 0x0a000000)
    {
        char buffer[200];
        __os_snprintf(buffer, sizeof(buffer), "CheckAndLoadRPL(%s) found and loading", rpl_entry->name);
        log_string(bss.global_sock, buffer, BYTE_LOG_STR);
    }

    // initialize FS
    FSInit();
    FSClient *pClient = (FSClient*) MEMAllocFromDefaultHeap(sizeof(FSClient));
    if (!pClient)
        return 0;

    FSCmdBlock *pCmd = (FSCmdBlock*) MEMAllocFromDefaultHeap(sizeof(FSCmdBlock));
    if (!pCmd)
    {
        MEMFreeToDefaultHeap(pClient);
        return 0;
    }

    // calculate path length for SD access of RPL
    int path_len = strlen(CAFE_OS_SD_PATH) + strlen(SD_GAMES_PATH) + strlen(GAME_DIR_NAME) + strlen(RPX_RPL_PATH) + strlen(rpl_entry->name) + 3;
    char *path_rpl = MEMAllocFromDefaultHeap(path_len);
    if(!path_rpl) {
        MEMFreeToDefaultHeap(pCmd);
        MEMFreeToDefaultHeap(pClient);
        return 0;
    }
    // create path
    __os_snprintf(path_rpl, path_len, "%s%s/%s%s/%s", CAFE_OS_SD_PATH, SD_GAMES_PATH, GAME_DIR_NAME, RPX_RPL_PATH, rpl_entry->name);

    // malloc mem for read file
    unsigned char* dataBuf = (unsigned char*)MEMAllocFromDefaultHeapEx(0x1000, 0x40);
    if(!dataBuf) {
        MEMFreeToDefaultHeap(pCmd);
        MEMFreeToDefaultHeap(pClient);
        MEMFreeToDefaultHeap(path_rpl);
        return 0;
    }

    // do more initial FS stuff
    FSInitCmdBlock(pCmd);
    FSAddClientEx(pClient, 0, FS_RET_NO_ERROR);

    // set RPL size to 0 to avoid wrong RPL being loaded when opening file fails
    rpl_entry->size = 0;
    rpl_entry->offset = 0;

    int fd = 0;
    if (real_FSOpenFile(pClient, pCmd, path_rpl, "r", &fd, FS_RET_ALL_ERROR) == FS_STATUS_OK)
    {
        int ret;
        int rpl_size = 0;

        // Get current memory area
        s_mem_area* mem_area    = (s_mem_area*)(MEM_AREA_ARRAY);
        int mem_area_addr_start = mem_area->address;
        int mem_area_addr_end   = mem_area->address + mem_area->size;
        int mem_area_offset     = 0;

        // Copy rpl in memory
        while ((ret = FSReadFile(pClient, pCmd, dataBuf, 0x1, 0x1000, fd, 0, FS_RET_ALL_ERROR)) > 0)
        {
            // Copy in memory and save offset
            for (int j = 0; j < ret; j++)
            {
                if ((mem_area_addr_start + mem_area_offset) >= mem_area_addr_end)
                {
                    // Set next memory area
                    mem_area            = mem_area->next;
                    mem_area_addr_start = mem_area->address;
                    mem_area_addr_end   = mem_area->address + mem_area->size;
                    mem_area_offset     = 0;
                }
                *(volatile unsigned char*)(mem_area_addr_start + mem_area_offset) = dataBuf[j];
                mem_area_offset += 1;
            }
            rpl_size += ret;
        }

        // Fill rpl entry
        rpl_entry->area = (s_mem_area*)(MEM_AREA_ARRAY);
        rpl_entry->offset = 0;
        rpl_entry->size = rpl_size;

        // flush memory
        // DCFlushRange((void*)rpl_entry, sizeof(s_rpx_rpl));
        // DCFlushRange((void*)rpl_entry->address, rpl_entry->size);

        if ((int)bss_ptr != 0x0a000000)
        {
            char buffer[200];
            __os_snprintf(buffer, sizeof(buffer), "CheckAndLoadRPL(%s) file loaded 0x%08X %i", rpl_entry->name, rpl_entry->area->address, rpl_entry->size);
            log_string(bss.global_sock, buffer, BYTE_LOG_STR);
        }

        FSCloseFile(pClient, pCmd, fd, FS_RET_NO_ERROR);
    }

    FSDelClient(pClient);
    MEMFreeToDefaultHeap(dataBuf);
    MEMFreeToDefaultHeap(pCmd);
    MEMFreeToDefaultHeap(pClient);
    MEMFreeToDefaultHeap(path_rpl);
    return 1;
}
Exemple #27
0
__attribute__((section(".text.start"), noreturn)) void _start()
{
	static const TCHAR fontPath[] = _T("") SYS_PATH "/" FONT_NAME;
	void *fontBuf;
	UINT btr, br;
	int r;
	FIL f;

	// Enable TMIO IRQ
	*(volatile uint32_t *)0x10001000 = 0x00010000;

	preloadStringsA();

	if (!FSInit()) {
		DrawString(BOT_SCREEN, strings[STR_FAILED],
			BOT_SCREEN_WIDTH / 2, SCREEN_HEIGHT - FONT_HEIGHT, RED, BLACK);
		while (1);
	}

	/*
	set_loglevel(ll_info);
	log(ll_info, "Initializing rxTools...");
	*/

	setConsole();

	fontIsLoaded = 0;
	r = f_open(&f, fontPath, FA_READ);
	if (r == FR_OK) {
		btr = f_size(&f);
		fontBuf = __builtin_alloca(btr);
		r = f_read(&f, fontBuf, btr, &br);
		if (r == FR_OK)
			fontIsLoaded = 1;

		f_close(&f);
		fontaddr = fontBuf;
	}

	if (fontIsLoaded)
		preloadStringsU();
	else
		warn(L"Failed to load " FONT_NAME ": %d\n", r);

	install();
	readCfg();

	r = loadStrings();
	if (r)
		warn(L"Failed to load strings: %d\n", r);

	drawTop();

	if (!cfgs[CFG_GUI].val.i && HID_STATE & BUTTON_L1)
		rxMode(cfgs[CFG_ABSYSN].val.i ? 0 : 1);

	if (sysver < 7) {
		r = initKeyX();
		if (r != FR_OK)
			warn(L"Failed to load key X for slot 0x25\n"
				"  Code: %d\n"
				"  If your firmware version is less\n"
				"  than 7.X, some titles decryption\n"
				"  will fail, and some EmuNANDs\n"
				"  will not boot.\n", r);
	}

	if (warned) {
		warn(strings[STR_PRESS_BUTTON_ACTION],
			strings[STR_BUTTON_A], strings[STR_CONTINUE]);
		WaitForButton(BUTTON_A);
	}

	OpenAnimation();
	MenuInit(&MainMenu);
	MenuShow();
	mainLoop();
}
int main (void)
{
   FSFILE * pointer;
   #if defined(SUPPORT_LFN)
   char count = 80;
   #endif
   char * pointer2;
   SearchRec rec;
   unsigned char attributes;
   unsigned char size = 0, i;

    // Initialize and configure Primary PLL, and enabled Secondary Oscillator
    PLLFBD = 58;			/* M  = 60	*/
    CLKDIVbits.PLLPOST = 0;	/* N1 = 2	*/
    CLKDIVbits.PLLPRE = 0;	/* N2 = 2	*/
    OSCTUN = 0;
    __builtin_write_OSCCONH(0x03);		
    __builtin_write_OSCCONL(0x03);
    while (OSCCONbits.COSC != 0x3); 
    while (_LOCK == 0);

   // Activate the RTCC module
   __builtin_write_RTCWEN();
   Nop();
   Nop();
   RCFGCALbits.RTCPTR0 = 1;
   RCFGCALbits.RTCPTR1 = 1;
   
   // Set it to the correct time
   // These values won't be accurate
   RTCVAL = 0x0011;   
   RTCVAL = 0x0815;
   RTCVAL = 0x0108;
   RTCVAL = 0x2137;
   RCFGCAL = 0x8000;

   while (!MDD_MediaDetect());

   // Initialize the library
   while (!FSInit());

#ifdef ALLOW_WRITES
   // Create a file
   pointer = FSfopen ("FILE1.TXT", "w");
   if (pointer == NULL)
      while(1);

   // Write 21 1-byte objects from sendBuffer into the file
   if (FSfwrite (sendBuffer, 1, 21, pointer) != 21)
      while(1);

   // FSftell returns the file's current position
   if (FSftell (pointer) != 21)
      while(1);

   // FSfseek sets the position one byte before the end
   // It can also set the position of a file forward from the
   // beginning or forward from the current position
   if (FSfseek(pointer, 1, SEEK_END))
      while(1);

   // Write a 2 at the end of the string
   if (FSfwrite (send2, 1, 1, pointer) != 1)
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);

   // Create a second file
   pointer = FSfopen ("Microchip File 1.TXT", "w");
   if (pointer == NULL)
      while(1);

   // Write the string to it again
   if (FSfwrite ((void *)sendBuffer, 1, 21, pointer) != 21)
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);
#endif

   // Open file 1 in read mode
   pointer = FSfopen ("FILE1.TXT", "r");
   if (pointer == NULL)
      while(1);

   if (FSrename ("Microchip File 2.TXT", pointer))
      while(1);

   // Read one four-byte object
   if (FSfread (receiveBuffer, 4, 1, pointer) != 1)
      while(1);

   // Check if this is the end of the file- it shouldn't be
   if (FSfeof (pointer))
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);

   // Make sure we read correctly
   if ((receiveBuffer[0] != 'T') ||
         (receiveBuffer[1] != 'h')  ||
         (receiveBuffer[2] != 'i')  ||
         (receiveBuffer[3] != 's'))
   {
      while(1);
   }

#ifdef ALLOW_DIRS
   // Create a small directory tree
   // Beginning the path string with a '.' will create the tree in
   // the current directory.  Beginning with a '..' would create the
   // tree in the previous directory.  Beginning with just a '\' would
   // create the tree in the root directory.  Beginning with a dir name
   // would also create the tree in the current directory
   if (FSmkdir (".\\Mchp Directory 1\\Dir2\\Directory 3"))
      while(1);

   // Change to 'Directory 3' in our new tree
   if (FSchdir ("Mchp Directory 1\\Dir2\\Directory 3"))
      while(1);

   // Create another tree in 'Directory 3'
   if (FSmkdir ("Directory 4\\Directory 5\\Directory 6"))
      while(1);

   // Create a third file in directory THREE
   pointer = FSfopen ("CWD.TXT", "w");
   if (pointer == NULL)
      while(1);

   #if defined(SUPPORT_LFN)
   // Get the name of the current working directory
   /* it should be "\Mchp Directory 1\Dir2\Directory 3" */
   pointer2 = wFSgetcwd ((unsigned short int *)path1, count);
   #endif

   if (pointer2 != path1)
      while(1);

   // Simple string length calculation
   i = 0;
   while(*((unsigned short int *)path1 + i) != 0x00)
   {
      size++;
      size++;
      i++;
   }
   // Write the name to CWD.TXT
   if (FSfwrite (path1, size, 1, pointer) != 1)
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);

   // Create some more directories
   if (FSmkdir ("Directory 4\\Directory 5\\Directory 7\\..\\Directory 8\\..\\..\\DIRNINE\\Directory 10\\..\\Directory 11\\..\\Directory 12"))
      while(1);

   /*******************************************************************
      Now our tree looks like this

 \ -> Mchp Directory 1 -> Dir2 -> Directory 3 -> Directory 4 -> Directory 5 -> Directory 6
                                                                                 -> Directory 7
                                                                                 -> Directory 8

                                                                    DIRNINE -> Directory 10
                                                                            -> Directory 11
                                                                            -> Directory 12
   ********************************************************************/

   // This will delete only Directory 8
   // If we tried to delete Directory 5 with this call, the FSrmdir
   // function would return -1, since Directory 5 is non-empty
   if (FSrmdir ("\\Mchp Directory 1\\Dir2\\Directory 3\\Directory 4\\Directory 5\\Directory 8", FALSE))
      while(1);

   // This will delete DIRNINE and all three of its sub-directories
   if (FSrmdir ("Directory 4\\DIRNINE", TRUE))
      while(1);

   // Change directory to the root dir
   if (FSchdir ("\\"))
      while(1);
#endif

#ifdef ALLOW_FILESEARCH
   // Set attributes
   attributes = ATTR_ARCHIVE | ATTR_READ_ONLY | ATTR_HIDDEN;

   // Functions "FindFirst" & "FindNext" can be used to find files
   // and directories with required attributes in the current working directory.

   // Find the first TXT file with any (or none) of those attributes that
   // has a name beginning with the letters "Mic"
   // These functions are more useful for finding out which files are
   // in your current working directory
   if (FindFirst ("Mic*.TXT", attributes, &rec))
      while(1);

 //   Find file to get "Microchip File 2.TXT"
      if (FindNext (&rec))
         while(1);

   #if defined(SUPPORT_LFN) 
  // Delete file 2
   // If the file name is long
   if(rec.utf16LFNfoundLength)
   {
      // NOTE : "wFSremove" function deletes specific file not directory.
      //        To delete directories use "wFSrmdir" function
      if (wFSremove (rec.utf16LFNfound))
         while(1);
   }
   else
   #endif
   {
      // NOTE : "FSremove" function deletes specific file not directory.
      //        To delete directories use "FSrmdir" function
      if (FSremove (rec.filename))
         while(1);
   }

#endif


/*********************************************************************
   The final contents of our card should look like this:
   \ -> Microchip File 1.TXT
      -> Mchp Directory 1 -> Dir2 -> Directory 3 -> CWD.TXT
                                                 -> Directory 4 -> Directory 5 -> Directory 6
                                                                               -> Directory 7

*********************************************************************/


   while(1);
}
Exemple #29
0
int main (void)
{
   FSFILE * pointer;
   #if defined(SUPPORT_LFN)
   char count = 80;
   #endif
   char * pointer2;
   SearchRec rec;
   unsigned char attributes;
   unsigned char size = 0, i;

	// Turn on the secondary oscillator
	__asm__ ("MOV #OSCCON,w1");
	__asm__ ("MOV.b #0x02, w0");
	__asm__ ("MOV #0x46, w2");
	__asm__ ("MOV #0x57, w3");
	__asm__ ("MOV.b w2, [w1]");
	__asm__ ("MOV.b w3, [w1]");
	__asm__ ("MOV.b w0, [w1]");

	// Activate the RTCC module
	__asm__ ("mov #NVMKEY,W0");
	__asm__ ("mov #0x55,W1");
	__asm__ ("mov #0xAA,W2");
	__asm__ ("mov W1,[W0]");
	__asm__ ("nop");
	__asm__ ("mov W2,[W0]");
	__asm__ ("bset RCFGCAL,#13");
	__asm__ ("nop");
	__asm__ ("nop");
	RCFGCALbits.RTCPTR0 = 1;
	RCFGCALbits.RTCPTR1 = 1;
	// Set it to the correct time
	// These values won't be accurate
	RTCVAL = 0x0007;   
	RTCVAL = 0x0717;
	RTCVAL = 0x0208;
	RTCVAL = 0x2137;
	RCFGCAL = 0x8000;

	#if defined(__PIC24FJ256DA210__)

		// Make Analog Pins Digital
		ANSB = 0x0000 ; 
		ANSA = 0x0000;
		ANSC = 0x0000;
		ANSD = 0x0000;

		// Enable PLL
		CLKDIVbits.PLLEN = 1; 

		// Configure SPI1 PPS pins (ENC28J60/ENCX24J600/MRF24WB0M or other PICtail Plus cards)
		__builtin_write_OSCCONL(OSCCON & 0xbf); // unlock PPS

		RPOR1bits.RP2R = 8;       // assign RP2 for SCK1
		RPOR0bits.RP1R = 7;       // assign RP1 for SDO1
		RPINR20bits.SDI1R = 0;    // assign RP0 for SDI1

		__builtin_write_OSCCONL(OSCCON | 0x40); // lock   PPS                

	#elif defined(__PIC24FJ256GB110__)

		AD1PCFGL = 0xFFFF;

		//Initialize the SPI
		RPINR20bits.SDI1R = 23;
		RPOR7bits.RP15R = 7;
		RPOR0bits.RP0R = 8;    

		//enable a pull-up for the card detect, just in case the SD-Card isn't attached
		//  then lets have a pull-up to make sure we don't think it is there.
		CNPU5bits.CN68PUE = 1; 

	#endif

   while (!MDD_MediaDetect());

   // Initialize the library
   while (!FSInit());

#ifdef ALLOW_WRITES
   // Create a file
   pointer = FSfopen ("FILE1.TXT", "w");
   if (pointer == NULL)
      while(1);

   // Write 21 1-byte objects from sendBuffer into the file
   if (FSfwrite (sendBuffer, 1, 21, pointer) != 21)
      while(1);

   // FSftell returns the file's current position
   if (FSftell (pointer) != 21)
      while(1);

   // FSfseek sets the position one byte before the end
   // It can also set the position of a file forward from the
   // beginning or forward from the current position
   if (FSfseek(pointer, 1, SEEK_END))
      while(1);

   // Write a 2 at the end of the string
   if (FSfwrite (send2, 1, 1, pointer) != 1)
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);

   // Create a second file
   pointer = FSfopen ("Microchip File 1.TXT", "w");
   if (pointer == NULL)
      while(1);

   // Write the string to it again
   if (FSfwrite ((void *)sendBuffer, 1, 21, pointer) != 21)
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);
#endif

   // Open file 1 in read mode
   pointer = FSfopen ("FILE1.TXT", "r");
   if (pointer == NULL)
      while(1);

   if (FSrename ("Microchip File 2.TXT", pointer))
      while(1);

   // Read one four-byte object
   if (FSfread (receiveBuffer, 4, 1, pointer) != 1)
      while(1);

   // Check if this is the end of the file- it shouldn't be
   if (FSfeof (pointer))
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);

   // Make sure we read correctly
   if ((receiveBuffer[0] != 'T') ||
         (receiveBuffer[1] != 'h')  ||
         (receiveBuffer[2] != 'i')  ||
         (receiveBuffer[3] != 's'))
   {
      while(1);
   }

#ifdef ALLOW_DIRS
   // Create a small directory tree
   // Beginning the path string with a '.' will create the tree in
   // the current directory.  Beginning with a '..' would create the
   // tree in the previous directory.  Beginning with just a '\' would
   // create the tree in the root directory.  Beginning with a dir name
   // would also create the tree in the current directory
   if (FSmkdir (".\\Mchp Directory 1\\Dir2\\Directory 3"))
      while(1);

   // Change to 'Directory 3' in our new tree
   if (FSchdir ("Mchp Directory 1\\Dir2\\Directory 3"))
      while(1);

   // Create another tree in 'Directory 3'
   if (FSmkdir ("Directory 4\\Directory 5\\Directory 6"))
      while(1);

   // Create a third file in directory THREE
   pointer = FSfopen ("CWD.TXT", "w");
   if (pointer == NULL)
      while(1);

   #if defined(SUPPORT_LFN)
   // Get the name of the current working directory
   /* it should be "\Microchip Directory 1\Dir2\Directory 3" */
   pointer2 = wFSgetcwd ((unsigned short int *)path1, count);
   #endif

   if (pointer2 != path1)
      while(1);

   // Simple string length calculation
   i = 0;
   while(*((unsigned short int *)path1 + i) != 0x00)
   {
      size++;
      size++;
      i++;
   }
   // Write the name to CWD.TXT
   if (FSfwrite (path1, size, 1, pointer) != 1)
      while(1);

   // Close the file
   if (FSfclose (pointer))
      while(1);

   // Create some more directories
   if (FSmkdir ("Directory 4\\Directory 5\\Directory 7\\..\\Directory 8\\..\\..\\DIRNINE\\Directory 10\\..\\Directory 11\\..\\Directory 12"))
      while(1);

   /*******************************************************************
      Now our tree looks like this

 \ -> Mchp Directory 1 -> Dir2 -> Directory 3 -> Directory 4 -> Directory 5 -> Directory 6
                                                                                 -> Directory 7
                                                                                 -> Directory 8

                                                                    DIRNINE -> Directory 10
                                                                            -> Directory 11
                                                                            -> Directory 12
   ********************************************************************/

   // This will delete only Directory 8
   // If we tried to delete Directory 5 with this call, the FSrmdir
   // function would return -1, since Directory 5 is non-empty
   if (FSrmdir ("\\Mchp Directory 1\\Dir2\\Directory 3\\Directory 4\\Directory 5\\Directory 8", FALSE))
      while(1);

   // This will delete DIRNINE and all three of its sub-directories
   if (FSrmdir ("Directory 4\\DIRNINE", TRUE))
      while(1);

   // Change directory to the root dir
   if (FSchdir ("\\"))
      while(1);
#endif

#ifdef ALLOW_FILESEARCH
   // Set attributes
   attributes = ATTR_ARCHIVE | ATTR_READ_ONLY | ATTR_HIDDEN;

   // Functions "FindFirst" & "FindNext" can be used to find files
   // and directories with required attributes in the current working directory.

   // Find the first TXT file with any (or none) of those attributes that
   // has a name beginning with the letters "Mic"
   // These functions are more useful for finding out which files are
   // in your current working directory
   if (FindFirst ("Mic*.TXT", attributes, &rec))
      while(1);

 //   Find file to get "Microchip File 2.TXT"
      if (FindNext (&rec))
         while(1);

   #if defined(SUPPORT_LFN) 
  // Delete file 2
   // If the file name is long
   if(rec.utf16LFNfoundLength)
   {
      // NOTE : "wFSremove" function deletes specific file not directory.
      //        To delete directories use "wFSrmdir" function
      if (wFSremove (rec.utf16LFNfound))
         while(1);
   }
   else
   #endif
   {
      // NOTE : "FSremove" function deletes specific file not directory.
      //        To delete directories use "FSrmdir" function
      if (FSremove (rec.filename))
         while(1);
   }

#endif


/*********************************************************************
   The final contents of our card should look like this:
   \ -> Microchip File 1.TXT
      -> Mchp Directory 1 -> Dir2 -> Directory 3 -> CWD.TXT
                                                 -> Directory 4 -> Directory 5 -> Directory 6
                                                                               -> Directory 7

*********************************************************************/


   while(1);
}
Exemple #30
0
void Initialize(){
	char str[100];
	char strl[100];
	char strr[100];
	DrawString(BOT_SCREEN,  " INITIALIZE... ", 0, SCREEN_HEIGHT-FONT_SIZE, WHITE, BLACK);
	if(FSInit()){
		DrawString(BOT_SCREEN,  " LOADING...    ", 0, SCREEN_HEIGHT-FONT_SIZE, WHITE, BLACK);
	}else{
		DrawString(BOT_SCREEN,  " ERROR!        ", 0, SCREEN_HEIGHT-FONT_SIZE, RED, BLACK);
	}
	LoadPack();

	//Console Stuff
	ConsoleSetXY(15, 20);
	ConsoleSetWH(SCREEN_WIDTH-30, SCREEN_HEIGHT-80);
	ConsoleSetBorderColor(BLUE);
	ConsoleSetTextColor(RGB(0, 141, 197));
	ConsoleSetBackgroundColor(TRANSPARENT);
	ConsoleSetSpecialColor(BLUE);
	ConsoleSetSpacing(2);
	ConsoleSetBorderWidth(3);
	//Check that the data is installed
	f_mkdir("rxTools");
	f_mkdir("rxTools/nand");
	InstallConfigData();
	LoadSettings();

	sprintf(str, "/rxTools/Theme/%c/TOP.bin", Theme);
	sprintf(strl, "/rxTools/Theme/%c/TOPL.bin", Theme);
	sprintf(strr, "/rxTools/Theme/%c/TOPR.bin", Theme);
	if(theme_3d)
		DrawTopSplash(str, strl, strr);
	else
		DrawTopSplash(str, str, str);

	if (!bootGUI)
	{
		if(silent_boot)
		{
			sprintf(str, "/rxTools/Theme/%c/boot.bin", Theme);
			DrawBottomSplash(str);

			for (int i = 0; i < 0x333333 * 2; i++){
				u32 pad = GetInput();
				if (pad & BUTTON_R1 && i > 0x333333) goto rxTools_boot;
			}
		}
		else
		{
			ConsoleInit();
			ConsoleSetTitle(STR_AUTOBOOT[language]);
			print(STR_HOLD_R[language]);
			ConsoleShow();

			for (int i = 0; i < 0x333333 * 6; i++){
				u32 pad = GetInput();
				if (pad & BUTTON_R1 && i > 0x333333) goto rxTools_boot;
			}
		}
				

		rxModeQuickBoot();
	}
rxTools_boot:

	sprintf(str, "/rxTools/Theme/%c/TOP.bin", Theme);
	sprintf(strl, "/rxTools/Theme/%c/TOPL.bin", Theme);
	sprintf(strr, "/rxTools/Theme/%c/TOPR.bin", Theme);
	if(theme_3d)
		DrawTopSplash(str, strl, strr);
	else
		DrawTopSplash(str, str, str);
}