0
0
AutocadHow-ToBeginner · 3 min read

How to Use pinMode in Arduino: Simple Guide and Examples

Use pinMode(pin, mode) in Arduino to set a pin as an input or output. The pin is the number of the pin, and mode can be INPUT, OUTPUT, or INPUT_PULLUP.
📐

Syntax

The pinMode function configures a specific pin on the Arduino board to behave either as an input or an output.

  • pin: The number of the pin you want to set.
  • mode: The mode to set the pin to. It can be INPUT, OUTPUT, or INPUT_PULLUP.
arduino
pinMode(pin, mode);
💻

Example

This example sets pin 13 as an output and turns the built-in LED on and off every second.

arduino
void setup() {
  pinMode(13, OUTPUT); // Set pin 13 as output
}

void loop() {
  digitalWrite(13, HIGH); // Turn LED on
  delay(1000);           // Wait 1 second
  digitalWrite(13, LOW);  // Turn LED off
  delay(1000);           // Wait 1 second
}
Output
The built-in LED on pin 13 blinks on and off every second.
⚠️

Common Pitfalls

Common mistakes when using pinMode include:

  • Forgetting to set the pin mode before using digitalWrite or digitalRead.
  • Using the wrong pin number or mode.
  • Not using INPUT_PULLUP when you want to use the internal pull-up resistor for input pins.

Example of wrong and right usage:

arduino
// Wrong: Using digitalWrite without setting pinMode
void setup() {
  // pinMode(2, OUTPUT); // Missing this line
}

void loop() {
  digitalWrite(2, HIGH); // May not work as expected
}

// Right: Setting pinMode before digitalWrite
void setup() {
  pinMode(2, OUTPUT); // Correctly set pin 2 as output
}

void loop() {
  digitalWrite(2, HIGH); // Works correctly
}
📊

Quick Reference

ModeDescription
INPUTConfigures the pin as an input to read signals.
OUTPUTConfigures the pin as an output to send signals.
INPUT_PULLUPConfigures the pin as input with an internal pull-up resistor enabled.

Key Takeaways

Always use pinMode to set a pin as INPUT or OUTPUT before using it.
Use INPUT_PULLUP mode to enable the internal pull-up resistor for input pins.
Forgetting pinMode can cause pins to behave unpredictably.
pinMode only needs to be set once, usually in the setup() function.
Use the correct pin number matching your Arduino board layout.