Trouble coding an LED selector in Python
Question: I have 4 LEDs connected to GPIO outputs of a Raspberry Pi. I want to use the
argv command so that I can select the LEDs using a simple binary code. For
example:

python test.py 1010

This would light up the first and third LEDs in the row. The problem is I
don't think Im approaching this correctly. Here is my code so far

    
    
    from sys import argv
    import RPi.GPIO as GPIO
    
    GPIO.setmode(GPIO.BOARD)
    
    GPIO.setup(11, GPIO.OUT)
    GPIO.setup(12, GPIO.OUT)
    GPIO.setup(13, GPIO.OUT)
    GPIO.setup(15, GPIO.OUT)
    
    x, y = argv
    
    print "Script:", x
    
    if y == '0000':
        GPIO.output(11, 0)
        GPIO.output(12, 0)
        GPIO.output(13, 0)
        GPIO.output(15, 0)
    
    if y == '0001':
        GPIO.output(11, 0)
        GPIO.output(12, 0)
        GPIO.output(13, 0)
        GPIO.output(15, 1)
    
    
    GPIO.cleanup()
    

Im leaving out the rest of the combinations so I dont bloat this question. Im
running into several syntax issues, but Im wondering if I should just scrap
this and go about it another way. Im new and any advice would be appreciated.


Answer: It sounds very much like what you really want is to map the pieces of your
input string to the values of your calls to `GPIO.output`. You can do that
easily (and with far less code than you currently have) by iterating over the
control string:

    
    
    led_map = {
        # This maps each "bit" of your input string to the correct ID for GPIO.
        0 : 11,
        1 : 12,
        2 : 13,
        3 : 15
    }
    
    for i in xrange(len(y)):
        bit = y[i]
        GPIO.output(led_map[i], int(bit))
    

This setup prevents you from having to code each permutation separately (which
quickly becomes terrible even with only two or three bits, let alone four or
more). Rather than thinking in terms of permutations, you can just consider
the bits individually, and perform the appropriate functions on each of them
in turn.

