Electronic – arduino – How to enable Output pin to high by default in Arduino Uno

arduinooutputpinspullup

In Arduino Uno, I noticed that when I set a PIN to output, the default initial state is low. Is there a way to set the initial output state to high?

The pinmode documentation supports only input, input_pullup, and output. I wish there is an option for output_pullup. If I put an external 10k Ohm pullup resistor around the output PIN, it does help a little pushing the initial state towards high.

Still, if there is a software based solution (i.e. flash the Arduino Uno to default output to high), that would be much appreciated.

Best Answer

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.