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?

12

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 

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.