DDRA = 0x72;
The value 0x72 is the value
, represented by
a hexadecial number.
While simple assignment statements are useful for the initialization of port pins, they are not suitable when only one bit needs to be changed. For example, if we only need to change the state of pin 4 of port A so it drives high (assuming it is already configured for output), we should not use the following statement:
PORTA = 0x10;
This is because this statement also affects pins 0, 1, 2, 3, 5, 6 and 7 of port A! Fortunately, PORTA is a read/write variable. We can read it back first, then use bitwise operators to change only the bits that we want to change. In this example, we should use the following statement to make pin 4 drive high:
PORTA = PORTA | 0x10;
This works because when a bit is ored with 0, the original value is preserved. To change pin 2 to drive low (assuming it is already configured for output), we can use the following code:
PORTA = PORTA & ~0x04;
The ~ operator means bitwise not. It is also called
one's complement. Essentially, ~0x04 is the same as
0xfb, but the former is easier to read because it is more
clear which bit is a 1. Note that any bit anded with 1 prserves
its original value, and that's why this operation does not
the configuration of pins other than pin 2.
For the C savvy programmers, you can also replace the previous simple assignment operators with the operator-assignment operators:
PORTA |= 0x10; PORTA &= ~0x04;
If you'd rather let the compiler figure out the bit pattern (from
the pin number), you can use the left-shift operator <<' as
follows:
PORTA |= 1 << 4; PORTA &= ~(1 << 2);
Copyright © 2006-02-15 by Tak Auyeung