// This function draws a binary file onto the screen, the file must be in the correct sgmented format, if not then use the MCHP putImage functions extern void DrawFromBinaryFile(FSFILE* source, unsigned int x_col, unsigned int y_row, unsigned int span, unsigned int columns) { unsigned char buffer[128]; // onto the stack unsigned char i; // Check file if (source == NULL) return; // Goto x,y y_row&=0x7; // y pos to page, 0-7 x_col&=0x7f; // x pos 0-127 DisplayWriteCommand((x_col>>4)|0x10); // high nibble with bit4 set DisplayWriteCommand(x_col&0x0f); // set lower column address DisplayWriteCommand(0xb0|y_row); // set GDRAM page address 0..7 (for 8 rows) y_row++; // next line // Read bytes to screen for (;columns>0;columns--) { // Buffer a line FSfread(buffer, span, 1, source); // Output the line for(i=0;i<span;i++) { DisplayWriteData(buffer[i]); } // Increment to next line, x = same, y+1 DisplayWriteCommand((x_col>>4)|0x10); // high nibble with bit4 set DisplayWriteCommand(x_col&0x0f); // set lower column address DisplayWriteCommand(0xb0|y_row++); // set GDRAM page address 0..7 (for 8 rows) } return; }
size_t FileReadUInt16(WORD *ptr, FILE_HANDLE stream) { BYTE databuff[2]; *ptr=0x0000; #if defined STACK_USE_MPFS2 WORD retVal; retVal=MPFSGetArray(stream, (BYTE*)ptr, 2); if(retVal == 2)//Number of bytes read { ((BYTE*)ptr)[1]= databuff[1]; ((BYTE*)ptr)[0]= databuff[0]; return 2;//Number of bytes read } else return 0; #elif defined STACK_USE_MDD size_t retVal; retVal= FSfread(databuff, 2, 1, stream); if(retVal == 1)//Number of Uints of 4 bytes each Read { ((BYTE*)ptr)[1]= databuff[1]; ((BYTE*)ptr)[0]= databuff[0]; return 2;//Number of bytes read } else return 0; #endif }
//************************************************************************************** //*** //*** //*** //************************************************************************************** size_t read (void *a, size_t b, size_t c, FILE *fin) { // This should not be required... // DEBUG ONLY asCON_SerialWriteString("read\n\r"); return FSfread(a,b,c,(FSFILE *)fin); }
/* 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); }
/* * 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)); } }
//************************************************************************************** //*** //*** //*** //************************************************************************************** size_t fread (void *a, size_t b, size_t c, FILE *fin) { if(fin==stdin) { // not required (direct call of "fgets()" above) // ASkr DEBUG asCON_SerialWriteString("*ouch*\n\r"); return 0; } else return FSfread(a,b,c,(FSFILE *)fin); }
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]); }
size_t FileRead(void *ptr, size_t size, size_t n, FILE_HANDLE stream) { #if defined STACK_USE_MPFS2 WORD length; length = size * n; return MPFSGetArray(stream, (BYTE*)ptr, length); #elif defined STACK_USE_MDD if(ptr == NULL) { return 0; } else { return FSfread(ptr, size, n, stream); } #endif }
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); }
/* * 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 fgetc (FILE *fin) { int ch; if( fin == stdin ) { // not that nice, but useful ch=asCON_RXBufReadChar(BLOCKING); asCON_SerialWriteChar(ch); // ENTER key returns '\r' if((char)ch=='\r') ch='\n'; return ch; } else { if(FSfread((int *)&ch,1,1,(FSFILE *)fin) != 1 ) return EOF; else return ch; } }
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; #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); }
/* * 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); }
static void file_flash(FSFILE* file) { UINT readBytes; UINT i; // Erase Flash (Block Erase the program Flash) if (NVMemBlockErase() != 0) { error(ERR_NV_ERASE); } record.status = REC_NOT_FOUND; // Initialize the state-machine to read the records. while (1) { USBTasks(); BlinkBlueLED(); BlinkOrangeLED(); // For a faster read, fetch 512 bytes at a time and buffer it. readBytes = FSfread((void*)&asciiBuffer[pointer], 1, 512, file); if (readBytes == 0) { // Nothing to read. Come out of this loop // break; // Jump to start of application // Disable all enabled interrupts (only USB) // before jumping to the application code. IEC5bits.USB1IE = 0; // JumpToApp(); return; } for (i = 0; i < (readBytes + pointer); i ++) { // This state machine seperates-out the valid hex records from the read 512 bytes. switch (record.status) { case REC_FLASHED: case REC_NOT_FOUND: if (asciiBuffer[i] == ':') { // We have a record found in the 512 bytes of data in the buffer. record.start = &asciiBuffer[i]; record.len = 0; record.status = REC_FOUND_BUT_NOT_FLASHED; } break; case REC_FOUND_BUT_NOT_FLASHED: if ((asciiBuffer[i] == 0x0A) || (asciiBuffer[i] == 0xFF)) { // We have got a complete record. (0x0A is new line feed and 0xFF is End of file) // Start the hex conversion from element // 1. This will discard the ':' which is // the start of the hex record. ConvertAsciiToHex(&record.start[1], hexRec); WriteHexRecord2Flash(hexRec); record.status = REC_FLASHED; } break; } record.len ++; // Move to next byte in the buffer. } if (record.status == REC_FOUND_BUT_NOT_FLASHED) { // We still have a half read record in the buffer. The next half part of the record is read // when we read 512 bytes of data from the next file read. memcpy(asciiBuffer, record.start, record.len); pointer = record.len; record.status = REC_NOT_FOUND; } else { pointer = 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); }
char BootApplication(FSFILE * pFile) { // Read the first packet header size_t sBytesRead = FSfread(&g_packetHeader, 8, 1, pFile); if( sBytesRead != 8 || g_packetHeader.PacketSize > 56) { if ( sBytesRead == 2 && g_packetHeader.PacketSize == 0) return 0; else return 2; } // Read the data if ( g_packetHeader.PacketSize ) { sBytesRead = FSfread(&g_DataBuffer, g_packetHeader.PacketSize, 1, pFile); if( sBytesRead != g_packetHeader.PacketSize ) return 2; } // Next action will depend on the type of packet we have switch( g_packetHeader.Type ) { case 0: { // FINISHED! return 0; break; } case UNLOCK_CONFIG: { MaxPageToErase = MaxPageToEraseWithConfigs; //Assume we will not allow erase/programming of config words (unless host sends override command) ProgramMemStopAddress = ProgramMemStopWithConfigs; ConfigsProtected = UNLOCKCONFIG; // There is one more page to erase then... ErasePageTracker = MaxPageToEraseWithConfigs; EraseFlash(); break; } case PROGRAM_COMPLETE: { WriteFlashSubBlock(); ProgrammedPointer = InvalidAddress; //Reinitialize pointer to an invalid range, so we know the next PROGRAM_DEVICE will be the start address of a contiguous section. break; } case PROGRAM_DEVICE: { if(ProgrammedPointer == (unsigned long)InvalidAddress) ProgrammedPointer = (unsigned long)g_packetHeader.Address; if(ProgrammedPointer == (unsigned long)g_packetHeader.Address) { unsigned char i; for(i = 0; i < (g_packetHeader.PacketSize/WORDSIZE); i++) { //unsigned int index; //index = (RequestDataBlockSize-g_packetHeader.PacketSize)/WORDSIZE+i; //ProgrammingBuffer[BufferedDataIndex] = g_DataBuffer[(RequestDataBlockSize-g_packetHeader.PacketSize)/WORDSIZE+i]; //Data field is right justified. Need to put it in the buffer left justified. ProgrammingBuffer[BufferedDataIndex] = g_DataBuffer[(i*2)]; ProgrammingBuffer[BufferedDataIndex] += (g_DataBuffer[(i*2)+1] << 8) & 0xFF00; BufferedDataIndex++; ProgrammedPointer++; if(BufferedDataIndex == (RequestDataBlockSize/WORDSIZE)) //Need to make sure it doesn't call WriteFlashSubBlock() unless BufferedDataIndex/2 is an integer { WriteFlashSubBlock(); } } } //else host sent us a non-contiguous packet address... to make this firmware simpler, host should not do this without sending a PROGRAM_COMPLETE command in between program sections. break; } } return 1; }//End BootApplication()