Question

Can you tell me where the syntax error in this code is??

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)

GPIO.setup(4, GPIO.IN)

try: 
    while True:
        if (GPIO.input(4) == 1):
            print "button pressed"
        else:
            print "he"
GPIO.cleanup()

it should print button pressed when the gpio pin on my raspberry pi gets power when the button on the board is pressed. but i get an error all the time i run the code in the console running raspbian. most of the errors say "invalid syntax" and than the last codeline of the script.

Was it helpful?

Solution

You have a try with no except clause. You need something like:

try:
    while True:
        if (GPIO.input(4) == 1):
            print "button pressed"
        else:
            print "he"
except:
    # handle exception here
    pass # if you want to ignore it
GPIO.cleanup()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top