• Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

Enum list counting

Status
Not open for further replies.

TucsonDon

Member
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?
 

dknguyen

Well-Known Member
Most Helpful Member
why can't you just go (new - current)? Where a positive result is counting forward and a negative result is counting backward?

Arithmetic works on enum types.
 

TucsonDon

Member
why can't you just go (new - current)? Where a positive result is counting forward and a negative result is counting backward?

Arithmetic works on enum types.
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.
 

dknguyen

Well-Known Member
Most Helpful Member
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.
 
Last edited:

Cicero

Active Member
Agree with above, consider adding a NELEMENT to your enum like so, and use a macro to wrap your pointer/counter:

Code:
#define CHKPTR(ptr,sz) if((ptr)>=(sz)) ptr=0
enum {DISP1, DISP2, DISP3, NDISP};

while(curProg != newProg) {
  curProg++;
  CHKPTR(curProg, NDISP);
}
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....
}
 
Status
Not open for further replies.

Latest threads

EE World Online Articles

Loading
Top