0
0
AutocadHow-ToBeginner · 3 min read

How to Write Your First Arduino Program: Simple Guide

To write your first Arduino program, create a sketch with two main functions: setup() to initialize settings and loop() to run code repeatedly. Use pinMode() to set pin modes and digitalWrite() to control outputs like an LED.
📐

Syntax

An Arduino program, called a sketch, has two main parts: setup() and loop(). setup() runs once to set up your board, like setting pin modes. loop() runs over and over to keep your program active.

Use pinMode(pin, mode) to tell Arduino if a pin is input or output. Use digitalWrite(pin, value) to turn an output pin HIGH (on) or LOW (off).

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
}
💻

Example

This example blinks the built-in LED on pin 13 on and off every second. It shows how to set pin mode and control the LED with delays.

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

void loop() {
  digitalWrite(13, HIGH); // Turn LED on
  delay(1000);            // Wait for 1 second
  digitalWrite(13, LOW);  // Turn LED off
  delay(1000);            // Wait for 1 second
}
Output
The built-in LED on the Arduino board blinks on for 1 second, then off for 1 second, repeatedly.
⚠️

Common Pitfalls

  • Forgetting to set the pin mode with pinMode() causes the pin to not work as expected.
  • Not using delay() or other timing causes the LED to blink too fast to see.
  • Using the wrong pin number for the built-in LED (usually pin 13) will not light the LED.
arduino
/* Wrong: Missing pinMode setup */
void setup() {
  // pinMode(13, OUTPUT); // This line is missing
}

void loop() {
  digitalWrite(13, HIGH); // LED may not turn on
  delay(1000);
  digitalWrite(13, LOW);
  delay(1000);
}

/* Right: Correct pinMode setup */
void setup() {
  pinMode(13, OUTPUT); // Correctly set pin 13 as output
}

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

Quick Reference

Remember these key functions for your first Arduino program:

  • void setup(): Runs once to set up pins and settings.
  • void loop(): Runs repeatedly to keep your program running.
  • pinMode(pin, mode): Sets a pin as INPUT or OUTPUT.
  • digitalWrite(pin, value): Sets an output pin HIGH or LOW.
  • delay(milliseconds): Pauses the program for a set time.

Key Takeaways

Every Arduino sketch needs a setup() and loop() function.
Use pinMode() to set pins as input or output before using them.
digitalWrite() controls output pins like LEDs by setting HIGH or LOW.
delay() pauses the program to make actions visible, like blinking LEDs.
Check you use the correct pin number for your hardware components.