 |
Working with pins
The only way a microcontroller can interface with the external
world is via its pins. Though the pins are grouped into ports for
programming convenience, yet for many applications one needs to
access the pins individually. So
- during output one needs to
- write 1 to some pins of a port without changing the other
pins,
- write 0 to some pins of a port without changing the other
pins,
- write a binary pattern to some pins of a port without changing the remaining
pins,
- toggle some pins of a port without changing the other
pins,
- during input one needs to
- check if some pins of a port are 1
- check if some pins of a port are 0
- check if some pins of a port have some specific binary pattern
We discuss these one by one.
Output
Write 1 to some pins without changing the rest
Suppose that we want to write 1's to pins 2,3 and 7.
unsigned char mask = (1<<2) | (1<<3) | (1<<7);
PORTB |= mask;
Write 0 to some pins without changing the rest
Suppose that we want to write 0's to pins 0,3 and 7.
unsigned char mask = (1<<0) | (1<<3) | (1<<7);
PORTB &= ~mask;
Write a binary pattern to some pins without changing the
rest
Suppose that we want to write 1's to pins 2,3, and 0's to pins 4
and 7.
unsigned char mask1, mask0;
mask1 = (1<<2) | (1<<3);
mask0 = (1<<4) | (1<<7);
PORTB = (PORTB | mask1) & ~mask0;
Toggle some pins without changing the rest
This is a rare requirement. But it is easy to do, anyway.
Suppose that we want to toggle pins 0,3 and 7.
unsigned char mask = (1<<0) | (1<<3) | (1<<7);
PORTB = mask;
Input
Check if some pins of a port show 1
Suppose that we want to check if the pins 0, 2 and 7 show 1.
We can use
unsigned char mask = (1<<0) | (1<<2) | (1<<7);
if((PINB & mask) == mask) {
...
}
Check if some pins of a port show 0
Suppose that we want to check if the pins 0, 2 and 7 show 1.
We can use
unsigned char mask = (1<<0) | (1<<2) | (1<<7);
if((PINB & mask) == 0) {
...
}
Check if some pins of a port show a given binary
pattern
Suppose that we want to check if the pins 0, 2 and 7 show 101.
We can use
unsigned char mask, posMask;
posMask = (1 << 0) | (1 << 2) | (1 << 7);
valueMask = (1 << 0) | (1 << 7);
if((PINB & posMask) == valueMask) {
...
}
|