Fwrite dysfunction on LPC1768 ?

09 Mar 2012

I am developing a slow rate (battery powered) data logger SW. I intend in a first time to store data in the local file system (flash memory). When I use fwrite() in a handler, if the main program does not end with a while(1) { }, fwrite fails (returns 0)... Why ?

09 Mar 2012

If you show the code, we'll be able to pinpoint the issue, but in general, doing heavy work like fwrite or sometimes even printf in interrupt handlers is not a good idea. What you should do is store your data in some global variable and set a flag which is checked in main() and the actual work is done there.

08 Apr 2012

Hi Igor, sorry for the delay. Here is a "demo" highlighting the problem ( USB cord used ). When I siwtched from local file system to USB stick in my project, I moved the writings in main(). Thanks for your support!

  1. include "mbed.h"

int done = 0; boolean DigitalOut myled(LED1); LocalFileSystem local("local"); Create the local filesystem under the name "local" FILE *fp;

void InitRTC() { struct tm t; t.tm_sec = 0; 0-59 t.tm_min = 0; 0-59 t.tm_hour = 0; 0-23 t.tm_mday = 1; 1-31 t.tm_mon = 0; 0-11 t.tm_year = 70; year since 1900 set_time(mktime(&t)); Jan 1 00:00:00 1970, sothat timestamp starts at 0 LPC_RTC->CCR = 0; RTC is stopped until acquisition is started NB: time() restarts the RTC ! LPC_RTC->CIIR = 1; Select interrupts, 1=seconds LPC_RTC->ILR = 3; Clear the counter increment interrupt and the alarm interrupt flags }

extern "C" void RTC_IRQHandler() { if(done == 0) { if (LPC_RTC->MIN == 0) { myled = 1; fprintf(fp, "%i: Hello World!", LPC_RTC->SEC); wait(0.1); myled = 0; } else { fclose(fp); myled = 1; done = 1; } } LPC_RTC->ILR = 1; Clear the counter increment interrupt flag }

int main() { InitRTC(); fp = fopen("/local/out.txt", "w"); Open "out.txt" on the local file system for writing LPC_RTC->CCR = 1; Start RTC NVIC_EnableIRQ(RTC_IRQn); while(1){} COMMENT OUT THIS LINE AND THE WRITINGS FAIL ! }

08 Apr 2012

Pierre, you need to use the code tags so the code is more legible.

I don't know if it is the issue, but if you are using fwrite, you should use "wb" in the fopen statement. fwrite is a binary file.

Second, have you tried putting a delay before it exits? Could it be that the interrupt isn't called before you exit?

-Doug

22 May 2012

Without the While to stay in the Main program, you would immediately exit Main which would probably Close any files before you had a chance to do any writing.