Shop OBEX P1 Docs P2 Docs Learn Events
Cases? — Parallax Forums

Cases?

jeff-ojeff-o Posts: 181
edited 2010-12-15 06:49 in Propeller 1
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!

Comments

  • VonSzarvasVonSzarvas Posts: 3,523
    edited 2010-12-15 05:53
    jeff-o wrote: »
    Hi everyone,

    What's the best way to implement "cases"?

    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.
  • AribaAriba Posts: 2,690
    edited 2010-12-15 06:00
    Either you use the case statement of Spin:
    case adc
        0..99:    val := 5
        100..199: val := 7
        200..499: val := 8
        500..599: val := 10
        ...
    

    or you do it with a table for range and resulting value:
    repeat i from 0 to 18
        if adc => range[i] and adc < range[i+1]
          val := outval[i]
          quit
    
    DAT
    range  word  0, 100, 200, 500, 600 ...  '20 values
    outval word    5,   7,   8,  10    ...  '19 values
    

    If your ranges are equal and the resulting value is proportional then a simple calculation can do it:
    val := adc / (3300/19) * resolution
    

    Andy
  • jeff-ojeff-o Posts: 181
    edited 2010-12-15 06:49
    Hey, thanks for the quick replies.

    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.
Sign In or Register to comment.