by Joe Pardue
Get started now with this
series! Joe’s book & kit are
available in our webstore at
www.nutsvolts.com
PART 5:
There are exactly 10 types of people in
the world: those who understand
binary and those who don’t.
Last month, we learned some more C syntax, a
bit about libraries, and taught our Butterfly to talk.
This month, we are going to learn what the heck
that button in Figure 1 means. AND, the first binary
1000000 folks who ask will get the button for free.
See www.smileymicros.com for details. If this doesn’t
make sense to you now, it will in a minute (or two).
Bitwise Operators
Bitwise operators are critically important in
microcontroller software. They allow us to do many things
in C that can be directly and efficiently translated into
microcontroller machine operations. This is a dense topic,
so get out a pencil and piece of paper and work through
each of the examples until you understand it.
In case you’ve ever wondered how to tell what is true
and what is false — well for bitwise operators which use
binary logic (single bits) — 1 is true and 0 is false.
We discussed binary vs. hexadecimal vs. decimal
in Workshop 3, but to refresh: A byte has 256 states
numbered 0 to 255. We number the bits in a byte from
the right to the left as lowest to highest:
bit 76543210
myByte = 01010101 binary = 0x55 hexadecimal = 85
decimal
Look at the truth tables for AND ‘&’, OR ‘|’, XOR ‘^,’
and NOT ‘~:’
AND
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
OR
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
XOR
0 0 = 0
0 1 = 1
1 0 = 1
1 1 = 0
NOT
~1 = 0
~0 = 1
Now memorize them. Ouch, but yes, I am serious.
■ FIGURE 1. Ten types of people.
ORing
We can set bit 3 to 1 in a variable, myByte, by using
the Bitwise OR operator: ‘|’
myByte = 0;
myByte = myByte | 0x08;
To see what’s happening, look at these in binary:
bit 76543210
myByte = 00000000 = 0x00
0x08 = 00001000 = 0x08
————————————
OR = 00001000 = 0x08
We see that bit 3 is 1 in 0x08 and 1 | 0 = 1, so we
set bit 3 in myByte.
Suppose myByte = 0xF7:
December 2008 57