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
anddigitalWrite
) 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 adigitalWrite
followed by apinMode
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
:So, it appears that calling
digitalWrite
beforepinMode
will do exactly what you want. Ignore the mess about direct register manipulation above.