I'm using the latest MCUXpresso IDE and am writing a bit of code to read a control bus. Nothing fancy. I debounce the bus for a bit of extra EMI/RFI robustness. The code is basically straight from Ganssle, J.G. (2004) A Guide to Debouncing.
The code works fine with the 'debug' configuration, but when I switch to 'release', the code breaks.
I've traced it down to compiler optimization. Optimization levels of -O0 to -O3 work. The optimization for size (-Os) breaks my code. I'm trying to understand why.
Here's my code:
#define DEBOUNCE_CHECKS 10u
/*******************************************************************************
* Global variables
******************************************************************************/
volatile uint32_t systick_counter;
volatile uint8_t raw_switches[DEBOUNCE_CHECKS], raw_controlBus[DEBOUNCE_CHECKS];
volatile uint8_t raw_switches_index = 0;
void SysTick_Handler(void)
{
if (systick_counter != 0U)
{
systick_counter--;
}
// Read control bus
raw_controlBus[raw_switches_index] = 0;
if(GPIO_PortRead(GPIO, BOARD_INITPINS_REMOTE_PORT) & BOARD_INITPINS_REMOTE_PIN_MASK) {
raw_controlBus[raw_switches_index] |= CTRL_REMOTE_BIT;
}
if(GPIO_PortRead(GPIO, BOARD_INITPINS_CTRL5_PORT) & BOARD_INITPINS_CTRL5_PIN_MASK) {
raw_controlBus[raw_switches_index] |= CTRL_CAP_BIT2_BIT;
}
[......]
if(raw_switches_index++ > DEBOUNCE_CHECKS) {
raw_switches_index = 0;
}
}
The issue is the in the last if() statement. raw_switches_index starts at 0 (as initialized) and counts 1, 2, 3 ... 10, 1, 2, 3 ... 10, 1, 2, 3 ... It was supposed to count 0, 1, 2 ,3 ... 10, 0, 1, 2, 3 ...
Why is this happening and how can I avoid it? I can certainly run without compiler optimization or with -O3, but I would like to understand what's going on here. I've tried taking the increment outside the if(), so:
raw_switches_index++;
if(raw_switches_index > DEBOUNCE_CHECKS) ....
I've tried pre-incrementing and I've tried raw_switches_index = raw_switches_index + 1. The compiler just laughs at me, which is not very nice.
Anyway. I'm really curious what could cause this. The reduction in code size that results for the compiler optimization is nice, but the reduction in functionality is not.
Thanks,
Tom