Hardware Reference
In-Depth Information
print “The mouse has been clicked at “,x,y
if x in range(50,90) and y in range(50,110) :
box = not box # toggle the state of the box
drawBox(box)
def terminate(): # close down the program
print (“Closing down please wait”)
pygame.quit()
sys.exit()
def checkForEvent(): # see if we need to quit
# or look at the mouse
#print “checking for quit”
event = pygame.event.poll()
if event.type == pygame.QUIT :
terminate()
elif event.type == pygame.MOUSEBUTTONDOWN :
mouseGet()
elif event.type == pygame.KEYDOWN
↵
and event.key == pygame.K_ESCAPE :
terminate()
if __name__ == '__main__':
main()
When you run this, you will get a much smaller window on the desktop with a single square
in it. Click in the square, and four things will happen. First the square will turn from grey to
red, and then you will hear the relay on the PiFace board come on and see one of the LEDs
come on. Finally you will see the position of the mouse when it was clicked printed out in
window coordinates. That means that the coordinate value will be the same when clicking
the same spot within the window, irrespective of where that window is positioned on the
screen. Let's see what's been done here.
This time you add in the call to import the
piface
library, which is going to control the relay
and lights. You set a variable called
box
to be false, which is called a
logic
or
Boolean value
and
can only take on one of two values. You can call these values one and zero or true and false.
The main function calls a
drawBox
function and then enters an endless loop that simply
checks the events.
Take a closer look at the
drawBox
function. It takes in a variable, called
state
, that defines
what colour the box is going to be. It is tested and you use the draw rectangle command from
pygame
. At first this looks complex, with lots of parameters or numbers in it, but it is quite
simple. The first parameter in the command tells where you are going to draw the rectangle, in
this case in an area called
screen
you defined at the start of the program. The next three