0
0
AutocadHow-ToBeginner · 3 min read

How to Use digitalWrite in Arduino: Syntax and Examples

Use digitalWrite(pin, value) to set a digital pin HIGH or LOW on an Arduino. First, set the pin mode to OUTPUT using pinMode(pin, OUTPUT), then call digitalWrite with the pin number and HIGH or LOW to turn it on or off.
📐

Syntax

The digitalWrite function sets a digital pin to either HIGH or LOW. You must first set the pin as an output using pinMode.

  • pin: The Arduino pin number you want to control.
  • value: Use HIGH to turn the pin on (5V or 3.3V depending on board) or LOW to turn it off (0V).
arduino
digitalWrite(pin, value);
💻

Example

This example turns an LED connected to pin 13 on and off every second. It shows how to set the pin mode and use digitalWrite to control the LED.

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 LED on pin 13 blinks on for 1 second, then off for 1 second repeatedly.
⚠️

Common Pitfalls

Common mistakes include:

  • Not setting the pin mode to OUTPUT before using digitalWrite. This can cause the pin to not work as expected.
  • Using pin numbers that do not support digital output.
  • Confusing digitalWrite with analogWrite (which is for PWM signals).
arduino
/* Wrong way: Missing pinMode setup */
void setup() {
  // pinMode(13, OUTPUT); // This line is missing
}

void loop() {
  digitalWrite(13, HIGH); // May not work properly
  delay(1000);
  digitalWrite(13, LOW);
  delay(1000);
}

/* Right way: Set pinMode first */
void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
  delay(1000);
}
📊

Quick Reference

Remember these tips when using digitalWrite:

  • Always call pinMode(pin, OUTPUT) in setup().
  • Use HIGH to turn the pin on and LOW to turn it off.
  • Use valid digital pins only.
  • digitalWrite controls voltage levels, not analog values.

Key Takeaways

Always set the pin mode to OUTPUT before using digitalWrite.
Use digitalWrite(pin, HIGH) to turn a pin on and digitalWrite(pin, LOW) to turn it off.
digitalWrite controls digital pins by setting voltage HIGH or LOW.
Do not confuse digitalWrite with analogWrite; they serve different purposes.
Check your Arduino board's pin capabilities before using digitalWrite.