Processing SPI transactions using interrupts

interruptsmicrocontrollerpic

I'm wondering what the best way to handle SPI transactions when using interrupts is.

I'm about to write my SPI interface code to an external flash part using a PIC. I'm going to use interrupts and I know that I'll get one after my byte is transferred, and after one is received. A typical 16 bit write transaction will look like this:

REGISTER_ADDRESS_BYTE | REGISTER_ADDRESS_BYTE | DATA_BYTE | DATA_BYTE | MAYBE_MORE_DATA_BYTES

Typically what I do is have a function like this pseudo code:

SendBytes(num_bytes, *ptr_to_bytes, address, init_true, callback_function_address);

Then in my SendBytes(...) I have a state machine with two static variables, one keeps track of the state, the other keeps track of the number of bytes sent. As interrupts come in I call SendBytes(...) again with init_false and step through my state machine for each byte of the transaction. When I'm all done I either stop or call the stored call_back_function.

My question is this a decent way to handle this, is there a better way using interrupts? I just made this up thinking about the problem but I assume others have had to handle this as well.

Best Answer

You didn't mention the PIC variant; SPI peripherals as well as interrupt controllers are different in different PICs. Here is an example of handling similar problem using PIC16:

https://github.com/felis/DMCI-XC8/blob/master/bsp.c#L91

It also shows state machine approach.