Cases?
jeff-o
Posts: 181
Hi everyone,
What's the best way to implement "cases"? I need to have my program choose one of 19 outcomes based on a value, and I'd like to avoid a gigantic else-if chain if I can. My input is a value from 1 to about 3,300 from an ADC. The program needs to choose which "range" the number falls into (say, between 1 and 200) can set a second value based on that.
Cases and if-else probably isn't the only way to do it, so if you've got a better idea let me know!
What's the best way to implement "cases"? I need to have my program choose one of 19 outcomes based on a value, and I'd like to avoid a gigantic else-if chain if I can. My input is a value from 1 to about 3,300 from an ADC. The program needs to choose which "range" the number falls into (say, between 1 and 200) can set a second value based on that.
Cases and if-else probably isn't the only way to do it, so if you've got a better idea let me know!
Comments
I would likely solve this by having a data var or array of the "2nd values", then devide the adc reading to produce a 1-19 index to read from the array..
this assumes your ranges are equal.
If not equal, you could have 2 arrays. the first holds the upper of each range, the 2nd the values. loop through the first array checking until the adc value is higher than the array value.. When it is higher, use the previous idx value (DEC idx?). Then read the "2nd value" from the 2nd value array at that idx.
Hope this is understandable! Let me know if anything not clear!
Good luck.
or you do it with a table for range and resulting value:
If your ranges are equal and the resulting value is proportional then a simple calculation can do it:
Andy
The ranges aren't equally sized, so dividing to get an array index won't work. So, I think Maxwin's idea of a second array containing the maximum values (basically the threshold values) would do the trick.
This would also allow for simplified "tuning" of those threshold values.