#include "mbed.h"
// Create a DigitalOutput object to toggle an LED whenever data is received.
static DigitalOut led(LED1);
// Create a UnbufferedSerial object with a default baud rate.
static UnbufferedSerial serial_port(p13, p14);
void on_rx_interrupt()
{
char c;
// Toggle the LED.
led = !led;
// Read the data to clear the receive interrupt.
if (serial_port.read(&c, 1)) {
// Echo the input back to the terminal.
serial_port.write(&c, 1);
}
}
int main(void)
{
// Set desired properties (9600-8-N-1).
serial_port.baud(9600);
serial_port.format(
/* bits */ 8,
/* parity */ SerialBase::None,
/* stop bit */ 1
);
// Set up flow control -----------------------------------------------------------
serial_port.set_flow_control(mbed::UnbufferedSerial::RTSCTS, p12, p11);
// Register a callback to process a Rx (receive) interrupt.
serial_port.attach(&on_rx_interrupt, SerialBase::RxIrq);
}
And that is not allowed in ISR context, as it’s explained in the related Mbed documentation. Although you say the timing is critical, I think UART is a “slow” device so you can try to defer the execution of receive handler to a different thread by using an EventQueue. For example:
#include "mbed.h"
// Create a DigitalOutput object to toggle an LED whenever data is received.
DigitalOut led(LED1);
// Create a UnbufferedSerial object with a default baud rate.
UnbufferedSerial serial_port(p13, p14);
Thread thread;
EventQueue eventQueue;
void onSerialReceived(void)
{
char c;
// Toggle the LED.
led = !led;
// Read the data to clear the receive interrupt.
if (serial_port.read(&c, 1)) {
// Echo the input back to the terminal.
serial_port.write(&c, 1);
}
}
void onRxInterrupt()
{
// Defer execution of receive handler to the context of thread "thread" by EventQueue
eventQueue.call(onSerialReceived);
}
int main(void)
{
// Set desired properties (9600-8-N-1).
serial_port.baud(9600);
serial_port.format( /* bits */ 8, /* parity */ SerialBase::None, /* stop bit */ 1);
// Set up flow control -----------------------------------------------------------
serial_port.set_flow_control(mbed::UnbufferedSerial::RTSCTS, p12, p11);
// Register a callback to process a Rx (receive) interrupt.
serial_port.attach(&onRxInterrupt, SerialBase::RxIrq);
// Start thread and dispach event queue forever.
thread.start(callback(&eventQueue, &EventQueue::dispatch_forever));
}