1

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 – jsotola Jun 27 at 19:49
3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.