Hardware Reference
In-Depth Information
continued
input” means that the pin is not actively trying to control the circuitry any more.
If you accidentally short an output pin to another pin when connecting or dis-
connecting, you can damage the circuitry. To prevent this from happening, it is
good practice to make your program call the GPIO.cleanup() function, so
that accidental short circuits when making changes to your circuit have no
chance of damaging the circuitry.
But you have a problem: because you have put while True: in your Python
program, it means that your program is in an infinite game loop. The only way to
break out of this program is to press CTRL+C or to stop the program from the
IDLE menu. But when you stop a program that way, it just stops immediately.
Don't worry—there's a way to deal with this too, and it involves try/finally ,
which is what is known as an exception handler. You won't be learning about
exception handlers in any detail in this topic, but you can't avoid using them
with GPIOs! Basically, when you press Ctrl+C or stop the program from the
IDLE menu, Python generates an exception called KeyboardInterrupt and
the program stops. Using try/finally is a little programmer's trick that
allows your Python program to detect that your program has stopped. After the
finally statement you can put any Python code that needs to run to clean up
before it finally finishes. So, you press CTRL+C or stop the program from the
IDLE menu, the program jumps to the code in the finally: block and runs
that, then it finishes. This ensures that GPIO.cleanup() is always called and
that the GPIO pins are always left in a clean and safe state when your program
has finished.
I won't really go into exceptions in any great detail in this topic, but you can read more
about them here: https://wiki.python.org/moin/HandlingExceptions
Secondly, what is sudo for on the Raspberry Pi, and why do you have to run
your GPIO programs from within LXTerminal?
All hardware on the Raspberry Pi is protected so that it cannot normally be
accessed by the normal pi user that you log in as, but you have to have super-user
privileges instead. sudo means “substitute user and do, which basically changes
your user from pi to root (the super user) and then runs your testLED.py
program inside the Python language. This means that your program can access
the protected GPIO hardware. If you don't run your GPIO programs in this way on
the Raspberry Pi, you will get an error.
When writing this topic I tried to ind a clear explanation of sudo , but interest-
ingly, all my Google searches ended up taking me to a page on my blog, which
seems quite popular! You can read all about sudo and its uses here: http://blog.
whaleygeek.co.uk/sudo-on-raspberry-pi-why-and-why-you-need-to-ask-kids-too.
Search WWH ::




Custom Search