Hardware Reference
In-Depth Information
if VERBOSE_MODE:
print “Chicken has stopped wobbling.”
def say(self, text_to_say):
#Makes the chicken say something
if VERBOSE_MODE:
print “Chicken says: %s” % text_to_say
talker.say(text_to_say)
def test_chicken():
#create a sample Chicken object called tweetyPi
tweetyPi = Chicken(pfio,1)
tweetyPi.start_wobble()
tweetyPi.say(“hello world”)
tweetyPi.stop_wobble()
if __name__ == '__main__':
test_chicken()
With a speaker connected, run the preceding script and check that it works. You should hear
the relay click (and see the corresponding LED illuminate) on the PiFace interface, the sound
“hello world” come from the speaker and then the relay click off again.
Looking back at the code, there are a couple of points to notice. The line VERBOSE_MODE =
True is an example of a constant. It is set by the programmer and then never changes - in other
words, it remains constant. In this case, it provides an easy way to turn on and off debugging
information in one place. With it turned on, you'll receive messages saying when the chicken
should start moving and stop. Without these messages, if the chicken wasn't moving, you
wouldn't know if the problem was with this module, or whether the problem was elsewhere.
Being able to see what is going on in a program is very important when debugging. Computer
scientists describe it has having good visibility . One way to achieve this is to have print
statements at key points in a program so as it executes you can follow its progress and the state
of data. It's very common for a program to not work perfectly the first time, so designing it to make
it easy to debug can save time in the long run, particularly when you might add a new feature later.
TIP
Creating Classes
The file chicken.py makes uses a particular style of programming called object-orientated
programming (OOP) . You don't need to worry too much if you don't understand the code at
the moment.
 
Search WWH ::




Custom Search