The Bitwise XOR Operator
The XOR operator (^) returns a 1 result if the bits are different and a 0 result if they are the same.
Using our demonstration bytes again,
byte a = B00111100; byte b = B01011010; byte c = 0;
the result of the comparison
will be 01100110.
The Bitwise NOT Operator
The NOT operator (~) simply reverses, or flips, the bits in each column: 0s are changed to 1s, and 1s are changed to 0s. Consider this example: If we store a bitwise NOT of byte a in byte b like so,
byte a = B00111100; byte b = 0; b = ~a;
then b contains 11000011.
Bitshift Left and Right
The bitshift left (<<) and bitshift right (>>) operators move bits to the left or right by a certain number of positions. For example, if the contents of a are shifted left four spaces, like so,
byte a = B00100101; byte b = a << 4;
then the result is the value 01010000 for b. The bits in a are moved left four spaces, and the empty spaces are filled with 0s. If we shift in the other direction, like so,
byte a = B11110001; byte b = a >> 4;
then the value for b will be 00001111.
project #21: creating an led matrix
The purpose of this project is to demonstrate the use of the LED matrix; we’ll turn on every second column and row in the matrix, as shown in Figure 6-20.
Figure 6-20: Checkerboard matrix template
To create this display pattern, we’ll send B10101010 to the rows shift register and ~B10101010 to the columns shift register. The 1s and 0s in each byte match the rows and columns of the matrix.
note Note the use of the bitwise NOT (~) on the columns byte. A columns shift register bit needs to be 0 to turn on an LED from the column connections. However, a rows shift register bit needs to be 1 to turn on the LED from the rows connections. Therefore, we use the bitwise arithmetic ~ to invert the byte of data being sent to the second shift register that drives the columns.
To create the effect shown in Figure 6-20, use the following sketch:
// Project 21 – Creating an LED Matrix
#define DATA 6 // connect to pin 14 on the 74HC595
#define LATCH 8 // connect to pin 12 on the 74HC595
#define CLOCK 10 // connect to pin 11 on the 74HC595
void setup()
{
pinMode(LATCH, OUTPUT); pinMode(CLOCK, OUTPUT); pinMode(DATA, OUTPUT); }
void loop()
{
digitalWrite(LATCH, LOW);
shiftOut(DATA, CLOCK, MSBFIRST, ~B10101010); // columns shiftOut(DATA, CLOCK, MSBFIRST, B10101010); // rows
digitalWrite(LATCH, HIGH); do {} while (1); // do nothing }
The result is shown in Figure 6-21. We have turned on every other LED inside the matrix to form a checkerboard pattern.
Figure 6-21: Result of Project 21
Do'stlaringiz bilan baham: |