Hardware Reference
In-Depth Information
If you have a single bit to store, the easiest way is just to code it as a byte, even
if you use 1 out of 8 bits.
If you have several bits to store, you might want to try storing them all in
1 byte to save space, for example, a notii cation LED that the user can program
as he wants. If this is an RGB LED, the user can choose a mix of any primary
colors for notii cation. This can be coded into 3 bits; 1 for red, 1 for green, and
1 for blue. A logical 1 means the color is present, and a logical 0 means the color
is not present.
You can dei ne this as follows:
// primary colors
#define BLUE 4 // 100
#define GREEN 2 // 010
#define RED 1 // 001
Did you note that RED was dei ned as 1, and has the number 001 next to it?
Arduinos, like all computer systems, store data as binary—a collection of ones and
zeros. It is critical to understand binary when performing bitwise calculations.
Binary is a base-two system; that is to say that each digit can take one of two
possible values—0 or 1. The rightmost i gure corresponds to 2
0
, the number to
its left corresponds to 2
1
, the next one to 2
2
, and so on. In this example, I have
used three specii c values: 1, 2, and 4. I did not use 3 since in binary, 3 is written
as 011, and I wanted each color to be assigned to a bit.
There are i ve more bits that could be coded into this byte. Each bit could
indicate another behavior; maybe the LED should blink? Or maybe a warning
beep? You can make this decision.
Also, another important part of bitwise calculations is
AND
and
OR
. In binary
logic, a result is
TRUE
if one value
AND
the second value are both
TRUE
.
TRUE
and
TRUE
would result in
TRUE
, but
TRUE
and
FALSE
would result in
FALSE
. A result
is
TRUE
if one value
OR
another value is
TRUE
. 1
OR
1 is
TRUE
, as is 1
OR
0, but
0
OR
0 is
FALSE
.
Let's imagine you want a cyan light to be lit up if something occurs. Cyan is a
mix of green and blue. In English, you would say that you want green and blue,
but in computer logic, you would say that you want
GREEN
or
BLUE
. A logical
OR
is true if one of the two values being compared is true. In this case, GREEN
(010) is compared to BLUE (100), and the answer becomes 110.
So, the result, called
CYAN
, is 110, but now that you have encoded that, how
can you get the data out of it? This time, you will be using a logical
AND
. A
logical
AND
is true if the both the values being compared are true. So,
CYAN
AND
BLUE
?
CYAN
has a value of 110, and the value of
BLUE
is 100. The leftmost bit is
1 in both, so that will return as a 1. The second bit is 1 in
CYAN
and 0 in
BLUE
.
It returns 0. The third bit is 0 in both values; it also returns 0. The result is 100.
You can now say that
BLUE
is present in
CYAN
because the result was not zero.
Search WWH ::
Custom Search