11 years, 10 months ago.

MSCUsbHost USB flask drive recording using Ticker interface problem

I encountered weird problems with the MSCUsbHost and Ticker interface. It does not continue after the printf("file opening\n"); line. Your help will be appreciated. Thank you!

#include "mbed.h"
#include "MSCFileSystem.h"

MSCFileSystem msc("msc"); 
DigitalOut led (LED1);
Ticker usb;

void usbflip()
{
    printf("file opening\n");
    FILE *fp = fopen( "/msc/test.txt", "a");
    printf("file Checking error\n");
    if ( fp == NULL ) {
        error("Could not open file for write\n");
    }
    printf("file recording\n");
    fprintf(fp, "recorded\n");
    printf("file closing\n");
    fclose(fp);
}

int main()
{
    FILE *fp = fopen( "/msc/test.txt", "a");
    if ( fp == NULL ) {
        error("Could not open file for write\n");
    }
    fprintf(fp, "Recording\n");
    fclose(fp);
    usb.attach(usbflip, 3);
    while(1) {
        led = !led;
        wait(1.001);
    }
}

1 Answer

11 years, 10 months ago.

The usbflip() callback is operating in handler (interrupt, or IRQ) context. Long processes like printf, and USB handling, should not be undertaken in handler context, because they block all subsequent interrupts - including the next Ticker interrupt, which will be along before the last callback is processed, often. And USB needs interrupts, too.

Best thing is to use the callback to just set a flag. then, the main while 1 loop can check for the flag being set, and call a normal (non-IRQ) context function to write the file.

Accepted Answer

I'm still an amateur in Mbed, mind typing out example code for referencing? Thanks.

posted by WB Tan 22 Jan 2013

You can follow Andy Kirkham's splendid tutorial on the proper use of interrupts, callbacks, and flags (trips). One of his examples shows exactly what to do, in your case:

http://mbed.org/users/AjK/notebook/regarding-interrupts-use-and-blocking/

posted by Rod Coleman 23 Jan 2013