1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Wow this is excellent! I had no idea I could break a string down like this. Its been incredibly helpful! The one odd thing it did tho is it only flashed the LEDs very briefly. I looped the last portion of your code here to make it steady. Could I have done something else?
@user2237256 I'm not certain, because I've never actually worked with RPi, but that sounds like the correct way to do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.