pinMode or Data Direction Register


If you use a lot of pins and regularily want to set them to INPUT or OUTPUT it can be useful to modify the data direction register instead of using the pinMode()-command.

In most cases you won't gain much speed.

Sometimes you want to switch ports exactly at the same time. This only is possible if the are mapped to the same port register.

This is to see the mapping of the pins:

void setup() {                
  Serial.begin(9600);
  // set all pins to INPUT:
  for (int i=0; i<20; i++) pinMode(i,INPUT);
  // test them all:
  Serial.println(" i   DDRB     DDRC     DDRD");
  for (int i=0; i<20; i++) {
    pinMode(i, OUTPUT);  
    showRegs(i);
    pinMode(i,INPUT);
  } 
}

void loop() {
}

// show the 3 data direction registers :
void showRegs(int i) {
  if (i<10) Serial.print(" ");
  Serial.print(i);
  Serial.print(itos(DDRB));
  Serial.print(itos(DDRC));
  Serial.print(itos(DDRD));
  Serial.println();
}

// converting to binary:
String itos(int x) {
  String s = " ";
  for (int i=7; i>=0; i--) 
    s.concat(bitRead(x,i));
  return s; 
}
  
and this is the result:
 i   DDRB     DDRC     DDRD
 0 00000000 00000000 00000001
 1 00000000 00000000 00000010
 2 00000000 00000000 00000100
 3 00000000 00000000 00001000
 4 00000000 00000000 00010000
 5 00000000 00000000 00100000
 6 00000000 00000000 01000000
 7 00000000 00000000 10000000
 8 00000001 00000000 00000000
 9 00000010 00000000 00000000
10 00000100 00000000 00000000
11 00001000 00000000 00000000
12 00010000 00000000 00000000
13 00100000 00000000 00000000
14 00000000 00000001 00000000
15 00000000 00000010 00000000
16 00000000 00000100 00000000
17 00000000 00001000 00000000
18 00000000 00010000 00000000
19 00000000 00100000 00000000

Note:
The digital pins 14 to 19 correspond to the analog pins A0 to A5.
The data direction registers can be set using the command DDRx = <bitmask>.
To write to the PORT registers use the command PORTx = <bits>.
To read the PORT registers use the command <var> = PORTx.
(x is one of the letters B, C, or D.)

If you have the ATmega2560 you have to extend the program.
There you have the registers A, B, C, D, E, F, G H, J, K and L (it is true: a register named I is missing).


contact: nji(at)gmx.de