Using Ports

In the previous sketch, outputs were controlled one at a time using the digitalWrite() function. But a sketch can change several outputs all at once.

Binary numbers

A program can specify numbers as a sequence of binary digits. Instead of writing x=4, we can write x=B100.

There are 8 bits in a byte. They are numbered right to left so that binary digits correspond to powers of two in the same way decimal digits correspond to powers of ten.

Memory mapped I/O

Some computers are designed so that a program writes to a special memory location in order to send signals to I/O pins.

The Atmel processor on Arduino boards has a special place in memory, Port B, that corresponds to I/O poins 8 through 13. Actually there are three locations in memory that relate to those pins. In each location, each bit corresponds to a pin. Bit 0 corresponds to pin 8, 1 to pin 9, etc.

Bits 7 and 8 aren't connected to any pins.

Output register

The name of the output register for Port B is PORTB. When a program writes a value to that location, all the bits are sent to the corresponding pins. For example:

PORTB = B000111

would set the pins corresponding to bits 0, 1 and 2 of Port B to HI and light LEDs 0, 1 and 2.

Data direction register

Instead of using the pinMode() function, a program can set up pins 8 though 13 as ouput all at once with this:

PORTB = B111111

Input register

This sketch doesn't use the input register. That is a special location for to receive the state of input pins. Just for completeness, it's PINB

This sketch

In the serial port, enter a number 0 to 5. The corresponding LED will go on. All the others will go off.