Writing directly to ports

Hi folks,
for speeding up my code I want to avoid the good old digitalWrite() funtion.
Therefore I directly write to the ports.

But it turned out that the really simple line of code shown below is quite tricky to write for direct port access.

digitalWrite(pin, value[pin]);

What I intend to do here is controlling the even pins 2-12 on an Arduino Uno sending them either HIGH or LOW. Below is my current version of that:

byte value[6]; // Value can be either 0 or 1
byte pin; // Pins are ONLY even pins 2-12 on an Arduino Uno

if (value[pin] == 0) {
if (pin > 1 && pin < 8 ) PORTD = PORTD &= ~(1 << pin); //=digitalWrite(pin,LOW) for pins 2-6
else PORTB = PORTB &= ~(1 << (pin-8)); } //=digitalWrite(pin,LOW) for pins 8-12

else {
if (pin > 1 && pin < 8 ) PORTD = PORTD |= (1 << pin); //=digitalWrite(pin,HIGH) for pins 2-6
else PORTB = PORTB |= (1 << (pin-8)); } //=digitalWrite(pin,HIGH) for pins 8-12

It works, but seems really a lot of code to me.

Is there any other and less code consuming way to accomplish the same thing?

Thanks for your help!

Check out this thread. http://arduino.cc/forum/index.php/topic,117356.0.html

This is the pin mapping : http://arduino.cc/en/Hacking/PinMapping

You could also use a pointer to a port.
You could use the mapping definitions from the avr pins to Arduino pins. They are somewhere in some include file. I’ve seen it a couple of times, but forgot how it is called.
You might also use bitSet() and bitClear(), those are macro’s and are the same as the &= and |= operations.
Since it is only 6 port, you could use a case-statement for the ports.

But I think your code is okay. I would write it like this:

if (value[pin] == LOW) 
  if (pin > 1 && pin < 8 )
    bitClear (PORTD, pin);    //=digitalWrite(pin,LOW) for pins 2-6
    bitClear (PORTB, (pin-8));  //=digitalWrite(pin,LOW) for pins 8-12
  if (pin > 1 && pin < 8 )
    bitSet (PORTD, pin);        //=digitalWrite(pin,HIGH) for pins 2-6
    bitSet (PORTB, (pin-8));   //=digitalWrite(pin,HIGH) for pins 8-12

Keep in mind that direct port access will effect 'portablity' between 328 based boards and mega type boards. You can deal with that in your source by testing for the chip type being compiled for and using conditional code to use the correct port and pin Vs the arduino abstracted pin numbers, but that may not be possible if you are using variables as pin numbers rather then constants?