I am trying to write the following program (8Relay.py) using python on the Raspberry Pi.

I want to use the input from a GPIO pin to turn an LED on or off, depending on what input was pressed (1~8).

For example, if I input 17, GPIO17 should be turned on. When I input 17 again, GPIO17 should be turned off. This is what I want.

I'm not quite sure how I should go about doing this. My current code is listed below:


#! /usr/bin/python

import os, sys, time
import RPi.GPIO as GPIO

Relays = [False, False, False, False, False, False, False, False]


GPIO.setup(17, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(27, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)
GPIO.setup(25, GPIO.OUT)
GPIO.setup(4, GPIO.OUT)

G1 = 17
G2 = 18
G3 = 27
G4 = 22
G5 = 23
G6 = 24
G7 = 25
G8 = 4

for A in [17, 18, 27, 22, 23, 24, 25, 4]:
    GPIO.output(G1, 0)
    GPIO.output(G2, 0)
    GPIO.output(G3, 0)
    GPIO.output(G4, 0)
    GPIO.output(G5, 0)
    GPIO.output(G6, 0)
    GPIO.output(G7, 0)
    GPIO.output(G8, 0)

def Toggle(Relay):
    Current_situation = Relays[Relay]
    print Relays[Relay]
    Relays[Relay] = not Current_situation
    GPIO.output([17, 18, 27, 22, 23, 24, 25, 4][Relay-1], not Current_situation)

Choice = "True"
while Choice:
    for A, B in enumerate(Relays):
        if B:
            B = "High"
            B = "Low"
        print "Relay({}) [{}]".format([G1, G2, G3, G4, G5, G6, G7, G8][A], B)

    Choice = int(input("GPIO number :"))
    if Choice >= 1 and Choice <= 8 :
    print "Something Failed."
  • Hi, welcome to Raspberry Pi StackExchange! I'm not 100% sure what you're trying to say, so I read your question and code and suggested an edit to your question in order for it to make a bit more sense. If I've misunderstood you at all, feel free to change it back. Also, just to clarify, is this what the program is meant to do? There is an LED which is connected to each of the GPIO pins in the order you specified, and when the user types a number into the console, the LED should toggle on/off? Sep 12, 2017 at 9:02

1 Answer 1


Ok, so you're trying to do a state machine. There is a lot of ways to do this, but what you can do it's keep a boolean variable for each of the pin that you want to change.

Then, detect using input what gpio the user wants to change the state and "flip" the value on the state variable, something like:

if gpioState is False:

Then, run a loop through all gpios using the boolean variables as the second parameter, like:

GPIO.output(G1, gpioState)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.