In this tip am going to show you how to avoid typing pinMode for each pin you want to control, this is great for when you are working with many/all of the pins in the Arduino.
The Old Way
Let’s say you wanted to make pins 0-5 outputs and pins 6 and 7 inputs, I bet you would type the following.
// outputs pins pinMode(0,OUTPUT); pinMode(1,OUTPUT); pinMode(2,OUTPUT); pinMode(3,OUTPUT); pinMode(4,OUTPUT); pinMode(5,OUTPUT); // input pins pinMode(6,INPUT); pinMode(7,INPUT);
The New Way
A shorter way would be to use the DDRD register, before I explain to you the details of DDRD let me show you the replacement to the code above.
How It Works
What we did above is we assigned a binary number to the direction register D of the Arduino. The binary number is the number to the right of "0b". The count from 7 down to 0 starts to the right of "0b", we have a number (either 0 or 1) for each pin of the Arduino 7 to 0 in that order. A zero means that we want that pin to be an input and one means output.
How To Control Other Pins The New Way
Similarly to control the direction of digital pins 8 to 15 we would refer to register B, so the old way of doing things.
pinMode(8,OUTPUT); pinMode(9,OUTPUT); pinMode(10,OUTPUT); pinMode(11,INPUT); pinMode(12,OUTPUT); pinMode(13,OUTPUT);
would be replaced with
I hope you enjoyed the first tip, there will be more to come.