9

I read here that I could toggle the state of a GPIO pin set to output in Python using the following command:

GPIO.output(LED, not GPIO.input(LED))

where LED is the pin value. I can turn the LED on using the following code:

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
LED = 17
GPIO.setup(LED,GPIO.OUT)
GPIO.output(LED,True)

But when I try GPIO.output(LED, not GPIO.input(LED)), the following error is thrown.

RPi.GPIO.WrongDirectionException: The GPIO channel has not been set up or is set up in the wrong direction

Am I supposed to set up the GPIO channel differently from above or is the site I referenced posting incorrect information?

2 Answers 2

13

You can't read an output. Just store the state of the pin in a variable.

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
LED = 17
ledState = False
GPIO.setup(LED,GPIO.OUT)

ledState = not ledState
GPIO.output(LED, ledState)
8

Although stated elsewhere, you CAN read an output by just inputting the same GPIO pin and get the value returned you just set out before:

GPIO.setup(LED_red, GPIO.OUT) #set Pin LED_red as aoutput

GPIO.output(LED_red, GPIO.HIGH) #set Pin LED_red = HIGH (ON)

GPIO.input(LED_red) returns 1 
1
  • Indeed you can read an output port. However note that if you do that from a different process and then call GPIO.cleanup(), this will result in the port changing state to zero. Commented Mar 12, 2020 at 7:02

Your Answer

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

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