/* * 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); }
/******************************************************************************* * FUNCTION: vLogGeneralException * * PARAMETERS: * ~ ucExcCode - ExcCode field of the Cause register. * * RETURN: * ~ void * * DESCRIPTIONS: * Log the general exception. * *******************************************************************************/ void vLogGeneralException(unsigned char ucExcCode) { // Convert the ExcCode to ASCII in hex. if (ucExcCode < 0x0a) { ucExcCode += 0x30; } else { ucExcCode += 0x37; } // Open the log file. FSFILE *pxLogFile = FSfopen(pucLogFilePath, "a"); // Write the message. const char szTxt1[] = "[General Exception] Cause: "; FSfwrite(szTxt1, 1, sizeof(szTxt1) - 1, pxLogFile); FSfwrite(&ucExcCode, 1, 1, pxLogFile); const char szTxt2[] = " Firmware: "; FSfwrite(szTxt2, 1, sizeof(szTxt2) - 1, pxLogFile); FSfwrite(szFirmwareVersion, 1, strlen(szFirmwareVersion), pxLogFile); const char szCrLf[] = "\r\n"; FSfwrite(szCrLf, 1, sizeof(szCrLf) - 1, pxLogFile); // Close the log file. FSfclose(pxLogFile); }
/* cat <nome_do_arquivo>, nao e' permitido espacos no nome */ static void b_cat(int argc, char **argv) { char retorno[16]; FSFILE *file; char l; if (argc != 2) { msg_erro_nos_argumentos(); return; } file = FSfopen(argv[1], "r"); if (strlen(argv[1]) == 0) return; if (file == NULL) { printf("\r\nerro: nao foi possivel abrir %s", argv[1]); return; } usb_print(NOVA_LINHA); while (!FSfeof(file)) { l = FSfread(retorno, 1, 16, file); usb_print_len(retorno, l); } FSfclose(file); }
//************************************************************************************** //*** //*** //*** //************************************************************************************** int close (FILE *fin) { // This should not be required... // DEBUG ONLY asCON_SerialWriteString("close\n\r"); return FSfclose((FSFILE *)fin); }
/******************************************************************************* * FUNCTION: vLogMallocError * * PARAMETERS: * ~ szSource - Location where malloc failed. * * RETURN: * ~ void * * DESCRIPTIONS: * Log the malloc error. * *******************************************************************************/ void vLogMallocError(const char* szSource) { // Open the log file. xSemaphoreTake(xSdCardMutex, portMAX_DELAY); portENTER_CRITICAL(); FSFILE *pxLogFile = FSfopen(pucLogFilePath, "a"); // Write the message. const char szTxt1[] = "[Malloc Error] "; FSfwrite(szTxt1, 1, sizeof(szTxt1) - 1, pxLogFile); FSfwrite(szSource, 1, strlen(szSource), pxLogFile); const char szTxt2[] = " Firmware: "; FSfwrite(szTxt2, 1, sizeof(szTxt2) - 1, pxLogFile); FSfwrite(szFirmwareVersion, 1, strlen(szFirmwareVersion), pxLogFile); const char szCrLf[] = "\r\n"; FSfwrite(szCrLf, 1, sizeof(szCrLf) - 1, pxLogFile); // Close the log file. FSfclose(pxLogFile); portEXIT_CRITICAL(); xSemaphoreGive(xSdCardMutex); }
/* * Cria um arquivo para o teste da memoria interna * Arquivo: LUA.INI * Conteudo: "gordon freeman" */ static void b_ft(int argc, char **argv) { FSFILE *file; char msg_teste[] = "gordon freeman"; char retorno[50]; (void) argc; (void) argv; if (argc != 1) { msg_erro_nos_argumentos(); return; } usb_print("\r\niniciando..."); file = FSfopen("HL.INF", "w"); if (file == NULL) goto erro; if (FSfwrite(msg_teste, 1, 15, file) != 15) goto erro; if (FSfclose(file)) goto erro; file = FSfopen("HL.INF", "r"); if (file == NULL) goto erro; if (FSfread(retorno, 15, 1, file) != 1) goto erro; if (FSfclose(file)) goto erro; printf("\r\nHL.INF: %s", retorno); usb_print("\r\nfinalizado sem nenhum erro"); return; erro: usb_print("\r\nerro: desconhecido"); return; }
int FileClose(FILE_HANDLE fh) { #if defined STACK_USE_MPFS2 MPFSClose(fh); #elif defined STACK_USE_MDD return FSfclose(fh); #endif return 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; } } } } }
// this may be called at interrupt or background level void log_close(void) { FSFILE* fp = fsp; // make a copy of our file pointer if (fsp) { fsp = NULL; // close the door to any further writes FSfclose(fp); // and close up the file printf("%s closed\r\n", logfile_name); } }
uint8_t fsmanSessionEnd(uint8_t * result_code){ if (*result_code = FSfclose (file), *result_code != CE_GOOD){ return FALSE; } if(!fsmanDeInit(result_code)){ return FALSE; } file = NULL; return TRUE; }
// *--------------------------------------------------------------------------------* 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(); } } } }
/******************************************************************************* * FUNCTION: vLogStackOverflow * * PARAMETERS: * ~ szTaskName - Task name. * * RETURN: * ~ void * * DESCRIPTIONS: * Log the RTOS stack overflow error. * *******************************************************************************/ void vLogStackOverflow(const char* szTaskName) { FSFILE *pxLogFile = FSfopen(pucLogFilePath, "a"); const char szLogMsg[] = "[Severe Stack Error] Task Name: "; FSfwrite(szLogMsg, 1, sizeof(szLogMsg) - 1, pxLogFile); FSfwrite(szTaskName, 1, strlen(szTaskName), pxLogFile); const char szFirmwareTitle[] = " Firmware: "; FSfwrite(szFirmwareTitle, 1, sizeof(szFirmwareTitle) - 1, pxLogFile); FSfwrite(szFirmwareVersion, 1, strlen(szFirmwareVersion), pxLogFile); FSfwrite("\r\n", 1, 2, pxLogFile); FSfclose(pxLogFile); }
void sendCompressedSpriteFile(unsigned long int cmd, unsigned int numBytes, unsigned char * filepath) { unsigned char spriteBuf[MAX_SPRITE_BUFFER_SIZE]; // DO NOT OVERFILL FSFILE * pointer; pointer = FSfopen(filepath, "r"); // read mode if (pointer == NULL) {while(1);} if (FSfread(spriteBuf, 1, numBytes, pointer) != numBytes) {while(1);} if (FSfclose(pointer)) {while(1);} sendCompressedSprite(cmd, numBytes, &spriteBuf[0]); }
// Draws a 128*64 image from a file name void DrawImageFromFileHelper(const char* fileName) { FSFILE* image = FSfopen(fileName, FS_READ); DisplayRestore(); if (image != NULL) { DrawFromBinaryFile(image, 0, 0, 128, 8); FSfclose(image); } else { DisplayClearDevice(); Display_print_xy("file not found:", 0, 2, 1); Display_print_xy((char*)fileName, 0, 3, 1); } return; }
static void b_edit_file(int argc, char **argv) { FSFILE *file; char buf[9]; int retorno; if (argc != 2) { msg_erro_nos_argumentos(); return; } file = FSfopen(argv[1], "w"); if (file == NULL) { usb_print("\r\nerro: nao foi possivel criar o arquivo"); return; } else { usb_print("\r\narquivo criado"); } // usb_print("\r\ndigite: "); // bash_read_null(buf, sizeof(buf)/sizeof(char)); // usb_print("\r\nrecebi: "); // for(retorno = 0; retorno < sizeof(buf)/sizeof(char); retorno++){ // usb_tx_1byte(buf[retorno]); // } while (1) { retorno = bash_read_null(buf, sizeof (buf) / sizeof (char)); if (FSfwrite(buf, 1, strlen(buf), file) != strlen(buf)) { usb_print("\r\nerro: na escrita"); goto fecha_arquivo; } else { usb_print("s"); } if (retorno == 1) break; } usb_print("\r\nfinalizado"); fecha_arquivo: if (FSfclose(file) != NULL) { usb_print("\r\nerro: nao foi possivel fechar o arquivo"); } }
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); }
static int fs_nextlog(char* filename) { FSFILE* fp; int i; for (i = 0; i < 99; i++) { sprintf(filename, "log%02u.txt", i); fp = FSfopen(filename, "r"); if (fp != NULL) { FSfclose(fp); } else { return 1; } } return 0; }
uint8_t fsmanSessionReset(uint8_t * result_code){ uint32_t pending = fsmanSessionCacheBytesWaiting(); if(pending){ __debug("Resetting session pending to disk %d bytes", pending); if (FSfwrite ((void *)fsbuf, 1, pending, file) != pending){ *result_code = UNKNOWN_WRITE_ERROR; __debug("Write pending bytes failed"); file = NULL; return FALSE; }else{ fsbufptr = 0; } } if (*result_code = FSfclose(file), *result_code != CE_GOOD){ return FALSE; } return fsmanSessionStart(result_code); }
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); }
/********************************************************************* * Forcibly shut down all connections with open files when the file * system is dismounted *********************************************************************/ void HTTP_FileSystemReset(BOOL safe) { BYTE index = MAX_HTTP_CONNECTIONS; do { HTTPLoadConn(--index); if(HTTP.file) { TCPFlush(HTTP.socket); TCPDisconnect(HTTP.socket); HTTP.StateMachine = SM_HTTP_IDLE; // Should the file be properly closed or just throw it away? if(safe) FSfclose(HTTP.file); HTTP.file = NULL; } } while(index); }
static CameraError retrievePic(String imgName) { setPowerOutput(ON); /** * Increasing Power On Period * * Although the data sheet says that the camera needs ~1.5 sec to start-up, * in practice 2 sec makes for a much more reliable situation. */ wait(2000);//1500); // initialize camera and image storage cameraComPort.init(); cameraComPort.baudrate(14400); //imageFile = getFileStream(); imageFile = FSfopen(imgName, "w"); CameraError error = NO_FILE; //if(imageFile.open) if(imageFile) { //FSfclose(FSfopen(imgName, "w")); // erase file //imageFile.open(imgName); // open file error = getPicture(); FSfclose(imageFile); imageFile = NullPtr; //imageFile.close(); } //imageFile.free(); setPowerOutput(OFF); wait(1000); return error; }
/******************************************************************************* * FUNCTION: vLogStackWatermark * * PARAMETERS: * ~ szTaskName - Task name. * ~ usWatermark - Value for watermark. * * RETURN: * ~ void * * DESCRIPTIONS: * Log the RTOS low stack error. * *******************************************************************************/ void vLogStackWatermark(const char* szTaskName, unsigned short usWatermark) { // Convert the watermark to string. char szWatermark[6]; prv_vUShortToString(usWatermark, szWatermark); // Open the log file. xSemaphoreTake(xSdCardMutex, portMAX_DELAY); portENTER_CRITICAL(); FSFILE *pxLogFile = FSfopen(pucLogFilePath, "a"); // Write the message. const char szTxt1[] = "[Stack Error] "; FSfwrite(szTxt1, 1, sizeof(szTxt1) - 1, pxLogFile); FSfwrite(szTaskName, 1, strlen(szTaskName), pxLogFile); const char szTxt2[] = " Watermark: "; FSfwrite(szTxt2, 1, sizeof(szTxt2) - 1, pxLogFile); FSfwrite(szWatermark, 1, strlen(szWatermark), pxLogFile); const char szTxt3[] = " Firmware: "; FSfwrite(szTxt3, 1, sizeof(szTxt3) - 1, pxLogFile); FSfwrite(szFirmwareVersion, 1, strlen(szFirmwareVersion), pxLogFile); const char szCrLf[] = "\r\n"; FSfwrite(szCrLf, 1, sizeof(szCrLf) - 1, pxLogFile); // Close the log file. FSfclose(pxLogFile); portEXIT_CRITICAL(); xSemaphoreGive(xSdCardMutex); }
BOOL BLMedia_LoadFile ( char *file_name ) { FSFILE *fp; // File pointer size_t nBuffer; // Number of bytes in the read buffer size_t iBuffer; // Index into the read buffer unsigned int nRemaining; // Number of bytes remaining to decode unsigned int Result; // Result code from "GetFlashBlock" operation WORD_VAL byteCountASCII; DWORD_VAL addressASCII; DWORD_VAL extendedAddressASCII; WORD_VAL recordTypeASCII; WORD_VAL checksumASCII; WORD_VAL dataByteASCII; DWORD_VAL totalAddress; BYTE_VAL byteCount; WORD_VAL address; WORD_VAL extendedAddress; BYTE_VAL recordType; BYTE_VAL checksum; BYTE_VAL dataByte; BYTE recordDataCounter; BYTE byteEvenVsOdd; WORD byteCountCopy; WORD* pData; BYTE i; BYTE mode; mode = 0x72; //"r" // Attempt to open the file if ( (fp=FSfopen((const char*)file_name, (const char*)&mode)) == NULL ) { BLIO_ReportBootStatus(BL_FS_FILE_ERR, "BL: Media Error - Unable to open file\r\n" ); return FALSE; } else { for(totalAddress.Val=PROGRAM_FLASH_BASE;totalAddress.Val<(PROGRAM_FLASH_END);totalAddress.Val+=FLASH_BLOCK_SIZE) { TBLPTRL = totalAddress.byte.LB; TBLPTRH = totalAddress.byte.HB; TBLPTRU = totalAddress.byte.UB; EECON1 = 0b00010100; INTCONbits.GIE = 0; //Make certain interrupts disabled for unlock process. _asm MOVLW 0x55 MOVWF EECON2, 0 MOVLW 0xAA MOVWF EECON2, 0 BSF EECON1, 1, 0 _endasm //Good practice now to clear the WREN bit, as further protection against any // future accidental activation of self write/erase operations. EECON1bits.WREN = 0; } // Read the file and program it to Flash iBuffer = 0; nRemaining = 0; nBuffer = 0; while(1) { if(nRemaining == 0) { nRemaining = FSfread(&ReadBuffer[0], 1, BL_READ_BUFFER_SIZE, fp ); if(nRemaining == 0) { //unable to read data from the file FSfclose( fp ); return FALSE; } iBuffer = 0; } switch(nBuffer) { case 0: //start code if(ReadBuffer[iBuffer] != ':') { //ignore line feeds and line returns if((ReadBuffer[iBuffer] != 0x0D) || (ReadBuffer[iBuffer] != 0x0A)) { iBuffer++; nRemaining--; //end of line of the last line continue; } else { FSfclose( fp ); return FALSE; } } iBuffer++; break; case 1: //byte count byte 1 byteCountASCII.v[1] = ReadBuffer[iBuffer++]; break; case 2: //byte count byte 2 byteCountASCII.v[0] = ReadBuffer[iBuffer++]; byteCount.Val = AsciiToHexByte(byteCountASCII.v[1],byteCountASCII.v[0]); byteCountCopy = byteCount.Val; byteEvenVsOdd = 0; recordDataCounter = 0; break; case 3: //address byte 1 addressASCII.v[3] = ReadBuffer[iBuffer++]; break; case 4: //address byte 2 addressASCII.v[2] = ReadBuffer[iBuffer++]; break; case 5: //address byte 3 addressASCII.v[1] = ReadBuffer[iBuffer++]; break; case 6: //address byte 4 addressASCII.v[0] = ReadBuffer[iBuffer++]; address.v[0] = AsciiToHexByte(addressASCII.v[1],addressASCII.v[0]); address.v[1] = AsciiToHexByte(addressASCII.v[3],addressASCII.v[2]); break; case 7: //record type byte 1 recordTypeASCII.v[1] = ReadBuffer[iBuffer++]; break; case 8: //record type byte 2 recordTypeASCII.v[0] = ReadBuffer[iBuffer++]; recordType.Val = AsciiToHexByte(recordTypeASCII.v[1],recordTypeASCII.v[0]); break; case 9: //data if(byteCountCopy != 0) { if(byteEvenVsOdd == 0) { dataByteASCII.v[1] = ReadBuffer[iBuffer++]; byteEvenVsOdd = 1; } else { dataByteASCII.v[0] = ReadBuffer[iBuffer++]; dataByte.Val = AsciiToHexByte(dataByteASCII.v[1],dataByteASCII.v[0]); recordData[recordDataCounter++] = dataByte.Val; byteCountCopy--; byteEvenVsOdd = 0; } break; } else { nBuffer = 10; } case 10: //checksum byte 1 checksumASCII.v[1] = ReadBuffer[iBuffer++]; break; case 11: //checksum byte 2 checksumASCII.v[0] = ReadBuffer[iBuffer++]; checksum.Val = AsciiToHexByte(checksumASCII.v[1],checksumASCII.v[0]); switch(recordType.Val) { case RECORD_TYPE_DATA_RECORD: //check the address here totalAddress.word.HW = extendedAddress.Val; totalAddress.word.LW = address.Val; if(totalAddress.Val < PROGRAM_FLASH_BASE) { //invalid address - below base - don't program the requested address break; } if(totalAddress.Val >= PROGRAM_FLASH_END) { break; } { unsigned int i; i = 0; if(totalAddress.Val & 0x01) { totalAddress.Val--; TBLPTRL = totalAddress.byte.LB; TBLPTRH = totalAddress.byte.HB; TBLPTRU = totalAddress.byte.UB; _asm tblrd tblwtpostinc _endasm TABLAT = recordData[i++]; _asm tblwt //Do not increment TBLPTR on the second write. See datasheet. _endasm EECON1 = 0b00100100; //Word programming mode INTCONbits.GIE = 0; //Make certain interrupts disabled for unlock process. _asm MOVLW 0x55 MOVWF EECON2, 0 MOVLW 0xAA MOVWF EECON2, 0 BSF EECON1, 1, 0 //Initiates write operation (halts CPU execution until complete) _endasm //Good practice now to clear the WREN bit, as further protection against any // future accidental activation of self write/erase operations. EECON1bits.WREN = 0; totalAddress.Val = totalAddress.Val + 2; byteCount.Val--; } while(byteCount.Val > 1) { TBLPTRL = totalAddress.byte.LB; TBLPTRH = totalAddress.byte.HB; TBLPTRU = totalAddress.byte.UB; TABLAT = recordData[i++]; _asm tblwtpostinc _endasm TABLAT = recordData[i++]; _asm tblwt //Do not increment TBLPTR on the second write. See datasheet. _endasm EECON1 = 0b00100100; //Word programming mode INTCONbits.GIE = 0; //Make certain interrupts disabled for unlock process. _asm MOVLW 0x55 MOVWF EECON2, 0 MOVLW 0xAA MOVWF EECON2, 0 BSF EECON1, 1, 0 //Initiates write operation (halts CPU execution until complete) _endasm //Good practice now to clear the WREN bit, as further protection against any // future accidental activation of self write/erase operations. EECON1bits.WREN = 0; totalAddress.Val += 2; byteCount.Val -= 2; } if(byteCount.Val == 1) { TBLPTRL = totalAddress.byte.LB; TBLPTRH = totalAddress.byte.HB; TBLPTRU = totalAddress.byte.UB; TABLAT = recordData[i++]; _asm tblwtpostinc _endasm _asm tblrd tblwt //Do not increment TBLPTR on the second write. See datasheet. _endasm EECON1 = 0b00100100; //Word programming mode INTCONbits.GIE = 0; //Make certain interrupts disabled for unlock process. _asm MOVLW 0x55 MOVWF EECON2, 0 MOVLW 0xAA MOVWF EECON2, 0 BSF EECON1, 1, 0 //Initiates write operation (halts CPU execution until complete) _endasm //Good practice now to clear the WREN bit, as further protection against any // future accidental activation of self write/erase operations. EECON1bits.WREN = 0; totalAddress.Val += 2; byteCount.Val--; } } break; case RECORD_TYPE_EOF: FSfclose( fp ); return TRUE; break; case RECORD_TYPE_EXTENDED_ADDRESS: extendedAddress.v[1] = recordData[0]; extendedAddress.v[0] = recordData[1]; break; } break; default: FSfclose( fp ); return FALSE; } if(nBuffer != 9) { nBuffer++; } if(nBuffer == 12) { nBuffer = 0; } nRemaining--; } FSfclose( fp ); } return TRUE; } // BLMedia_LoadFile
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) { 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; }
/* * Loader for Intel hex */ static int load_hex(char *fn) { register int i; FSFILE * fd; char buf[BUFSIZE]; char *s; int count = 0; int addr = 0; int saddr = 0xffff; int eaddr = 0; int data; int temp; char tempBuf[BUFSIZE]; if ((fd = FSfopen(fn, "R")) == NULL) { printf("can't open file hex %s\n", fn); return (1); } //:20100000F33100412100420EFFAF77230DC20A10219B2C1100420159007E1223130B78B13A while (FSfeof(fd) == 0x00) { temp = 0; tempBuf[0] = 0; while (tempBuf[0] != 0x0a) { FSfread(tempBuf, 1, 1, fd); if (tempBuf[0] != 0x0d) buf[temp++] = tempBuf[0]; } // while (fgets(&buf[0], BUFSIZE, fd) != NULL) { s = &buf[0]; while (isspace(*s)) s++; if (*s != ':') continue; if (checksum(s + 1) != 0) { printf("invalid checksum in hex record: %s\n", s); return (1); } s++; count = (*s <= '9') ? (*s - '0') << 4 : (*s - 'A' + 10) << 4; s++; count += (*s <= '9') ? (*s - '0') : (*s - 'A' + 10); s++; if (count == 0) break; addr = (*s <= '9') ? (*s - '0') << 4 : (*s - 'A' + 10) << 4; s++; addr += (*s <= '9') ? (*s - '0') : (*s - 'A' + 10); s++; addr *= 256; addr += (*s <= '9') ? (*s - '0') << 4 : (*s - 'A' + 10) << 4; s++; addr += (*s <= '9') ? (*s - '0') : (*s - 'A' + 10); s++; if (addr < saddr) saddr = addr; eaddr = addr + count - 1; s += 2; for (i = 0; i < count; i++) { data = (*s <= '9') ? (*s - '0') << 4 : (*s - 'A' + 10) << 4; s++; data += (*s <= '9') ? (*s - '0') : (*s - 'A' + 10); s++; *(ram +addr + i) = data; } } FSfclose(fd); printf("\nLoader statistics for file %s:\n", fn); printf("START : %04x\n", saddr); printf("END : %04x\n", eaddr); printf("LOADED: %04x\n\n", eaddr - saddr + 1); PC = wrk_ram = ram +saddr; return (0); }
/* ************************************************************************* * 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; } }
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); }
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); }
//************************************************************************************** //*** //*** //*** //************************************************************************************** int fclose (FILE *fin) { return FSfclose((FSFILE *)fin); }