I have enum list that has 16 elements in it. If the current selection is element 14 and the new selection is 5, how would I count from the current back around to the new selection? Can I do it with a for loop?
this is for a led light that has 16 program and is advanced by power cycle so need to count between current and new. I need to count 15 to 0 then to new and can't go backwards.
So you're not really asking about counting at all.
Just do a while loop and add in conditional checks after each increment to ensure the counting/tracking/index value wraps around properly at the limits. If X > max then X = min. Then just run the while loop until your current index value matches your destination index.
For loops require you to know the number of iterations you want to run ahead of time. You could use it for your scenario but then you would need to calculate the number of iterations ahead of time (which is more involved than necessary in your scenario). If you just use a while loop with wraparound summing then you don't need to worry about actually knowing how many power cycles you need to run.
As for advancing by power cycle, thats a bit strange, and I dont see how you would ever be out of sync by more than one (eg having a new selection of 5 when your current is 14)? You'd simply do the following on startup?
Code:
#define CHKPTR(ptr,sz) if((ptr)>=(sz)) ptr=0
enum {DISP1, DISP2, DISP3, NDISP};
int main(void) {
// read curProg from non-volatile source - eeprom/flash
curProg = get_curProg();
curProg++;
CHKPTR(curProg, NDISP);
// store
set_curProg(curProg);
// ...continue with regular prog....
}