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?

Peter Mortensen
  • 2,004
  • 2
  • 15
  • 18
bobthechemist
  • 546
  • 1
  • 6
  • 17

2 Answers2

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)
Gerben
  • 2,420
  • 14
  • 17
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 
HeatfanJohn
  • 3,125
  • 3
  • 24
  • 36
user14486
  • 81
  • 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. – Diomidis Spinellis Mar 12 '20 at 07:02