Can't make uart receive data

Hi, I have a code written below. It has to send some data on my pc each 10 ms. Also, I want to send a single number back via the same uart. It works fine until I send anything, then it stops completely.

#include "mbed.h"
#include "rtos.h"
Serial pc(PA_2, PA_3);
EventQueue eventQueue;
volatile int pos;
void uartOut(){
    pc.printf("%i", pos);
}
void uartIn(){
    if(pc.readable()){
    pc.scanf("%i", &pos);
    }
}
int main() {
    pc.baud(115200);
    eventQueue.call_every(10, uartOut);
    eventQueue.call_every(10, uartIn);
    eventQueue.dispatch_forever();
}

Hi @lav522
What is the board you are using?
Could you confirm that PA_2 pin is in fact the SERIAL_TX pin, and that it is correctly configured?
Regards,
Mbed support
Ron

I’m using BlackBoard with STM32F407VET6 on it. It’s the right pin, i’ve also tried the other UART pins (PD5, PD6) and got the same behavior.

Sounds like scanf() is waiting for a newline. Are you sure you are sending a line ending character?

Yes, you were right about that, now, when i’m adding \n it doesn’t stop. But I have another problem: it doesn’t receive my messages each time, so I have to press “send” button 10-20 times until it gets it.

You don’t want to use scanf in a character interrupt. It’s better to use an interrupt handler that only takes a character and then process the buffer when characters are received. PC.readable only tells you that at least 1 character is available. scanf wants a full line with CRLF in it.
Grab characters via interrupt and then just process the buffer on a regular interval and you should be ok.

Guys, new information: program stops every time it goes to interrupt context.

void onCharReceived(){
        led2 = !led2;
}
int main() {
    pc.attach(&onCharReceived);

        while (1) {
            pc.putc(pc.getc());
   }
}

Once I send anything, it stops.

Ahoj,
ye, you can not use it like that. The serial interrupt flag was set but not cleaned. Maybe my old answer will help you to understand.

BR, Jan

Thank you so much! RawSerial solved the problem.