Serial Buffer

03 Nov 2011

Hi,

I have a question. How does the Serial buffer (either in the Serial or MODSERIAL API) work?

Basically can I start receiving data through a serial connection, go do something else, then return to the buffer and read in all the data? Or once I've started receiving data do I have to stand there and do nothing else until the last bit of data is received?

I'm guessing it's the former but don't know for sure.

Cheers Martin

03 Nov 2011
Hi,

>> do I have to stand there and do nothing else 
you can do that. It's simple, but blocks the CPU (and unsurprisingly, it's called "blocking IO").

If "coming back later": the hardware buffer may be quite limited, so don't wait for too long.
The best solution is IMO to attach an interrupt to the serial interface. On interrupt, copy the data to a (ring)buffer and do as little else as possible.
AFAIK, "modserial" attempts to provide a ready-made solution for those tasks.

With non-blocking IO, one needs to be aware of that the data doesn't arrive in pre-cut pieces, for example chopped at every newline.
You need some kind of parser / state-machine thing. Depending on the protocol, it can be simple (newline) or quite complex.

Here is one example for an interrupt handler: "radioSerial" is of type "Serial".
void radioSerialInterruptHandler(void){
    while (radioSerial.readable()){
        spektRx_runChar(&radioParser, radioSerial.getc());
    }
}

and here it's enabled for incoming data:

/* Start radio interrupt */
radioSerial.attach(&radioSerialInterruptHandler, Serial::RxIrq);