Hardware Reference
In-Depth Information
three intensities and inally the blue colour in three intensities. If you don't see this, check
the wiring, soldering and PiFace connections.
he colour changing the state of the input switches is checked, and a message is printed out
if a button is held down. You will notice there is some bit manipulation code in this part that
you might not have come across before - the use of the bitwise AND operation; in Python and
many other languages the symbol to do this is the ampersand ( & ). Basically, an AND opera-
tion is used to selectively zero bits so that you are left with just the bits you are interested in.
he AND operation is performed between two numbers or bit patterns; one is called the sub-
ject and the other the mask, although these names are arbitrary. he AND rules are simple:
here will be a logic one in the result if there is a logic one in that bit position in both the
subject AND the mask. So if you have a zero in the mask, you have a zero in the result; if you
have a one in the mask, you will have that position in the result, depending on what the bit
was in the subject. In efect you use it for selectively clearing bits. So the line
switchState = pfio.read_input() & 3
sets the variable switchState to whatever is on the two least signiicant bits of the PiFace
input connectors. he 3 is the mask that is zeroing out all the other bits except bits zero and
one. If you write the number 3 in binary, you will see that it looks like 0000011, with ones in
the positions you are interested in. To test a bit, you can use another AND operation; the line
if switchState & 1 :
takes the switchState variable and AND s it with 1 (or in binary, 00000001). If the result of
doing this is a zero, the if operator sees a false; with any other result, it sees a true. So there
is no need, for example, to say in this line
if (switchState & 1) == True :
although the result would be the same. he same augment applies to looking at the switch on
bit 1: You simply AND the switchState variable with the number 2 (or in binary, 00000010).
Now go on and succumb to the temptation of showing all the colours just for fun. he simpli-
ied program in Listing 8-2 does this.
Listing 8-2 Colour Snap Hardware Test 2
#!/usr/bin/env python
“””
Colour Snap test 2
continued
Search WWH ::




Custom Search