3

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()
Greenonline
  • 1,330
  • 8
  • 23
  • 31
GuysmileZ
  • 31
  • 1
  • 2

2 Answers2

0

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)
101
  • 8,514
  • 6
  • 43
  • 69
0

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)
Peter Wood
  • 23,859
  • 5
  • 60
  • 99