If you've coded PICs before Arduinos one of the things you might have noticed is the lack of function on the latter to manipulate multiple pins at once. Manipulating all the Arduino pins at once is needed, for example, when using a seven-segment display or creating strobe lights. Is there a way to read/write multiple pins at once in Arduino?
Contents
Toggle
The Arduino Pins
Arduino Pins Example
Displaying All Digits
The Final Code
The Arduino Pins
The Arduino, which uses the ATMega328p, is actually the same as a PIC16F877A when it comes to pin manipulation. You only need to specify the name of registers that control the physical ports (or pins). Take a look at the pin mapping of the ATMega328 with the corresponding Arduino pins:
Here you will see that the pins are grouped as power pins, PORTB, PORTC and PORTD.
Each PORT has a corresponding DDR (data direction register) that specifies whether a pin on that port is output or input. A "1" on the DDR pin corresponds to an output on the PORT pin. A "0" on the DDR pin corresponds to an input on the PORT pin.
For example, you want to set digital Arduino pins 2, 3, 4, 5 and 6 as output and digital pins 0, 1 and 7 as inputs. Their ATMega328p pin names are PD2, PD3, PD4, PD5 and PD6; PD0, PD1 and PD7 respectively. Here's how to set them all simultaneously:
DDRD = B01111100;
Now let's say you want to blink Arduino pins 2, 3, 4, 5, and 6 simultaneously with 1 second interval, you could write this:
Now you might not appreciate what we've done here because the difference is subtle. Let's try another example.
Suppose you want to use a common cathode seven-segment display connected to the Arduino pins without using a driver of some sort. Digital pins 2 to 8 is connected to seven-segment pins a to f.
To display the digit 7, for example, you need the seven segment pins a, b, c to be high and the rest to be low.
PORTD is equal to the value of digit[7] with bits shifted two positions to the left. This is because we used PORTD.2 to PORTD.7 instead of PORTD.0 to PORTD.7.
The last segment (f) is connected to PB0. This would be bit 6 of digit[7]. To get only bit 6 of digit[7], a logical AND of B01000000 and digit[7] is done. The result of the logical AND operation is then shifted six positions (to LSB or PORTB.0) whose result is then stored to PORTB.
The Final Code
Now to display all digits in sequence from 0 to 9, your code would be like this: