Master Arduino Programming - Lesson #6

by lucascreator in Circuits > Arduino

711 Views, 11 Favorites, 0 Comments

Master Arduino Programming - Lesson #6

lesson-6-article(1).png

A complete guide for beginners about how to code Arduino programs.

Supplies

1 x DFRobot MindPlus Arduino Coding Kit

1 x DFRobot I/O Expansion Shield

1 x DFRobot Digital Buzzer (active buzzer)

1 x DFRobot Digital Piranha LED Module - Red

1 x DFRobot Digital piranha LED module - Blue

1 x Arduino UNO

1 x Ultrasonic Sensor (generic)

1 x Jumper wires (generic)

YouTube Tutorial

Master Arduino Programming – Lesson #6

I've recently posted a tutorial about this project on YouTube explaining everything you can read on this article. You can watch it right above.

Introduction

3.png

In this lesson, we’re taking a big step forward: moving beyond simply wiring components and into the world of coding. If you’ve ever wondered how to make your Arduino truly “think, ” this is where it all begins.

You’ll learn how to think like a programmer by understanding some of the most important coding concepts:

  1. Variables: store and manage data in your programs.
  2. Constants: keep fixed values that never change.
  3. Arrays: handle entire lists of data with ease.
  4. Conditionals & Logic: make your code smart by letting it react to different situations.
  5. Operators: perform calculations and comparisons that bring everything together.
  6. Loops & Functions: write cleaner, more efficient, and reusable code.

And of course, learning is best when you build something. That’s why, as always, there’s a hands-on project at the end of the lesson to help you practice everything you’ve learned.

This is lesson #6 of a 24-part series called Arduino for Beginners. If you haven’t checked out the earlier lessons, I highly recommend starting from the beginning, since each class builds on the last one.

You can read the articles of this course or watch the related videos on this YouTube playlist.

Ready to level up your Arduino skills? Let’s get started!


Sponsor

20250609_162406.jpg
20250609_162454.jpg
20250609_162534.jpg
20250609_162545.jpg

All components I'll use for the project come with the MindPlus Arduino Coding Kit - a complete kit provided by DFRobot that contains everything you need to take your first steps in the Arduino world.

DFRobot is one of the top-global providers of open-source hardware. In their online store, you can find basically anything you need for your next STEM project.

If you don't have this kit, don't worry. You can follow along with your Arduino board and other components easily found in several stores worldwide.

But I highly recommend getting one because it'll make your learning journey easier.

Thank you so much DFRobot for sponsoring educational content like this.

Variables

10.png
page-1.png
page-2.png

Let's start our explanation by analyzing one of the most fundamental concepts in programming: variables.

Imagine your Arduino sketch is like a recipe. And just like a recipe needs to remember how much of each ingredient to use, your program needs a way to remember numbers, words, and other values as it runs.

That’s where variables come in.

A variable is like a labeled box in your Arduino’s memory. You can store a value in it, change it later, and use it throughout your program (see the drawing above).

  1. Want to remember which pin your LED is connected to? Use a variable.
  2. Want to keep track of how many times a button has been pressed? Use a variable.

In short, variables allow your program to store and manipulate data, and that’s what makes them one of the most essential building blocks in coding.

Another reason that makes variables so important is that they allow you to change information on your code in a simpler way.

Imagine if you had to write the same value - say, pin number 9 - dozens of times in your code. What happens if you later move your LED to pin 6?

You’d have to update every single line manually. That’s not only a pain, it also leads to bugs (see the screenshots above).

But if you use a variable, you'll only need to update one line (clean and reusable code).

Variable Types

17.png
18.png
21.png

Now that you understand the concept of variables, let's learn about variable types.

Not all values are the same. Some are whole numbers, others are decimal numbers, some are just true or false. To handle all these different types of data efficiently, Arduino gives you different variable types.

Right above there's a table that shows the four basic data types in Arduino.

You may be wondering: why do these types exist?

In short because microcontrollers like the Arduino have limited memory.

For example, a float (which stores decimal numbers) usually takes up more memory than an int (which stores whole numbers). So even though you can store a number like 1 as 1.0 in a float, it's better to use an int if you don’t need the decimal (see the drawing).

Constants

We talked a lot about variables, b ut sometimes, you don’t want a value to change. That’s when you use a constant.

Let’s say you write:

int ledPin = 9;

This works - but the value can still be changed later in the code, even by accident:

int ledPin = 9;
ledPin = 5;

But if you write:

const int ledPin = 9;

Now the Arduino will protect that value. If you tries to change it later, the code won’t compile.

As you may noticed, constants are declared by using the const keyword before the data type, as you can see here:

const int buttonPin = 2;
const float voltageThreshold = 3.3;

You can use const with any variable type.

Some people also use ALL CAPS for constant names to make them easy to spot. This is just a style preference, but it can make your code easier to read. See the following example:

const int LED_PIN = 9;

Arrays

29.png
31-1.png

So far, you've seen how to use variables to store single pieces of data - like a pin number or a temperature reading.

But what if you had to control 5 LEDs connected to different pins?

You could create 5 separate variables (see the first image).

That works, but it’s messy. And if you wanted to turn all those LEDs on or off in a loop? You’d have to repeat your code 5 times.

That’s where arrays come in.

An array is like a row of boxes, where each box holds one value and all the boxes share the same name.

Instead of 5 variables, you can write (see the second image):

int ledPins[] = {3, 5, 6, 9, 10};

Now you have one variable - ledPins - that stores all five pin numbers in one place.

As you may noticed, arrays make your code shorter, cleaner, and easier to manage - especially as your projects get more complex.

Let's take a closer look at how array works.

Each item in an array is stored at a specific position, starting from 0. So in this example:

int ledPins[] = {3, 5, 6, 9, 10};
  1. 3 is in position 0
  2. 5 is in position 1
  3. 6 is in position 2
  4. 9 is in position 3
  5. 10 is in position 4

If you try to access ledPins[5], it won’t work because there’s nothing stored there.

You can also read or update array values like this:

int ledPins[] = {3, 5, 6, 9, 10};
ledPins[2] = 8;

Arrays unlock a whole new level of scalability and organization in your code. Once you get comfortable with them, you’ll start using arrays in almost every project.


Conditionals

We talked a lot about data. Let's move on and learn about other coding structures.

Imagine your Arduino is faced with a decision.

  1. If a button is pressed, turn on the LED.
  2. If the temperature is too high, activate a fan.
  3. If it’s dark, turn on a light.

These decisions "if this, then do that" are called conditionals.

In code, conditionals let your Arduino react to the world around it by checking whether something is true and doing something based on that.

Without conditionals, your program would do the exact same thing over and over again. But with conditionals, it can make choices.

The most basic conditional is the if statement. It looks like this:

if (condition) {
// do something
}

The condition is something that can be true or false. If it’s true, the code inside the curly brackets runs. If it’s false, your Arduino skips it.

For example:

if (digitalRead(buttonPin) == HIGH) {
digitalWrite(ledPin, HIGH);
}

This means:

  1. If the button is pressed, turn the LED on.

But what if you want to do something different when the condition is false?

That’s where else comes in:

if (digitalRead(buttonPin) == HIGH) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}

Now your Arduino says:

  1. If the button is pressed, turn on the LED. Otherwise, turn it off.

Sometimes you need to check multiple conditions. That’s where else if is useful:

if (temperature > 30) {
// it’s hot
} else if (temperature > 20) {
// it’s warm
} else {
// it’s cold
}

This creates a chain of decisions, where only one block runs depending on the situation. You can add as many else if blocks as you want, but the whole code always starts with if and ends with else.

Comparison Operators

46.png

As you may noticed, in the previous examples we used some special symbols inside the condition structure, like equal to (==) or greater than (>). These symbols are known as comparison operators.

