Multiple digitalWrite Variables

First off, Arduino is fantastic.

Second, here’s what I’d like to know. Inside a loop, I’d like to accomplish this, for example:

digitalWrite (4, HIGH);
digitalWrite (5, HIGH);

But, I’d like to do it all on the same line, basically accomplish this:

digitalWrite (4,5, HIGH);

Of course, if I type the line above, it errors. So, without having 50 lines of code for turning on 50 pins, how can I do it all at once?

Thanks!

Write your own massDigitalWrite() function that takes as an argument an array and an array length. Have this function run a for loop that loops through the array and calls digitalWrite() on each element.

void massDigitalWrite(unsigned char pins, unsigned char length, unsigned char state)
{
unsigned char i;
for (i = 0; i < length; i++)
digitalWrite(pins*, state);*
}
void setup()
{

  • unsigned char pins = {4, 5, 9, 13};*
  • massDigitalWrite(pins, 4, HIGH);*
    }
    Or you could just use the mega168’s digital I/O registers directly to set multiple pin states at once. Each bit of each one-byte register corresponds to a particular pin, so it’s possible to control states of eight output pins with a single instruction. For example:
    PORTD = 0b00101100; // set pins 2, 4, and 5 high; set pins 0, 1, 3, 6, and 7 low
    - Ben

arduino digital pins 4, 5 are mapped to the chip's PORTD pins 4 and 5.

PORTD represents the state of PD0 - PD7 (arduino digital 0 - 7) as a byte.

digitalWrite(4,5,HIGH) would be ( |= bit wise OR ):

PORTD |= B00110000

digitalWrite(4,5,LOW) would be ( &= bit wise AND ):

PORTD &= B11001111

change status of pins 4,5 would be ( ^= bit wise XOR ):

PORTD ^= B00110000

this will do what you wanted in one line and change all pins at the same time if that is important for your setup.

Okay, thanks for the responses, but where do I put this command?

PORTD = 0b00101100;

I tried it in both the setup and loop, but it didn’t work. Do I need something else to get it working?

you'd use PORTD = .... as a replacement for digitalWrite(), that is normally you'd put it somewhere inside the loop() function if you need it to run more than once. what's left is to set the relevant pins of PORTD to output mode. this can be done with pinMode(arduino_pin,OUTPUT), or like this:

DDRD = B11111111; // this is bad

this stands for DataDirectionRegisterD, with 1 = output, 0 = input.

caveat: PD0 and PD1 are used for communication with your computer, so changing the values of DDRD can block stuff.
better use the |= / &= way of setting/clearing the bits, leaving "dangerous" bits untouched.

DDRD |= B00110000; // safer

just set PD4 and PD5 to output, rest remains unchanged

Awesome, thanks. Forgot I had to set them as OUTPUT too.