Interrupt / event for read a serial input

Hi mbed fans,

I try to read string from serial when it comes.
I tried a lot of variant code blocks found here, and I still can not find out way how to interrupt main thread to catch income message via serial line.
There must be the way.

can someone show me (and others too) simple way how it do it.

thank you.
indent preformatted text by 4 spaces

#include "mbed.h"
#include "platform/mbed_thread.h"

#define STRING_SIZE                                                         20

RawSerial pc(USBTX,USBRX, 9600);
DigitalOut led(LED2);

char message[STRING_SIZE];
bool flag_serial_catch = false;

void read_serial()
{	int string_possition;
char chr;
flag_serial_catch = true;
do
{
    chr = pc.getc();
	pc.putc(chr);       // it should be for clear Serrial::Irq
	message[string_possition] = chr;
	string_possition++;
}
while (chr != '\n');    // end of line character
}

int main()
{
    pc.attach(&read_serial, Serial::RxIrq);
    while(1)
    {
    wait(5);
    led = !led;
    if (flag_serial_catch)
    {
	    pc.printf("caught message is : %s\r\n", message);
	    flag_serial_catch = false;
    }
    else
	    pc.printf("Noting on serial port. \r\n");
    }
}

Maybe something like this?

#include "mbed.h"

DigitalOut led(LED1);
RawSerial pc(USBTX, USBRX);
EventQueue *queue = mbed_event_queue();

char message[32];

void onDataReceived();	// callback

void read_serial() {
	int string_possition;
	char chr;
	do
	{
	    chr = pc.getc();
		message[string_possition] = chr;
		string_possition++;
	}
	while (chr != '\r');    // end of line character
	pc.printf("caught message is : %s\r\n", message);
	memset(message, '\0', sizeof message);
	pc.attach(&onDataReceived, Serial::RxIrq);	// reattach interrupt
}

void onDataReceived() {
	pc.attach(NULL, Serial::RxIrq); // detach interrupt
	queue->call(read_serial);		// process in a non ISR context
}

int main() {
	pc.attach(&onDataReceived, Serial::RxIrq);
	while (1) {
	    ThisThread::sleep_for(500);  
    	led = !led;
	}
}
1 Like

Thank you so much! :+1:

I don’t understand it but it works.

Ahoj,

@Kiskovce I copy & paste your code and change only one thing .

//from this
int string_possition;
//to this
int string_possition = 0;

and your code working for me.

Br, Jan

Thank you, saw your post today, and it works!