Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 1251

Python • Cleanest way to turn on GPIO based on input string

$
0
0
Hello, All.

I have a (silly?) question.

Let's say I have a variable:

Code:

led = 12
such that the following command would turn on an LED at pin 12:

Code:

GPIO.output(led, GPIO.HIGH)
Very simple.

Now, what if I had a list of strings (in this case, from a .csv file) of different variable names. And as I iterated through those variable names, I would want to turn ON/OFF the respective accordingly.

It would be very easy to do the following:

Code:

if input == "led":GPIO.output(led, GPIO.HIGH
However, if there were 1000 different variables, this would be less than ideal. I suppose that a slightly cleaner method would be switch-statement, however I still feel this is not ideal.

Assuming that every string in my list correctly equals a variable that references a GPIO pin (ie, led1, led2, etc...) is there a way to convert the current string to a literal? So that we end up with something like:

Code:

myString = 'led'GPIO.output(someConversion(myString), GPIO.HIGH)
I understand that the simpilest way would be to just have a list of integers, each representing their respective GPIO pins, however for the sake of future debugging and readability, I don't want to do this.

ONE POSSIBILITY, would be to add an additional column in my .csv file with a corresponding pin. Maybe even some sort of translation table, like a dictionary. I'm just curious if there's a more elegant way, like the one I described above.

Any suggestions are appreciated.

Thank you,
Joe

Statistics: Posted by joebro391 — Mon Mar 24, 2025 1:00 am



Viewing all articles
Browse latest Browse all 1251

Trending Articles