/******************************************************************************* * 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); }
/******************************************************************************* * 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); }
/******************************************************************************* * 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); }
size_t FileWrite(const void *ptr, size_t size, size_t n, FILE_HANDLE stream) { #if defined STACK_USE_MPFS2 WORD length; length = size * n; return MPFSPutArray(stream, (BYTE*)ptr, length); #elif defined STACK_USE_MDD return FSfwrite(ptr, size, n, stream); #endif }
static void log_write(char* str, int len) { if (fsp) { LED_BLUE = LED_ON; if (FSfwrite(str, 1, len, fsp) != len) { DPRINT("ERROR: FSfwrite\r\n"); log_close(); } } }
//************************************************************************************** //*** fwrite //*** //*** output for: //*** - io.write (file and "console") //************************************************************************************** size_t fwrite (const void *ptr, size_t size, size_t count, FILE *fin ) { char *pc=(char *)ptr; if( ( fin == stdout) || ( fin == stderr ) ) { while(count--) asCON_SerialWriteChar(*pc++); return count; } else return FSfwrite(ptr,size,count,(FSFILE *)fin); }
// *--------------------------------------------------------------------------------* 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(); } } } }
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"); } }
uint8_t fsmanSessionWrite(uint8_t * result_code, uint8_t* data, uint32_t len){ uint32_t sz = MIN(len, FS_BUF_SZ - fsbufptr); memcpy(&fsbuf[fsbufptr],data, sz); fsbufptr += sz; if (fsbufptr >= FS_BUF_SZ){ //todo add a time limit so that we do exceed file size limits if ( FSfwrite(fsbuf, 1, FS_BUF_SZ, file) != FS_BUF_SZ){ *result_code = UNKNOWN_WRITE_ERROR; return FALSE; } else{ memcpy(fsbuf,&data[sz], len-sz); //copy pending data if any fsbufptr = len-sz; __debug("Wrote %d bytes",FS_BUF_SZ); } } *result_code = CE_GOOD; return TRUE; }
/* * 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; }
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); }
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); }
/******************************************************************************* * 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); }
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); }
void WriteToUSB(){ if (state == log){ unsigned millisec_USE = millisec; double pitch, roll, yaw; double latAcc, longAcc, vertAcc; double HRlatAcc, HRlongAcc, HRvertAcc; char angString[40]; char accString[40]; char HRaccString[40]; char motec0String[40]; char motec1String[40]; char motec2String[40]; char motec3String[40]; char motec4String[40]; char motec5String[40]; char PSOCstring0[40]; char PSOCstring1[40]; char PSOCstring2[40]; char dataFlagString[40]; char timeString[40]; sprintf(timeString,"%d,", millisec_USE); if(angularRateInfoRec){ pitch = (((double)(angularRateInfo[1] << 8 | angularRateInfo[0])) /128) - 250; roll = (((double)(angularRateInfo[3] << 8 | angularRateInfo[2])) /128) - 250; yaw = (((double)(angularRateInfo[5] << 8 | angularRateInfo[4])) /128) - 250; angularRateInfoRec = FALSE; sprintf(angString, "%.6f,%.6f,%.6f,", pitch, roll, yaw); }else{ sprintf(angString, " , , ,"); } if(accelerationSensorRec){ latAcc = (((double)(accelerationSensor[1] << 8 | accelerationSensor[0])) * .01) - 320; longAcc = (((double)(accelerationSensor[3] << 8 | accelerationSensor[2])) * .01) - 320; vertAcc = (((double)(accelerationSensor[5] << 8 | accelerationSensor[4])) * .01) - 320; accelerationSensorRec = FALSE; sprintf(accString, "%.6f,%.6f,%.6f,", latAcc, longAcc, vertAcc); }else{ sprintf(accString, " , , ,"); } if(HRaccelerationSensorRec){ HRlatAcc = (((double)(HRaccelerationSensor[1] << 8 | HRaccelerationSensor[0])) * .000599) - 19.62; HRlongAcc = (((double)(HRaccelerationSensor[3] << 8 | HRaccelerationSensor[2])) * .000599) - 19.62; HRvertAcc = (((double)(HRaccelerationSensor[5] << 8 | HRaccelerationSensor[4])) * .000599) - 19.62; HRaccelerationSensorRec = FALSE; sprintf(HRaccString, "%.6f,%.6f,%.6f,", HRlatAcc, HRlongAcc, HRvertAcc); }else{ sprintf(HRaccString, " , , ,"); } if(motec0Read){ int t_rpm = rpm; double t_tps = (double) tp * .1; double t_map = (double) map *0.1; double t_at = (double) at*0.1; sprintf(motec0String, "%d,%.6f,%.6f,%.6f,", t_rpm, t_tps, t_map, t_at ); motec0Read = FALSE; }else{ sprintf(motec0String, " , ,"); } if(motec1Read){ double t_engineTemp = (double) et * .1; double t_lambda1 = (double) la1 * .001; int t_fuelPress = fp; sprintf(motec1String, "%.6f,%.6f,%d,", t_engineTemp, t_lambda1, t_fuelPress); motec1Read = FALSE; }else{ sprintf(motec1String, " , , ,"); } if(motec2Read){ double t_egt1 = (double)egt1; int t_userLaunch = launch;//not sure scaling int t_userNtrl = ntrl;//not sure scaling int t_brakePres = bp;//not sure scaling sprintf(motec2String, "%.6f,%d,%d,%d,", t_egt1, t_userLaunch, t_userNtrl, t_brakePres); motec2Read = FALSE; }else{ sprintf(motec2String, " , , , ,"); } if(motec3Read){ int t_brakePresFil = bpf1;//not sure scaling double t_batV = (double)batV * .01; double t_ldspd = (double)ldSpd * .1; double t_lgspd = (double)lgSpd * .1; sprintf(motec3String, "%d,%.6f,%.6f,%.6f,", t_brakePresFil, t_batV, t_ldspd, t_lgspd); motec3Read = FALSE; }else{ sprintf(motec3String, " , , , ,"); } if(motec4Read){ double t_rdspd = (double)rdSpd * .1; double t_rgspd = (double)rgSpd * .1; float t_runTime = runTime * .1;//not sure scaling sprintf(motec4String, "%.6f,%.6f,%.6f, %d,", t_rdspd, t_rgspd, t_runTime, fuel); motec4Read = FALSE; }else{ sprintf(motec4String, " , , , ,"); } if(motec5Read){ double oilTempDegF = (double)oilTemp * .1; double ignTimeL = (double)ignTime * 0.1; sprintf(motec5String, "%.6f, %.6f,", oilTempDegF, ignTimeL); motec5Read = FALSE; }else{ sprintf(motec5String, ", ,"); } //PSOC if(PSOCConnected){ //This allows for the program to be tested without the PSOC connected. PSOC read is a global variable defined at the top of the file PSOC_Read(); sprintf(PSOCstring0,"%d,%d,%d,%d,%d,%d,",PSOC_volts[0],PSOC_volts[1],PSOC_volts[2],PSOC_volts[3],PSOC_volts[4],PSOC_volts[5]); //Current Sensors sprintf(PSOCstring1,"%d,%d,%d,%d,",PSOC_volts[6],PSOC_volts[7],PSOC_volts[8],PSOC_volts[9]); //Shock Pots sprintf(PSOCstring2,"%d,%d,",PSOC_volts[10],PSOC_volts[11]); //Steering Angle And Brake temp and millisec counter } else{ sprintf(PSOCstring0," , , , , , , "); sprintf(PSOCstring1," , , , ,"); sprintf(PSOCstring2,", ,"); } //dataFlag sprintf(dataFlagString,"%d,",dataFlag); //Write all strings to the CSV file FSfwrite(timeString,1,strlen(timeString),myFile); FSfwrite(angString,1, strlen(angString),myFile); FSfwrite(accString,1, strlen(accString),myFile); FSfwrite(HRaccString,1, strlen(HRaccString),myFile); FSfwrite(motec0String,1, strlen(motec0String),myFile); FSfwrite(motec1String,1, strlen(motec1String),myFile); FSfwrite(motec2String,1, strlen(motec2String),myFile); FSfwrite(motec3String,1, strlen(motec3String),myFile); FSfwrite(motec4String,1, strlen(motec4String),myFile); FSfwrite(motec5String,1, strlen(motec5String),myFile); FSfwrite(PSOCstring0,1, strlen(PSOCstring0),myFile); FSfwrite(PSOCstring1,1, strlen(PSOCstring1),myFile); FSfwrite(PSOCstring2,1, strlen(PSOCstring2),myFile); FSfwrite(dataFlagString,1,strlen(dataFlagString),myFile); FSfwrite(GPSWriteData,1,sentenceLength,myFile); //The NMEA sentence had a \n character at the end, no need to manually include it FSfwrite("\n",1,1,myFile); } }
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; }
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); }
static CameraError getPicture(void) { toCam = newCameraPacket(), fromCam = newCameraPacket(); toCam.cmdToken = SYNC; int syncTries = 0; //if(!imageFile.open) if(!imageFile) return NO_FILE; /* try and get sync with camera */ while(!(fromCam.cmdToken == ACK && fromCam.parameter1 == SYNC)) // until ACK received { if(syncTries == 3) cameraComPort.baudrate(115200); cameraComPort.flush(); sendPacket(toCam); // send SYNC command pause(25); fromCam = getPacket(); // get reply if(syncTries < 7) ++syncTries; else return NO_HANDSHAKE; } /* acknowledge camera's sync request */ toCam = newCameraPacket(); // initialize packet toCam.cmdToken = ACK; // acknowledge toCam.parameter1 = SYNC; // the sync syncTries = 0; while(!(fromCam.cmdToken == SYNC)) // wait for camera SYNC request { fromCam = getPacket(); if(syncTries < 7) ++syncTries; else return NO_SYNC; } sendPacket(toCam); /* configure camera */ toCam = newCameraPacket(); // initialize packet toCam.cmdToken = INITIAL; // initial configuration toCam.parameter1 = 0x04; // 115,200 baud rate toCam.parameter2 = 0x87; // compress color toCam.parameter3 = 0x01; // 80x60 preview resolution toCam.parameter4 = 0x07; // 640x480 compression resolution sendPacket(toCam); /* if camera acknowledges changes, change the UART baud rate */ fromCam = getPacket(); if(!(fromCam.cmdToken == ACK && fromCam.parameter1 == INITIAL)) return NO_INITIAL;// if reconfiguration was not successful cameraComPort.baudrate(115200); // change UART baud rate /* specify image quality */ toCam = newCameraPacket(); // initialize packet toCam.cmdToken = QUALITY; // configure picture quality toCam.parameter1 = 0x00; // to be the best sendPacket(toCam); /* if camera acknowledges change, then get an image */ fromCam = getPacket(); if(!(fromCam.cmdToken == ACK && fromCam.parameter1 == QUALITY)) return NO_QUALITY;// if reconfiguration was not successful /* get an image */ toCam = newCameraPacket(); // initialize packet toCam.cmdToken = GET_PIC; // configure picture quality toCam.parameter1 = 0x05; // get full size image sendPacket(toCam); /* if camera acknowledges request, then retrieve image data */ fromCam = getPacket(); if(!(fromCam.cmdToken == ACK && fromCam.parameter1 == GET_PIC)) return NO_GET_PIC; // if request was not successful /* get image size */ fromCam = getPacket(); if(!(fromCam.cmdToken == DATA)) return NO_DATA; // if request was not successful /* read data size */ picsize = bytesToGet = fromCam.parameter2 + fromCam.parameter3 * 0x100LL + fromCam.parameter4 * 0x10000LL; int cnt = 0; /* store the image */ while(bytesToGet > 0) // until all bytes retrieved { tempSize = cameraComPort.receive(tempBuffer, RX_BUFFER_SIZE); // receive the bytes //imageFile.write(tempBuffer,tempSize); // store the bytes FSfwrite(tempBuffer, sizeof(char), tempSize, imageFile); bytesToGet -= tempSize; // update bytes remaining // watch dog counter - bytes are sometimes lost...so loop will hang cnt = tempSize ? 0: cnt + 1; if(cnt > 200) break; } /* acknowledge that data was received */ /* NOT NEEDED */ //toCam = newCameraPacket(); // initialize packet //toCam.cmdToken = ACK; // notify the camera of successful //toCam.parameter1 = DATA; // data retrieval //sendPacket(toCam); pause(30); if(bytesToGet) return LOST_DATA; // not all camera data was gathered else return NO_ERROR; // successful }
/****************************************************************************** * Main Program Loop ******************************************************************************/ void main(void) { // SD Card variables FSFILE *csv_file; // The file to write to SearchRec rec; // The data structure to store the search results UINT8 i=0; char filename[] = "ACCEL00.CSV"; char file_number[2]; char attr0[] = "w"; char attr1[] = "a"; char headers[] = "X,Y,Z\n"; char rangeString[] = "range=00\n"; char buf[6] = ""; ADXL345_AXIS_DATA *temp; UINT8 range = 0x03; // The range to use the accelerometer with (initialize with a mask for the pins) boolean selfTest = FALSE; // Selftest enable flag for the accelerometer (initialize with false) /* * Initialize the program */ // TODO: Fix function prototype warning // Initialize the processor and peripherals config_proc(); Delay10KTCYx(4); i2c_init(); printf("\n\n\rProcessor Configuration Complete\n\r"); printf("Delaying for 5..."); Delay10KTCYx(FOSC); printf("4..."); Delay10KTCYx(FOSC); printf("3..."); Delay10KTCYx(FOSC); printf("2..."); Delay10KTCYx(FOSC); printf("1..."); Delay10KTCYx(FOSC); printf("0...\n\r"); // Initialize the SD Card and set a default clock printf("Initializing SD Card\n\r"); while (!FSInit()) { printf("Error Initializing SD Card: %d\n\r", FSerror()); } if (SetClockVars (2013, 1, 1, 12, 0, 00)) printf("Clock not set\n\r"); // It didn't work // Read the accelerometer range from the pins and make a string to say what it is range = range & ~( ( PORTAbits.RA0 << 1) | PORTAbits.RA1 ); printf("Determining range setting\n\r"); switch (range) { case ADXL345_RANGE_2G: rangeString[6] = '0'; rangeString[7] = '2'; break; case ADXL345_RANGE_4G: rangeString[6] = '0'; rangeString[7] = '4'; break; case ADXL345_RANGE_8G: rangeString[6] = '0'; rangeString[7] = '8'; break; case ADXL345_RANGE_16G: rangeString[6] = '1'; rangeString[7] = '6'; break; default: // Just leave the range as 00 to show an error condition has occured break; } printf("%s\r", rangeString); /* * Determine the filename to use for the new file. * The filename should be "accelx" where x is the next available integer. */ // This code section causes the PIC to crash for some reason, // It was used previosuly so I have no idea what is going on /* printf("Searching for files\n\r"); if (FindFirstpgm("accel*.csv", ATTR_MASK, &rec) == -1) { // No file was found so leave it at the default filename printf("No files found\n\r"); } else { printf("Files found\n\r"); // Files were found, so find the next unused number do{ file_number[0] = rec.filename[5]; file_number[1] = rec.filename[6]; } while (FindNext(&rec) == 0); if(file_number[1] == '9') { file_number[0]++; file_number[1] = '0'; } else { file_number[1]++; } filename[5] = file_number[0]; filename[6] = file_number[1]; } */ // Open the file using the above name printf("Opening file %s\n\r",filename); csv_file = FSfopen(filename, attr0); if (csv_file == NULL) printf("File not opened, error: %u\n\r",FSerror()); // Write a header to the file saying the current measurement range if (FSfwrite((void*)rangeString , 1, 9, csv_file) != 9) printf("Unable to write measurement range to the file\n\r"); // Write the column headers into the file if (FSfwrite((void *)headers, 1, 6, csv_file) != 6) printf("Unable to write headers to the file\n\r"); // Close the file if (FSfclose(csv_file)) printf("Unable to close file\n\r"); /* * Perform configuration on the accelerometer */ // Enable the selftest if neccessary if (PORTAbits.RA2 == 0) { selfTest = TRUE; } config_accel(range); printf("Accelerometer Configuration Complete\n\r"); // Main program loop while(1) { #ifdef PRINT_DEBUGS printf("Waiting for watermark\n\r"); #endif // Loop and do nothing while waiting for the watermark to be triggered while (ADXL345_INT1_PORT == 0){}; LATCbits.LATC1 = 1; // Turn on the LED to show we are processing data #ifdef PRINT_DEBUGS printf("Watermark Received\n\r"); #endif // Read in the data for(i=0; i<12; i++) { // Read the data adxl345_data_read(temp); #ifdef PRINT_DEBUGS printf("%i, %i, %i\n\r", temp->x, temp->y, temp->z); #endif // Convert the x-axis data into text padded_itoa(buf, temp->x); sendBuffer[(18*i)+0] = buf[0]; sendBuffer[(18*i)+1] = buf[1]; sendBuffer[(18*i)+2] = buf[2]; sendBuffer[(18*i)+3] = buf[3]; sendBuffer[(18*i)+4] = buf[4]; sendBuffer[(18*i)+5] = ','; // Convert the y-axis data into text padded_itoa(buf, temp->y); sendBuffer[(18*i)+6] = buf[0]; sendBuffer[(18*i)+7] = buf[1]; sendBuffer[(18*i)+8] = buf[2]; sendBuffer[(18*i)+9] = buf[3]; sendBuffer[(18*i)+10] = buf[4]; sendBuffer[(18*i)+11] = ','; // Convert the z-axis data into text padded_itoa(buf, temp->z); sendBuffer[(18*i)+12] = buf[0]; sendBuffer[(18*i)+13] = buf[1]; sendBuffer[(18*i)+14] = buf[2]; sendBuffer[(18*i)+15] = buf[3]; sendBuffer[(18*i)+16] = buf[4]; sendBuffer[(18*i)+17] = '\n'; } csv_file = FSfopen(filename, attr1); if (csv_file == NULL) printf("File not opened, error: %u\n\r",FSerror()); FSfwrite((void *) sendBuffer, 1, 216, csv_file); FSfclose(csv_file); LATCbits.LATC1 = 0; } }