When you write a conditional like if (x == 10), you're asking your Arduino to compare two values.

To do this, we use comparison operators. These are symbols that help your program answer questions like:

  1. Is this equal to that?
  2. Is this greater than that?
  3. Is this smaller or different?

Each comparison returns a true or false result - exactly what an if statement needs to make a decision.

For example:

if (temperature > 30)

This reads as: “if the temperature is greater than 30°C, then…”

Without comparison operators, you couldn’t write conditions that depend on sensor values, time, counters, or anything dynamic. They’re the core of logical decision-making in code.

Arduino has six comparison operators. Refer to the table above for more information about them.

An important note: don't confuse = to ==

  1. = is for assigning values.
  2. == is for comparing values.
x = 5; // set x to 5
x == 5; // check if x is equal to 5

Comparison operators are the tools that allow you to ask questions in code:

  1. Is the button pressed?
  2. Is the temperature above a threshold?
  3. Has 10 seconds passed?

These questions are the logic behind every smart behavior your Arduino performs.

By understanding comparison operators, you're learning how to give your code the power to decide and that’s a major step toward real programming.


Logical Operators

53.png

Now let's look at another type of operators: the logical operators.

So far, we’ve written conditions like: if (temperature > 30)

But what if you want to check two things at once?

For example:

  1. If the temperature is high and the humidity is low, turn on the fan.
  2. If the button is pressed or the motion sensor is triggered, sound an alarm.

This is where logical operators come in. They let you combine multiple conditions into a single decision.

These commands are important because real-world situations are rarely based on just one condition. Logical operators let your Arduino handle compound logic, just like we do in everyday thinking.

There are three different logical operators. You can refer to the above table for more details.

Let's look at each operator, starting from AND. This will only run if both conditions are true.

if (temperature > 30 && humidity < 50) {
Serial.println("Hot and dry! Turning on fan.");
}

On the other hand, the OR condition runs if at least one of the conditions is true.

if (button1 == HIGH || button2 == HIGH) {
Serial.println("At least one button was pressed.");
}

In the end, we have the NOT operator. It reverses the result of a condition, so False becomes True and True becomes False.

if (!isLightOn) {
digitalWrite(ledPin, HIGH);
}
// This means: “if isLightOn is false, then turn on the LED.”

Logical operators allow your Arduino to make smart decisions based on multiple inputs - just like we do in real life.

A tip: when combining conditions, especially with AND and OR, use parentheses to make the logic easier to read and avoid confusion.

if ((lightLevel < 300 || isNightTime) && motionDetected) {
// Turn on the lights
}
// This reads as: if it’s dark OR nighttime, AND there’s motion, turn on the lights.

Logical operators are your bridge from simple logic to real-world intelligence. They let your code ask complex questions and act only when the right combination of conditions is met.

Arithmetic Operators

63.png
69.png

Congratulations if you've made this far. There are only two coding structures left to study: loops and functions. But before diving into these advanced topics, let's take a look at the last type of operator we need to know: the arithmetic operators.

In the same way that you use math in everyday life - adding prices, calculating time, subtracting scores - Arduino also needs math to process data and control behaviors.

Arithmetic operators are the basic math symbols your Arduino uses to perform operations on numbers.

They help your code do things like:

  1. Add values
  2. Subtract quantities
  3. Multiply measurements
  4. Divide results
  5. Find remainders

You’ll use arithmetic operators all the time in your Arduino programs.

For example:

  1. Want to fade an LED gradually? You’ll increase or decrease its brightness using + or -.
  2. Want to track how long something has been active? You’ll accumulate time using +=.
  3. Need to alternate between even and odd steps? You’ll use modulo to check remainders.

Math is the language that lets your Arduino make precise, continuous changes - not just on/off decisions.

There are five different math operators you should learn. Refer to this above table for more details.

You can also combine math with assignment to simplify code, as you can see on the second table.

