Learn electronics, coding, and projects — step by step.

Arduino Basics: Comments & Code Readability

Table of Contents

Comments & Code Readability

Comments are notes in your code that are ignored by the Arduino compiler. They help you and others understand what your code does, why certain decisions were made, and make future debugging or updates easier. Writing clear and readable code is just as important as making it work.

Types of Comments

  • Single-line comments: Use // for comments on a single line. They are ideal for short explanations or labeling lines of code.

    int ledPin = 13; // LED is connected to pin 13
  • Multi-line comments: Use /* */ to comment out multiple lines of code or write longer explanations.

    /*
      This section initializes the LED pins
      and sets up the necessary variables for blinking
      the LEDs in sequence.
    */

Tips for Improving Code Readability

  • Label pins and variables clearly: Use descriptive names like buttonPin or temperatureSensor instead of generic names like pin1 or x.
  • Explain complex logic: Write comments that describe why a piece of code exists, not just what it does.
  • Keep consistent formatting: Indent code properly and group related sections together.
  • Use blank lines: Separate logical sections of your code to make it easier to read at a glance.

Example: Well-Commented Arduino Sketch

// Define pin numbers
int ledPin = 13;        // Built-in LED pin
int buttonPin = 2;      // Push button pin

void setup() {
  pinMode(ledPin, OUTPUT);   // Set LED as output
  pinMode(buttonPin, INPUT); // Set button as input
}

void loop() {
  int buttonState = digitalRead(buttonPin); // Read the button state

  // Turn LED on if button is pressed
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
  } 
  // Otherwise, turn LED off
  else {
    digitalWrite(ledPin, LOW);
  }
}

Using comments and maintaining good code readability ensures that your projects are easier to debug, share, and expand. It also helps others understand your work if you collaborate on larger projects.

×



Related Articles: (by Series)