There is nothing stopping you from writing the output registers (PORTx) before writing the direction registers (DDRx). Unfortunately, the Arduino library functions (pinMode
and digitalWrite
) have a number of side effects and may or may not work. (Perhaps someone more familiar than I am with the Arduino libs can advise if a digitalWrite
followed by a pinMode
will work.
So, direct register manipulation can achieve what you want, if @Tom's solution is insufficient (Tom's solution should work in just about every case). First, consult page 77 of the ATmega328 datasheet and note table 14-1.
Assuming a pin starts with the DDR and PORT bits clear: it's a Hi-z input pin. Set the PORT bit, the pin is now an input with a pullup. Now, when you set the DDR bit, the pin goes from an input with pullup directly to a output high.
Edit: trying to better understand what would happen with the following code by reading through wiring_digital.c
:
// where p is an Arduino pin, x is the corresponding port,
// and n is the corresponding bit
// pin starts with DDRxn == 0, PORTxn == 0
digitalWrite(PINp, HIGH);
// PORTx |= 1<<n, from line 159
// PORTxn == 1, DDRxn == 0: input pullup
pinMode(PINp, OUTPUT)
// DDRx |= 1<<n, from line 56
// PORTxn == 1, DDRxn == 1: output high
So, it appears that calling digitalWrite
before pinMode
will do exactly what you want. Ignore the mess about direct register manipulation above.