2

I'm writing a program to run on my Raspberry Pi, and I can't seem to get past this pesty syntax error. Here's my code:

import RPi.GPIO as GPIO, time

GPIO.setmode(GPIO.BCM)

GPIO.setup(14,GPIO.OUT)

GPIO.output(14,GPIO.HIGH)

def RCtime (PiPin):
  measurement = 0
  # Discharge capacitor
  GPIO.setup(PiPin, GPIO.OUT)
  GPIO.output(PiPin, GPIO.LOW)
  time.sleep(0.1)

  GPIO.setup(PiPin, GPIO.IN)
  # Count loops until voltage across
  # capacitor reads high on GPIO
  while (GPIO.input(PiPin) == GPIO.LOW):
    measurement += 1

  return measurement

# Main program loop
while True:
  print RCtime(4) # Measure timing using GPIO4

except KeyboardInterrupt:
  GPIO.cleanup()

Returns the following error:

File "measure.py", line 28
    except KeyboardInterrupt:
         ^
SyntaxError: invalid syntax

I can't seem to find the problem. Can anyone help?

4
  • 4
    You do not have the matching try part of the try-except statement. Commented Apr 19, 2017 at 2:29
  • try-except returns the same error. @DYZ Commented Apr 19, 2017 at 2:31
  • 1
    Please update the code, then, and include the new error message. What you have shown us so far is definitely incorrect. Commented Apr 19, 2017 at 2:32
  • For GPIO cleanup, it's a good habit to use try...finally instead anyway. That way if the program exits normally (not possible in this program, but is in others) the cleanup still happens. Also you don't lose your error, which helps a lot when it comes to debugging... Commented Apr 19, 2017 at 3:05

2 Answers 2

2

Since the term is called a try...except statement, you must have a try keyword. Wrap the try...except around the lines you wanted to error handle. Note: you should wrap as less as possible:

while True:
  try:
    print RCtime(4) # Measure timing using GPIO4
  except KeyboardInterrupt:
    break # break the while loop
  finally:
    GPIO.cleanup() # GPIO clean up

Edit: as suggested, the GPIO cleanup should be ran regardless if there's an exception, you should place the cleanup operation inside the finally clause.

Sign up to request clarification or add additional context in comments.

1 Comment

Usually I would agree that you want to keep as little as possible inside the exception catching scope - but in this case, we would always want the cleanup to run. So wrapping the entire program in this is not a bad idea.
0

You should put your function in the try block:

# Main program loop
try:
    while True:
        print RCtime(4) # Measure timing using GPIO4
except KeyboardInterrupt:
    GPIO.cleanup()

I think this will work.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.