We want to set pins 0,2,5 to low and 1,3,4,6,7 to high.
How?
- Binary number (works only on certain gcc compilers)
PORTD = 0b11011010;
- Hexadecimal number
PORTD = 0xDA;
Changing a value of a specific bit to high. Let’s assume, our register looks like PORTD: 11011010 and we want only to change the value of the 2nd bit to one. We can use Boolean algebra disjunction like
PORTD |= (1 << bit_number);
In this case:
00000100 |
11011110 (result)
// set second bit high PORTD |= (1 << 2);11011010
00000100 |
11011110 (result)
We can also change several bits at the same time:
// sets pin 4 and 5 to logical one PORTD |= (1 << 4) | (1 << 5);
Changing a value of a specific bit to low. It works almost the same as in the example above, except that logical conjunction and negation is used. When changing 3rd bit of PORTD to zero, the pattern looks like:
PORTD &= ~(1 << bit_number);
So:
//sets third bit low PORTD &= ~(1 << 3);
11011010
11110111 &
11010010 (result)
11110111 &
11010010 (result)
To change more than one bit, we use:
// sets pins 6 and 7 to logical zero PORTD &= ~((1 << 6) | (1 << 7));