I was wondering if instead of doing several digitalWrite commands to set individual output pin levels
on an Arduino (e.g. digitalWrite(D0, HIGH) - digitalWrite(D7, HIGH)) if there is a way to just write a
byte of data to set all output levels at once.
Also, is there a way to set all of the pinModes at once also... (like writing a value to a register for example)
You can, as Udo Klein's link demonstrates, but unless you really need the speed or to save memory, why do you want to? Generally, code that doesn't use port manipulation is easier to read.
PORTD = PORTD & B11110111; // clear bit 3 (D4, as an example) to enable device X slave select
SPI.transfer(0x03); // send out address byte
SPI.transfer(0x03); // send out data byte
PORTD = PRTD | B00001000; // set bit 3 to deselect device X
In the real world, comments like these ensure fixability by any member of the software team.
Good variable names can minimize the amount of comment you need to write,
the biggest benefit of that is that it is far easier to keep comments and code in sync (especially when there are no comments left
writes all the bits at the same time, if you have used pinMode ahead of that to set the pins as OUTPUT.
Not all port2 have 8 bit on an Uno.
And some might be in use as another function, such as Rx/Tx. So you have to pay a little attention when doing that.
irethedo:
I was wondering if instead of doing several digitalWrite commands to set individual output pin levels
on an Arduino (e.g. digitalWrite(D0, HIGH) - digitalWrite(D7, HIGH)) if there is a way to just write a
byte of data to set all output levels at once.
Also, is there a way to set all of the pinModes at once also... (like writing a value to a register for example)
thanks
Sure. You can find out what port name and bit numbers are used on your particular board and program them directly.
For example, an an Arduino UNO:
pinMode(8, INPUT) == DDRB &= ~_BV(0)
pinMode(8, OUTPUT) == DDRB |= _BV(0)
digitalWrite(8, HIGH) == PORTB |= _BV(0)
digitalWrite(8, LOW) == PORTB &= ~_BV(0)
x = digitalRead(8) == x = PINB & _BV(0) ? 1 : 0
Set pinmode of pins 7 through 0 as outputs in one shot:
DDRD = 0b11111111;
As all inputs:
DDRD = 0b00000000;
Bits 0...3 as input, 4...7 as outputs:
DDRD = 0 | _BV(4) | _BV(5) | _BV(6) | _BV(7);