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
  • 18

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
  • 16
  • 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,115
  • 3
  • 26
  • 38
user14486
  • 81
  • 1
  • 1