简体   繁体   中英

Python for loop accessing GPIO pins

I'm new to Python and the Raspberry Pi. I'm trying to shorten my code and use for loops for repetitive parts in my code, like changing all pins to high and low.

I'm trying to use a for loop to access pins. Is this even possible?

import RPi.GPIO as GPIO
from time import sleep

R1=22
R2=10
R3=9
R4=11

GPIO.setup(R1, GPIO.OUT)
GPIO.setup(R2, GPIO.OUT)
GPIO.setup(R3, GPIO.OUT)
GPIO.setup(R4, GPIO.OUT)

for x in range(1, 5):
    print "We're on time %d" % (x)
    GPIO.output(R + %d % (x), GPIO.HIGH)
    sleep(1)
    GPIO.output(R + %d % (x), GPIO.LOW)
    sleep(1)

GPIO.cleanup()

That sort of thing is possible, but often nicer to use a list or dict :

pins = [22, 10, 9, 11]

for pin in pins:
    GPIO.setup(pin, GPIO.OUT)

for x in range(1, 5):
    GPIO.output(pins[x], GPIO.HIGH)
    sleep(1)
    GPIO.output(pins[x], GPIO.LOW)
    sleep(1)

You can't create variable names like that. You have to have the same variable name and change what it is pointing to:

pins = [R1, R2, R3, R4]

for pin in pins:
    GPIO.setup(pin, GPIO.OUT)

for pin in pins:
    GPIO.output(pin, GPIO.HIGH)
    sleep(1)
    GPIO.output(pin, GPIO.LOW)
    sleep(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM