Hi,
I have a volatile long variable counting ticks in an interrupt routine. In order to work with the value in the main loop safely I first copy the volatile long to a local long and then work with the local one. Naturally I have to ensure that the interrupt doesn't increment the volatile long when I am copying it (imagine 0x0000ffff -> 0x00010000) so I need to disable the interrupts for a microsecond. What is the suggested way of temporary disabling the interrupts? Note that I must not lose any other interrupt coming at the time when the interrupts are disabled temporarily.
Currently I use three pins (A0, A1 and A2) for independent counting of three sources of ticks and I feel like sometimes the interrupt routines are called improperly and the ticks say from A0 pin are counted for pin A1 instead. It happens in like one of ten thousands ticks so it's almost impossible to debug. I suppose it might be caused by the way I disable the interrupts now:
volatile long _imp_count[3];
void loop()
{
long imp_count[3];
PCintPort::detachInterrupt(A0);
PCintPort::detachInterrupt(A1);
PCintPort::detachInterrupt(A2);
for(int f=0; f<3; f++) {
imp_count[f] = _imp_count[f];
imp_delta[f] = _imp_delta[f];
imp_millis[f] = _imp_millis[f];
}
PCintPort::attachInterrupt(A0, Kirq1, FALLING);
PCintPort::attachInterrupt(A1, Kirq2, FALLING);
PCintPort::attachInterrupt(A2, Kirq3, FALLING);
...
}
Perhaps if there is another interrupt coming at the moment when they are disabled then something bad happens when the interrupts are being re-enabled again and the interrupt is mis-handled?
What do you think? Is there a better way of safe copying the volatile variable to a local one? Also is it safe to assume that the interrupts on pin A0, A1 and A2 are handled independently by this library, even when the interrupts occur almost at the same time or when the interrupt routines are just disabled? Would it perhaps be more reasonable to direct each of the tick sources to its own dedicated Arduino port (B, C, D)?
Thanks,
Petr