Hi all,
I have a problem with 'volatile' use in C++.
The function get_clocks() below tries to use a 16 bit hardware counter to
count time. The counter overflows very often. But an interrupt is generated
everytime the counter overflows, and function handler() counts these
overflows in variable n_overflows.
The problem is that during calculation of time value in get_clocks()
function (marked by *** in the code), an overflow interrupt can happen
modifying n_overflows value. This will render the calculation useless
because value read from timer and n_overflows would not correspond to the
same point of time. To prevent that I use another variable called flag. The
flag is set by the interrupt handler to inform get_clocks function that
overflow occured. The function then retries the time calculation by
rereading values from the timer (the hardware timer counter is mapped to
memory address 0x10000000).
The problem is that it does not work. Sometimes time value returned from
get_clocks() is less than the previously acquired (by roughly 2^16 what
indicates a problem with n_overflow counter). I suspect there might be
something wrong with my use of volatile modifier.
Here's the relevant code:
volatile unsigned long n_overflows;
volatile bool flag;
// Overflow interrupt handler
void handler() {
++n_overflows;
flag = true;
}
// Function to get the number of clock ticks passed
unsigned long get_clocks() {
unsigned long r;
do {
flag = false;
r = n_overflows << 16 +
*(volatile unsigned short *)0x10000000; // ***
} while (flag);
return r;
}
thanks,
Marcin