Arithmetic operators are more than just math—they’re how you make your Arduino:

  1. Count button presses.
  2. Calculate sensor averages.
  3. Create visual effects.
  4. Manage loops and conditions.

They’re the foundation of every dynamic behavior in your code.

Loops

In real life, we often repeat tasks: brushing teeth, blinking, checking the mailbox everyday, etc. In programming, loops let us automate repetition. Instead of writing the same code over and over again, we write it once and tell the computer to repeat it as long as needed.

Arduino programs usually run nonstop from the moment the board is powered. That’s why the loop() function exists: to repeat your code endlessly. But inside that function, you can use different types of loops for different kinds of repetition.

Let’s go over the main ones.

For

Firstly, let's learn the for structure. A for loop is great when you know exactly how many times you want to repeat something. For example, blinking an LED 10 times, or checking the first 5 elements in an array.

Its basic structure is something like this:

for (int i = 0; i < 5; i++) {
// Your repeated code here
}

As you can see, we defined a special variable - a counter. This code can be interpreted as:

  1. The counter I starts at 0 and while I is less than 5, keeps adding one unit to the counter.
  2. In reality, this for loop will execute the code inside the curly brackets 5 times.

We can use it, for example, to blink a LED 10 times:

for (int i = 0; i < 10; i++) {
digitalWrite(LED_BUILTIN, HIGH);
delay(500);
digitalWrite(LED_BUILTIN, LOW);
delay(500);
}

While

Another loop Arduino supports is the while structure. Use a while loop when you want something to repeat until a condition becomes false.

The basic structure is:

while (sensorValue < threshold) {
// Keep reading sensor until the value reaches the threshold
}

Now a very important note: if the condition is always true, you’ll create an infinite loop, which may freeze your program. Always make sure the condition will eventually turn false.

The blink a LED 10 times can be represented using while this way:

int i = 0; // Initialize counter before the loop
while (i < 10) {
digitalWrite(LED_BUILTIN, HIGH);
delay(500);
digitalWrite(LED_BUILTIN, LOW);
delay(500);
i++; // Increment the counter inside the loop
}

As you can see, some things changed:

  1. The int I = 0 initialization was moved before the loop.
  2. The i++ increment was added at the end of the loop block.
  3. The condition I < 10 remains the same.

Despite the changes, the result is exactly the same: the LED blinks 10 times.

Do...While

There's a third and last loop structure we are going to understand. It's similar to the while loop and is called do...while.

This loop works like while, but it always runs the code at least once, before checking the condition.

The structure is:

do {
// This block runs at least once
} while (condition);

For example:

int value;
do {
value = analogRead(A0);
} while (value < 100); // Keep reading until value is high enough

In this code, we read values from A0 and keep doing it until it becomes less than 100.

Now you may be thinking: how do I choose the right loop structure?

Well...

  1. If you know exactly how many times to repeat, choose for.
  2. If you want to repeat while a condition is true, choose while.
  3. If you want to always execute once, then keep going if needed, choose do...while.

Loops are important because they allow your Arduino to:

  1. Read sensors continuously.
  2. Update displays regularly.
  3. Blink LEDs in patterns.
  4. Monitor inputs in real time.
  5. Repeat actions without copying code.

Without loops, your Arduino would only do something once and then stop, and that’s not what we want in an embedded system designed to run forever.

Functions

The last structure we will study today is: functions.

A function is a block of code that performs a specific task. You can "call" it whenever you need to do that task, instead of writing the same lines over and over again.

Think of it like a recipe: once you've written it down, you can follow it whenever you want that dish. No need to rewrite the whole recipe every time.

In Arduino, you’ve already used two special functions: setup and loop.

void setup() {
// runs once when the board starts
}
void loop() {
// runs continuously after setup
}

But you can create your own custom functions too.

These structures are important because:

  1. It helps avoid repetition (write once, use many times).
  2. It makes your code easier to read.
  3. It keeps things organized.

