Page 1 of 1

ADC, threading & mutexes?

Posted: Mon Oct 29, 2012 3:29 am
by russian
I have started with stm32f407_discovery demo code which works with ADC conversion callback. I am trying to save ADC state into a global data structure, so I have started to use mutexes. Thing is my code started to hang up after some random period of time, I have isolated it to locking/unlocking within ADC callback:

void adccb(ADCDriver *adcp, adcsample_t *buffer, size_t n) {
....
chSysLockFromIsr();
chMtxLock(&osc_mtx);
int i ;
for (i=0;i<100;i++) {
}
chMtxUnlock();
chSysUnlockFromIsr();


and my main thread does

while(1) {
someUIcode();
chMtxLock(&osc_mtx);
for (i=0;i<100;i++) {
}
chMtxUnlock();
}

I have tried both with and without 'chSysLockFromIsr/chSysUnlockFromIsr'.

So, what thread executed ADC callbacks? Is is allowed to use mutexes from within ADC callback? If it is not, how can I protect my data?

Re: ADC, threading & mutexes?

Posted: Mon Oct 29, 2012 9:06 am
by Giovanni
Hi,

The problem is that you cannot perform any "wait" operation in an interrupt handler or callback. This is true in general for any RTOS. I suggest you read the "kernel concepts" section in the kernel reference manual.

I suggest that you enable the debug options in chconf.h, the state checker would have signaled you the problem immediately by stopping you when calling chMtxLock().

If you need to access protected data from an ISR or callback do that by simply accessing it within a lock:

From the ISR: chSysLockFromIsr() / chSysUnlockFromIsr()
From threads: chSysLock() / chSysUnlock.

Basically, just remove the mutex and you will be fine.

Giovanni

Re: ADC, threading & mutexes?

Posted: Mon Oct 29, 2012 2:30 pm
by russian
Gotcha, "Serving Regular Interrupt. No system APIs are accessible but it is possible to switch to the I-Locked state using chSysLockFromIsr()". Thank you for the help!

And yes, debug options and immediate stop would have been a blessing, I will totally enable them.

I do have the solution I need, but just to be pedantic - if my UI thread would acquire system lock would it mean my interrupt handler/callback is waiting? Obviously, I will do my best to release this lock as soon as I can.