With digitalWrite(pin_number,value)
, we can set an output pin as HIGH
or LOW
. But if only coding pinMode (pin_number, OUTPUT)
, what is the default state for the pin pin_number
, LOW
or HIGH
? It is noted that: Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state
. Does that mean the pin will be in the state LOW
?
-
neither, they are HI-Z ... all pins are set as input with pullup resistors disabled ... that means that they are seen as floating (disconnected) ... any pin that has an external pullup or pulldown resistor will be pulled in the direction of the resistor– jsotolaJun 27, 2019 at 19:49
2 Answers
On the AVR-based Arduinos at least, pins start in the INPUT
, i.e. high
impedance state. If you then pinMode(pin, OUTPUT);
, the pin turns to
OUTPUT
LOW
. Note, however, that if you first set the pin to
INPUT_PULLUP
, and then to OUTPUT
, the pin ends up in the
OPUTPUT
HIGH
state.
Sometimes you want to control the state the pin will have right when
it's turned to OUTPUT
. You may for example simulate an open collector
output by switching between INPUT
(or INPUT_PULLUP
) and OUTPUT
LOW
, while avoiding the OUTPUT
HIGH
state. In this case, a safe
idiom is to set the output level before switching the pin to OUTPUT
,
e.g.
// Set pin to OUTPUT LOW without going throught the OUTPUT HIGH state.
digitalWrite(pin, LOW); // do this first
pinMode(pin, OUTPUT);
A side effect of performing a digitalWrite()
on a pin that is not set
to OUTPUT
is that the pin gets switched to either INPUT
(if writing
LOW
) or INPUT_PULLUP
(if writing HIGH
). This is an idiosyncrasy of
the AVR IO ports you should probably not rely on if you want your code
to be readable or portable.
Reference: the source code of pinMode()
in the Arduino
core, and the datasheet of the relevant MCU. See for example the section
Ports as General Digital I/O in the ATmega328P’s datasheet.
I've had a similar issue with an ATTINY85 powered DIGISPARK board.
I was getting a glitch when setting a pin to OUTPUT
and the driving it HIGH
immediately. Looked something like this:
CH1:
pinMode(ch1, OUTPUT); // it is at this line that ch1 becomes LOW
digitalWrite(ch1, LOW); // technically redundant since ch1 pin already driven LOW
CH2:
pinMode(ch2, OUTPUT); // at this point ch2 goes LOW
digitalWrite(ch2, HIGH); // and only goes HIGH once this instruction executes
The solution that mitigated the above glitch in my case (ATTiny85 / Digispark Board) was, as Edgar Bonet pointed out above, going through the INPUT_PULLUP phase:
pinMode(ch2, INPUT_PULLUP);
pinMode(ch2, OUTPUT);
digitalWrite(ch2, HIGH);