Menu

More elegant way of nesting multiple If...Then statements?

Help
mkstevo
2016-09-15
2016-09-19
  • mkstevo

    mkstevo - 2016-09-15

    I'm building a module that checks the colour of some plastic balls presented to it, as part of a larger project.

    I'm using a TCS3200 module which gives an output in frequency, proportional to the intensity of the reflected light detected. This has selectable filters of Red, Green, Blue and Clear which can be selected before a reading is taken.

    I'm selecting a filter (say red for a start) then counting the number of pulses within a loop, incrementing the 'red' variable each time to give the intensity of the reflected red light, before selecting the next filter (green then blue then clear) and again counting the pulses in a loop. This leaves me with four values which have the light intensity for the primary colours as well as an unfiltered light value.

    To determine the colour of the ball presented, I created a spreadsheet with the values from various samples and estimated the high/low thresholds for each colour ball, for each filtered value. I'm left with something like the following:

    If Red > 100 and Red < 120 Then
        If Grn > 320 and Grn < 345 Then
            If Blu > 175 and Blu < 205 Then
                If Clr > 1535 and Clr < 1570 Then
                    Let Detect = DGrn 'Green ball detected
                End If
            End If
        End If
    End If
    

    This is repeated with the different values representing the different ball colour intensities detected.

    While it works, the multiple nested If...End If statements seem rather cumbersome and I wondered if it could be improved upon. I considered using some sort of look up table, but couldn't see how I could make it work with the range of values which run from around 145 up to 4000.

     

    Last edit: mkstevo 2016-09-15
  • Peter

    Peter - 2016-09-15

    Can you write a custom function:

    Function get_colour(R, G, B)

    Return(0|1|2) '1=red, 2=green, 3=blue

    End function

    Then have a select case to perform an action based on the colour?

    Edit: maybe using SELECT in the function will work as a crude elseif?

     

    Last edit: Peter 2016-09-15
  • mkstevo

    mkstevo - 2016-09-19

    Thanks for your thoughts. I'll try putting the If ... Then statements into a function and return the value of detected colour.

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.