Here's the basic structure of a function:

returnType functionName(parameters) {
// Code to execute
return value; // if returnType is not void
}
  1. returnType: what the function gives back (e.g., int, float, or void if it returns nothing).
  2. functionName: the name you choose for your function.
  3. parameters: inputs the function needs (optional).

Let's transform the blink LED example in a function.

void blinkLED(int times, int delayTime) {
for (int i = 0; i < times; i++) {
digitalWrite(LED_BUILTIN, HIGH);
delay(delayTime);
digitalWrite(LED_BUILTIN, LOW);
delay(delayTime);
}
}

This code is a bit confusion when you look at it for the first time, but I'm going to break it down:

  1. void means the function doesn't return any value. It's just doing something (in this case blinking a LED), but it won't give anything back.
  2. blinkLED is the name of the function. You can call it later in your code to make the LED blink.
  3. int times and int delayTime are parameters - values you pass to the function when calling it.
  4. times gets how many times the LED should blink.
  5. delayTime gets how long the LED stays on and off in milliseconds.

So this function not only let's us blink a LED, it allows us to set up how many times it blinks and how much time it'll stay on or off.

For example, if we write blinkLED(5, 500), it would blink the LED 5 times, with a 500ms delay between ON and OFF.

As you can see, we put a for loop inside the function. There's nothing wrong with that. You can combine structures the way you need, just make sure to follow the syntax rules.

Functions can return values. For example:

int addNumbers(int a, int b) {
return a + b;
}

addNumbers gets two integers, sum them up, and returns the result. So if we call it passing the numbers 4 and 7, we'll get 11.

When working with functions, it's important to follow some basic rules:

  1. Give functions clear, descriptive names like readTemperature(), turnOnFan(), or calculateAverage().
  2. Keep functions focused on one specific task.
  3. Try to keep them short and simple.

Now that we finished studying about programming, let's put everything together and build a real project.

Project

99.png

Today, we're going to build an alarm system using an ultrasonic sensor. If somebody gets within 10cm (3.93in) of the sensor, it triggers the alarm.

In our case, it sounds a buzzer while a red and blue leds blink alternatively. This happens for 10 seconds and after that, the system resets and starts monitoring again.

For this project, you'll need the following materials - note that all of them come with the MindPlus Arduino Coding Kit but you can use your own components too.

  1. Arduino UNO
  2. I/O Expansion Shield
  3. Ultrasonic Sensor
  4. Red LED
  5. Blue LED
  6. Digital (Active) Buzzer
  7. Jumper Wires (to connect the components)

After you get all components, assemble them according to the schematics.

Code

20250820_103959.jpg
20250820_103238.jpg
20250820_103145.jpg
20250820_103146.jpg
alarm-system-mindplus-block-code(1).png

Now that you wired up the components, let's recap how the system works:

  1. The ultrasonic sensor constantly checks the distance to any object in front of it.
  2. If something is detected within 10cm (3.93in), the alarm is triggered.
  3. Alarm runs for 10 seconds: red and blue LEDs blink alternately while the buzzer sounds.
  4. After 10 seconds, the system resets and resumes monitoring.

After that, connect the Arduino on your computer using the USB cable, open up Arduino IDE, and upload the code of today's lesson.

Mind+

Additionally, you can create the same code on Mind+ using the block-based interface. I won't dive into the details, but you can refer to the last image above to build your own block code.

Conclusion

That's the end of this lesson. You learned a lot about coding and built your own alarm system using an ultrasonic sensor, LEDs, and a buzzer.

In the next lesson, we'll study push buttons and how to assemble them on Arduino. We'll also modify this project, so after the alarm system is triggered, the user can press a button to reboot it.

You can read the lessons here or watch them on this YouTube playlist.

Additionally, refer to the official Arduino documentation if you have any doubts or want to learn more about coding.

Thank you so much for reading this lesson. I'll see you in the next one.