6 years, 5 months ago.

Correct use of Serial attach()

I would like to use the Serial attach() method to echo back characters received on an interrupt basis. However, when I do so I receive the error “Mutex 20000c3c error -6: Not allowed in ISR context”. What is the correct way to read a character from a serial port when in the attach() callback? Kindly note that the serial example quoted on mbed serial api page also uses the same method.

Here is my sample code:

application for serial echo

#include "mbed.h"

Serial pc(UART2_TX, UART2_RX);

void callback1() {
    pc.putc(pc.getc());
}


int main() {
    pc.attach(&callback1);
    pc.printf("Echoes back to the screen anything you type\n");

    while(1) {}
}

1 Answer

6 years, 5 months ago.

I will try to replicate this. What target are you using?

Hi. Thanks for the reply.

Actually i am working on porting mbed for a new target so I have written the HAL serial_api.c myself and now i am testing it. Does the above code works fine on other targets?

RawSerial works fine whereas using Serial class creates problem. Some old thread here on forums say that It is not allowed to acquire mutex in ISR and Serial class uses methods from Stream class which acquire mutex and hence the issue. So is this how it works that one cannot use Serial class in callbacks?

posted by Wajahat Abbas 20 Nov 2017

Sorry for the late reply - please try using RawSerial instead.

posted by mbed official 21 Dec 2017