Shop OBEX P1 Docs P2 Docs Learn Events
How to group inputs for IF statements? — Parallax Forums

How to group inputs for IF statements?

Chad1Chad1 Posts: 26
edited 2015-04-08 20:25 in General Discussion
Hey everyone,

Let's say I have ten switches, and any time one of them is high I want to turn on an LED. Instead of writing something like this in SPIN...

repeat
if (ina[SW1] == 1) or (ina[SW2] == 1) or (ina[SW3] == 1) or ... or (ina[SW10] == 1)
***Turn on LED***

...could I write something like this? (Pseudocode for the sake of clarity)

InputGroup = [SW1, SW2, ... , SW10]

repeat
if InputGroup == 1
***Turn on LED***

Thanks in advance for your help!

Comments

  • ElectrodudeElectrodude Posts: 1,658
    edited 2015-04-08 19:04
    You can read a range of IO lines with ina[last..first] (please correct me if the order is wrong). You'll get them as one binary number. If all of the inputs are 0, you'll get %0000000 == 0, otherwise you'll get something that's not 0. The condition to an "if" is true if it's not 0, so all you have to do is this:
    repeat
      if ina[lastswitch..firstswitch]
        ' turn on LED
    

    To make code appear how I did it, retaining indentation and such, put it in [noparse]
    code tags like this
    
    [/noparse].

    EDIT:
    Here's a more advanced solution that doesn't need contiguous pins and tells you which pins are on:
    CON
    
      ' let's say we care about inputs on pins 1, 2, 3, 5, 8, 11, 14, and 18; those bits are all set in pinmask
      pinmask = %00000000_00000100_01001001_00101110
    
    PUB switchmonitor | ins, pinno
    
      repeat
        ins := ina & pinmask  ' capture the inputs we care about
    
        repeat while ins      ' while there are more inputs to process
          pinno := (>| ins)   ' get the id of the highest pin that's on
          ins &= ! |< pinno   ' mark the pin as processed (clear bit pinno of ins)
    
          ' pin #pinno is on, do something about it
    
  • JonnyMacJonnyMac Posts: 9,105
    edited 2015-04-08 19:05
    In my designs I try to make a group of inputs like this contiguous. Did you do that, or are they spread out all over the place?
  • Chad1Chad1 Posts: 26
    edited 2015-04-08 20:25
    Thanks! Figured it was easy :)
Sign In or Register to comment.