Dynamically Change from Serial to DigitalIn and InterruptIn

I want to be able to dynamically change 2 pins from Serial (RX and TX) to one DigitalIn and One InterruptIn.

I can dynamically assign the pins at startup, but I cannot change it after that. Is there a way to do that. Here is my code now.


#define MODE_SERIAL 0
#define MODE_STEP_DIR 1
#define UART_TX PA_2
#define UART_RX PA_3
int mode = MODE_SERIAL;

Serial *pc;
InterruptIn *step;
DigitalIn *dir;

void set_mode(int new_mode) {
    delete step;
    delete dir;
    delete pc;
    
    if (new_mode == MODE_SERIAL) {               
        pc = new Serial(UART_TX, UART_RX);
        pc->baud(921600);
        pc->attach(&serial_interrupt);
    }
    else {
        step = new InterruptIn(UART_RX);
        step->rise(&stepInt);
        dir = new DigitalIn(UART_TX);
    }
    
    mode = new_mode;
}

This is called once in main(), which works, then subsequent calls don’t work.

Note: The deletes at the beginning were an experiment and had no effect.

You could try detaching the interrupt function before changing pin function.

pc->attach(NULL);

Otherwise afaik redefining a pin function will overwrite the previous settings.