Chapter 13
Up to now, our programs have worked.
But let’s be honest —
- Numbers appear randomly.
- Code repeats itself.
- Small changes require editing many lines.
This chapter is about fixing that — not by learning more code, but by learning
We'll simply learn a few habits that make our Arduino projects easier to build, debug, and improve.
🧠 Why Clean Code Matters (Even for Arduino)
When projects grow, bad structure causes:
confusion
bugs
fear of changing things
copy-paste disasters
Clean code gives you:
readability
control
confidence
scalability
📦 Variables — Naming Values
A variable is a named container that holds a value.
Instead of writing this everywhere:
digitalWrite(13, HIGH);
We do this:
const int ledPin = 13;
digitalWrite(ledPin, HIGH);
Now:
the meaning is clear
changing pins is easy
code reads like English
🔒 const — Lock What Shouldn’t Change
const int ledPin = 13;
const means:
“This value should never change.”
Use it for:
pin numbers
fixed timings
configuration values
This prevents accidental bugs.
🔢 Variables Store More Than Pins
Examples you already used:
int buttonState = digitalRead(2);
int sensorValue = analogRead(A0);
Variables let you:
store readings
compare values
make decisions
Without them, logic is impossible.
🔁 Functions — Avoid Repeating Yourself
If you write the same code again and again, that’s a sign.
Example problem:
digitalWrite(9, HIGH);
delay(500);
digitalWrite(9, LOW);
delay(500);
What if you want to blink multiple LEDs?
Instead, create a function.
✨ Creating a Function
void blinkLED(int pin, int delayTime) {
digitalWrite(pin, HIGH);
delay(delayTime);
digitalWrite(pin, LOW);
delay(delayTime);
}
Now use it:
blinkLED(9, 500);
blinkLED(10, 200);
Cleaner. Reusable. Powerful.
🧩 What Functions Really Are
A function is:
a named block of code
that performs one job
and can be reused
Think of it as:
“Pack this behavior into a box and reuse it.”
This is how real systems are built.
🏗️ Clean Structure Example
const int ledPin = 9; const int buttonPin = 2;void setup() { pinMode(ledPin, OUTPUT); pinMode(buttonPin, INPUT_PULLUP); }
void loop() { if (digitalRead(buttonPin) == LOW) { blinkLED(ledPin, 300); } }
void blinkLED(int pin, int delayTime) { digitalWrite(pin, HIGH); delay(delayTime); digitalWrite(pin, LOW); delay(delayTime); }
This code:
reads clearly
is easy to extend
is easy to debug
What is the main purpose of a variable in programming?
Why do we use functions in a program?
Which of the following is a good clean code practice?
🧰 Common Beginner Mistakes
Using raw numbers everywhere
Avoiding functions because “it works already”
Writing huge
loop()blocksFear of breaking working code
Clean code reduces fear, not increases it.
📌 What Comes Next
Now that we can:
structure code
reuse logic
name things properly
We’re ready to think about decision-making.
Comments
Share your thoughts, questions, or corrections below. Be kind and keep it on-topic ✨