Page 1 of 1

Using SPI driver inside of an interrupt routine

Posted: Wed Mar 14, 2012 2:51 am
by SDControls
Hi,

I'm writing a handler for a touch screen sensor. An EXTi event is generated when user touches the screen. The handler should connect the sensor via SPI bus and read the values as soon as the event generated. Timing is critical in this case, because the touch value lasts only for 100msec or less, while I have to read the value multiple times (as much as 30 times) to get a stable average.

Problem arise when I try to communicate with the sensor via SPID driver inside of the EXTi handler, for example :

spiAcquireBus(&SPID1);
spiStart(&SPID1, spicfg);
spiSelect(&SPID1);
spiSend(&SPID1, 1, &cmd_byte); // system hangs here
spiReceive(&SPID1, 2, data); // or here
spiUnselect(&SPID1);
spiReleaseBus(&SPID1);

My observations are

- chSysLockFromIsr() / chSysUnlockFromIsr() won't help. In other words:

chSysLockFromIsr();
spiStartSendI(&SPID1, 1, &cmd_byte);
_spi_wait_s(&SPID1);
spiStartReceiveI(&SPID1, 2, data);
_spi_wait_s(&SPID1);

results the same.

- increasing PORT_INT_REQUIRED_STACK won't help either.

- invoking a thread instead, and treat there is not an option because of the delay.

So, my question is what am I missing here? or how do I workaround this? Any suggestion would be greatly appreciated.
Thank you for your time.

Re: Using SPI driver inside of an interrupt routine

Posted: Wed Mar 14, 2012 8:55 am
by Giovanni
Hi,

The problem is that you cannot "wait" into an interrupt handler, a callback is called from ISR context so any normal API cannot be used, you can only use I-Class functions and macros betwen chSysLockFromIsr() and chSysUnlockFromIsr().

An easy solution for your problem could be to wakeup a dedicated thread from your callback and let the thread do the transmission work synchronously.

Alternatively you can work without a thread and implement a state machine handling your transfer (from callback to callback until the end). Note that the STM32F4-Discovery demo shows how to start a SPI transmission from a callback, see main.c.

Giovanni