Last updated on November 19th, 2024 at 04:55 pm
If you are new to Arduino and have no prior knowledge of programming, then this guide on “ Arduino Programming for Beginners ” is for you only. In this post, you will learn everything you need to know about Arduino programming in order to build those mind-boggling projects.
This detailed guide is filled with examples so that you can grab the concepts more clearly. Three beginner-level Arduino projects are also given at the end of the article.
Before moving on to the Arduino programming section, let’s learn what Arduino is and why it is so popular.
Table of Contents
What is Arduino?
Arduino is an Italy-based company that manufactures Microcontroller boards called Arduino Boards which is used in many electronics and day-to-day applications.
It is one of the most popular microcontroller based Development boards on Earth since a lot of hobbyists and students from all over the world use Arduino Boards in their day-to-day projects. One of the key reasons for Arduino being so popular is that it is Open Source Software and Open Source Hardware-based Board.
Arduino was originally designed for artists, designers, and hobbyists, but it has found many practical applications in industry. Some of the biggest names in technology are using Arduino, including Google, Microsoft, Apple, and Amazon.
One factor that separates Arduino from all the other Microcontroller boards is its community of thousands of users. Queries, Projects, and questions are posted daily on the Internet by its community members. Checkout: Official Arduino forum
Or you can join our Arduino forum as well.
What do you need to get started with Arduino?
The great thing about Arduino is that you don’t need much to get started. All you need is a working computer with Arduino software installed and an Arduino board.
In addition to an Arduino board, you also need a USB cable to connect the board to your computer.
Types of Arduino boards
Since there are so many applications and areas where Microcontroller boards like Arduino can be used, it is impossible to fit all features in one type of Arduino Board. Hence there are many types of Arduino boards available in the market according to application and user needs.
Some have more pins while some have more features.
For example, the Arduino portenta is the most powerful Arduino board intended for industrial applications. Similarly, Arduino Mini, due to its small size, is best fitted for small projects where size is a constraint.
Some of the popular Arduino Boards are listed below:
Apart from Arduino UNO, Arduino Nano also became very popular soon after it was launched. Due to its form factor popularity, a lot of Nano variants have been launched since then. You can read about each one of them on our blog in detail.
Arduino UNO R3: Best for beginners
Out of all the Arduino boards, Arduino UNO is the most popular one and also the simplest board for beginners. It was launched way back in 2005.
Anyone can start making projects using Arduino UNO after just a few minutes of reading and practicing.
Now that we have covered the basics, let’s jump to the programming of an Arduino board.
Arduino programming basics
What is Arduino IDE( Integrated Development Environment)?
As given in techtarget.com, the definition of IDE is:
“An integrated development environment (IDE) is a software suite that consolidates the basic tools developers need to write and test software“
In simple words, Arduino IDE or Arduino programming environment is a software/tool that helps us code and program Arduino Boards. Arduino IDE is the basic interface of Arduino software that you see on your Laptop screen after installing it.
It is a Java-based platform but the programs (or sketches) you write for the Arduino boards are typically written in a language very similar to C++. The IDE is open source and runs on Windows, macOS, and Linux operating systems. The “Wiring” programming language simplifies C++ syntax for use with the IDE.
It contains all the tools like compiling and debugging required to upload and run programs on Arduino boards. So getting familiar with Arduino IDE is important if you are starting your journey with Arduino.
Arduino IDE dashboard tour
Given below are the dashboard images of Arduino 1.0 IDE and new improved Arduino 2.0.
Verify / Upload – compile and upload your code to your Arduino Board.
Select Board & Port – The Arduino board connected and detected by the system is shown here along with the port number.
Sketchbook – All of the stored/saved sketches or programs can be found here.
Boards Manager – Here you will find the packages of boards other than Arduino.
Library Manager – browse through thousands of Arduino libraries, made by Arduino & its community.
Debugger – This feature is used to test and debug the code in real time.
Search – search for keywords in your code.
Open Serial Monitor – Opens the Serial Monitor tool, as a new tab in the console. You can use it to print characters and numbers; and read and print the sensor’s input using a set of commands called Serial Commands.
For additional commands, check these Menus: File, Edit, Sketch, Tools, and Help.
Note: To know Arduino IDE in detail you can check out this post on Arduino.cc itself: Arduino Software (IDE)
Arduino basic syntax
What are Void Setup() and Void Loop()?
Void Setup and Void Loop are the building blocks of any program in Arduino. Every Arduino Program necessarily needs these two functions to work.
Void Setup() :
Void means not returning any value. Void functions are called so because these functions do not take any input parameters whenever they are called. The setup means setting the proper conditions for the initialization of a program.
Void Setup is a function called only once when the Arduino board starts. So generally, all the initialization code (for example: Initializing pin 13 as the output pin) goes inside this function.
The structure of the Void Setup function is: Void Setup() { }
Example:
void setup()
{
pinMode(13, OUTPUT);
// put your setup code here, to run once:
}
Void Loop() :
A void Loop is an infinite loop. The code written inside this function keeps on executing continuously in an endless loop. There is no ending for this loop i.e., the code written here will run for an infinite number of times unless the board is reset or powered off.
The structure of the Void Loop function is: Void Loop() { }
Example:
void loop()
{
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
// put your main code here, to run repeatedly:
}
Arduino Program that does nothing
Copy the program given below and paste it into the code editor window.
void setup()
{
// put your setup code here, to run once:
}
void loop()
{
// put your main code here, to run repeatedly:
}
Now run the simulation and observe. The Arduino will not do anything because there are no instructions for it to follow.
Since there is nothing to initialize in the setup function, the loop function runs continuously.
Comments in Arduino Programming
Comments are the lines of code that Arduino does not execute. These are written in a program to increase their readability.
A comment is a note that programmers write to help them remember what’s happening in the code. Code comments help you and other people understand how the code works. If you are a beginner in Arduino programming, we recommend using comments in every program.
They can also be helpful for debugging, as you can comment on sections of code that you suspect are causing errors.
Note: Comments are not read by the compiler, i.e., the compiler does not consider any comment a part of the code.
What are single line comments?
Single-line comments in Arduino are written using ‘//‘ symbols. Anything that is written after ‘//‘ symbols till the end of the line is not executed by Arduino.
int x;
void setup()
{
// put your setup code here, to run once( Yes this is a comment! )
}
void loop()
{
x = 5; // This is a single line comment. Anything after the slashes is a comment
// to the end of the line
}
What are multi-line comments?
Multi-line comments in Arduino code are indicated by /* and */. Anything between these symbols will be ignored by the compiler. This can be useful for commenting out large sections of code or leaving yourself notes about what a particular block of code is supposed to do.
However, it’s important to note that /* and */ must always come in pairs – if you forget to close a multi-line comment, everything after it will be ignored by the compiler until the end of the program.
How to use Multi-Line Comments in Arduino Programming?
Before starting a Multi-line comment: use “/*“
To end a Multi-line comment: Just end the Multi-line comment by typing “*/“
Example:
void setup()
{
pinMode(13, OUTPUT);
// put your setup code here, to run once(this is a single line comment)
}
void loop()
{
digitalWrite(13, HIGH); /* This is a Multi-line comment ending
........................here,
........................no here ! */
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
Rule of using a semicolon(;) in Arduino programming.
The semicolon is perhaps one of the most important punctuation marks in any programming language. In C++, it denotes the end of a statement. Without a semicolon, the compiler would not know where one statement ends and the next begins.
This would make writing even simple programs extremely difficult. In addition, the semicolon is also used to separate different object definitions and function declarations.
Example:
int x = 5; // This statement assigns value 5 to variable x
If there is no semicolon(;) at the end of a statement, it leads to an error.
Example:
int x = 5 // this will lead to an error because there is no semicolon(;) at the end of the statement.
Variables and Datatypes
What is a variable?
When you sit down to write a program, there are certain pieces of data you know ahead of time. For example, let’s say you’re writing a program to calculate the average grade in a class. You would need to create a variable to store the total number of grades entered and a variable to store the running total.
In this case, the total number of grades would be a constant(number of students), while the running total would vary. So variables are used to store these kinds of known or unknown quantities of information referred to as a value.
In most programming languages, you must declare variables before you can use them. This means that you need to specify the type of data that the variable will hold (such as a number or a string), as well as the name of the variable.
Example: The following code creates integer variables named “runningTotal” and “numberofstudents”.
int runningTotal;
int numberofstudents = 30;
The second variable is assigned a value of 30. If you later want to change the value of this variable, you can simply reassign it using the same operator: numberofstudents = 20;
But the first variable is unknown and will be used to save the user’s input.
Note: A variable is a way to identify a memory location using a name. This makes it easier to work with the memory location since you can easily remember the name.
What are Datatypes?
Datatypes are used to specify the type of data that a variable can hold. For example, an int datatype can hold an integer value, while a float datatype can hold a floating point number.
In addition, data types can be used to specify the size of a variable. For example, a byte datatype is one byte in size, while an int datatype is two bytes in size. By specifying the size of a variable, you can ensure that the data it contains will be properly processed by the Arduino board.
- An int data type is two bytes long and ranges from -32,768 to 32,767.
- A float data type is four bytes long and ranges from 3.40282347E+38F to 1.17549435E-38F.
- A char data type is one byte long and can hold 256 different characters.
How to use variables in Arduino?
Look at this program:
int ledPin = 13;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH);
}
The variable “ledPin” is declared whose name is ledPin, whose value is 13, and whose type is int.
This variable is then used by its name later in the program where it simply replaces it with the stored value i.e, 13.
So pinMode(ledPin, OUTPUT) is same as pinMode(13, OUTPUT) and digitalWrite(ledPin,HIGH) is same as digitalWrite(13,HIGH).
What are global variables?
In the example program above, the variable ledPin is a global variable since it was declared outside the function. This means that it is available for use throughout the entire program. Global variables can be accessed by any function in your sketch, including setup() and loop().
Since both the setup() and loop() functions use ledPin, any changes made to it in one function will also show up in the other. See the example below:
int ledPin = 13;
void setup() {
ledPin = 3;
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH);
}
The digitalWrite() function in loop() will have a value of 3 passed to it, since that is the value assigned to the variable in setup().
What are local variables?
Look at the example given below:
int ledPin = 13;
void setup() {
pinMode(ledPin, OUTPUT);
int pin = 3;
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);
}
void loop() {
digitalWrite(ledPin, HIGH);
}
Here, a new variable is declared: name is pin, value is 13, and type is int.
The only difference is that it is declared inside the loop() function. So it is a local variable.
This means that it can only be used inside the function in which it is declared. In this case, only the loop() function knows about this variable, and any changes made to it will not affect any other part of the program.
So doing this inside the loop() function will result in an error: digitalWrite(pin, HIGH);
Commonly used functions in Arduino programming
1. The pinMode() function
pinMode() function is used to configure a pin as input or output. Input means you can then read the incoming voltage/value at this pin, and output means you can get an output voltage at this pin.
For example, in the program above, the line pinMode(ledPin, OUTPUT); configures pin 13 as an output pin.
If you want to configure a pin for input, you will use INPUT instead of OUTPUT.
2. The digitalRead() function
This function reads the value of a digital and analog pin. The value can be either HIGH(5 V) or LOW(0 V).
For example, if you want to read the value of pin 5 connected to a sensor, you would use the following code:
int sensorPin = 5;
void setup() {
pinMode(sensorPin, INPUT);
}
void loop() {
int sensorState = digitalRead(sensorPin);
}
In this example, the value of pin 5 is being read and stored in a variable called sensorPin.
3. The digitalWrite() function
This function writes a value to a digital pin or sends a voltage value to this pin. The value can be either HIGH(5V) or LOW(0V).
For example, if you want to write the value HIGH to pin 13, you would use the following code:
int ledPin = 13;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH);
}
In this example, the value HIGH is being written to pin 13.
4. The analogRead() function
This function is used to read the analog value from an analog pin. The value will be between 0 and 1023.
For example, if you want to read the value of analog pin A0, you would use the following code:
int analogPin = A0;
void setup() {
pinMode(analogPin, INPUT);
}
void loop() {
int sensorValue = analogRead(analogPin);
}
In this example, the value of analog pin A0 is being read and stored in a variable called sensorValue.
Note A: analogRead function can be used only on Analog pins.
Note B: analog value 0 means 0 volts and analog value 1023 means 5 volts.
5. The analogWrite() function
This function is used to write a value to a digital PWM pin(explained in the next section) in Arduino. The value can be between 0 and 255.
The analogWrite function can only be used on digital pins 3, 5, 6, 9, 10, and 11 of the Arduino UNO board. These are special digital pins called PWM pins.
Note A: PWM value 0 means 0 volts, and PWM value 255 means 5 volts. For example, PWM value 127 gives approximately 2.5 volts.
- “analogWrite(3,0)”// Gives output 0 volts to digital pin 3
- “analogWrite(3,255)”// Gives output 5 volts to digital pin 3
- “analogWrite(3,127)”// Gives output 2.5 volts to digital pin 3
Note B: analogWrite() function is not related to analog pins or analogRead function in any way.
For example, if you want to write the value 150 to PWM pin 3, you would use the following code:
int ledPin = 3;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
analogWrite(ledPin, 150);
}
In this example, the value 150 is being written to digital pin 9.
6. The delay() function
This function is used to add a delay in your program. The time is specified in milliseconds.
For example, if you want to add a delay of 1000 milliseconds (1 second), you would use the following code:
int ledPin = 13;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
}
In this example, the delay() function is being used to add a 1 second delay between the HIGH and LOW states of pin 13.
7. The millis() function
This function returns the time in milliseconds since the Arduino board started running the current program.
For example, if you want to know how much time has elapsed since the board started running the program, you would use the following code:
void setup() {
Serial.begin(9600);
}
void loop() {
unsigned long currentMillis = millis();
Serial.println(currentMillis);
delay(1000);
}
In this example, the millis() function is being used to print the time in milliseconds since the board started running the program.
The Serial.begin() and Serial.println() functions are used to initialize the Serial port and to print the value of currentMillis to the serial monitor respectively.
8. Serial commands in Arduino
In order to communicate with the Arduino board from a computer, you will need to use the Serial class.
The Serial class has a lot of useful functions that can be used to communicate with the Arduino board.
The basic commands are explained in this section.
The Serial.begin() function
This function initializes the serial port and sets the baud rate for communication. The baud rate must match with both the computer and the Arduino board. The baud rate of Arduino is set inside the program, whereas the baud rate of the computer is set directly from serial monitor.
For example, if you want to initialize the serial port with a baud rate of 9600, you would use the following code:
void setup() {
Serial.begin(9600);
}
In this example, the Serial port is being initialized with a baud rate of 9600.
What is the baud rate?
Baud rate is the speed of communication between two electronic devices i.e, Arduino and computer. You can’t choose any random baud rate. The supported baud rates are 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 31250, 38400, 57600, and 115200.
Note A: Since Tinkercad is just a simulation, you don’t have to set the baud rate to view data on the serial monitor. Any baud rate will work as long as you are using serial.begin command to initialize serial communication. But while using a real Arduino board, you have to select the proper baud rate from the serial monitor that matches the one you have chosen inside the code.
Note B: This command must be typed inside void setup() before using any other serial commands.
The Serial.print() function
This function is used to print data to the serial port. You can print text/numbers/data using this function. For example, if you want to print “Hello World!” to the serial port, you would use the following code:
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("Hello World!");
}
In this example, the text “Hello World!” is printed to the serial port.
The Serial.println() function
This function is used to print data to the serial port and add a new line after printing it. It works in the same way as the Serial.print() function but adds a new line at the end of the output so that the next data is printed in the next line.
For example, if you want to print “Hello World!” to the serial port and add a new line after it, you would use the following code:
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("Hello World!");
}
In this example, the text “Hello World!” is printed to the serial port followed by a new line.
This is useful when you want to print multiple lines of data to the serial port.
Serial.available() and Serial.read()
Serial.available() function is used to check if data is available on the serial port or not. The Arduino board will wait until some data arrives at the serial port before executing further instructions.
Serial.read() function is used to read data from the serial port. It reads one byte at a time and stores it in a variable that can be used later on in your program.
For example, if you want to read data from serial port and store it in a variable called currentMillis, you would use the following code:
int serialData = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
serialData = Serial.read();
Serial.print("I received: ");
Serial.println((char)serialData);
}
}
In this example, the serial port is checked for available data and if any byte of data is available, it is read and stored in the variable called Serial. Data, and then printed on the serial monitor.
Arduino programming projects for beginners
Just like “Hello World” is always the first example in any programming language, “Blinking the inbuilt LED” is always the first project in Embedded systems.
1. Blinking the LED(inbuilt + external)
The inbuilt LED is connected to pin 13 in Arduino UNO. So to control the LED we have to control this pin. We are going to control the external LED also from this pin.
Components
- LED
- 100-ohm resistor
Note: The digital pins of Arduino give 5 V. So before connecting an external LED, always use a resistor in series. In this case, a resistor is internally connected between the internal LED and pin 13. But for the external LED, you need to connect a 100-ohm resistor.
Circuit diagram
- Connect the Cathode terminal of the LED to the digital pin 13.
- Connect the Anode terminal to the ground through a 100-ohm resistor.
After making the circuit connections, go to the Arduino IDE and paste the program given below.
Program
void setup() {
pinMode(13, OUTPUT); //set digital pin 13 as OUTPUT pin
}
void loop() {
// this loop runs continuously i.e, LED Blinks with 1 second delay
digitalWrite(13, HIGH); // give output 1 or 5v on digital pin 13
delay(1000); // pause or delay this HIGH logic for 1 sec or LED is on for 1 sec
digitalWrite(13, LOW); // give output 0 or 0v on digital pin 13
delay(1000); // pause or delay this LOW logic for 1 sec or LED is off for 1 sec
}
Program explanation
First and foremost, pinMode(13,OUTPUT) sets pin 13 as output. Now for the blinking effect, the LED should turn ON and OFF in a loop.
So inside the void loop(), it is first turned off and then on using the digital write command. The delay of 1 second in between, i.e., on for 1 second, then off for 1 second, and so on, makes the LED blink.
You can also connect an external LED to pin 13 using a 220-ohm resistor, just like in the circuit diagram given above.
Download the program or try this circuit on Tinkercad from here.
2. Using a buzzer with Arduino
A piezo buzzer is an electronic device that produces sound when powered by a voltage source. It utilizes the Piezo effect to generate sounds using a wide range of frequencies and tones.
Components:
- Arduino uno
- Buzzer / piezo speaker
- 100 Ohm resistor
There are only two pins on the buzzer i.e, +ve and -ve or red and black, respectively. If you connect it across a 5 V supply, it will produce a constant sound. You can try this on TinkerCad.
The buzzer can generate different sounds based on the frequency of the square wave signal given to its +ve pin. This is achieved by using predefined “tone” and “notone” functions.
Circuit diagram
- Connect the positive terminal of the buzzer to the digital pin 3 through a resistor.
- Connect the negative terminal to the Ground pin of Arduino.
Program
Upload this program to your Arduino board:
const int Buzzer = 3;// buzzer connected to pin 3
void setup()
{
pinMode(Buzzer, OUTPUT);
}
void loop()
{
tone(Buzzer, 1000);// send 1 KHz signal to pin 3 where buzzer is connected
delay(1000);
tone(Buzzer, 3000);// send 3 KHz signal
delay(1000);
tone(Buzzer, 5000);// send 5 KHz signal
delay(1000);
tone(Buzzer, 10000);// send 10 KHz signal
delay(1000);
noTone(Buzzer);// stop the sound..
delay(2000); // for 2 seconds
}
The tone function automatically generates a square wave signal(50% duty cycle) with frequency defined by you.
Program explanation
const int Buzzer = 3; // buzzer connected to pin 3
This line defines a constant integer Buzzer and sets its value to 3, indicating that the buzzer is connected to pin 3 on the Arduino.
pinMode(Buzzer, OUTPUT);
Sets the buzzer pin as an output pin, allowing the Arduino to send signals to the buzzer.
tone(Buzzer, 1000);
Sends a 1 kHz signal to the buzzer, making it produce a sound at this frequency.
delay(1000);
Pauses the program for 1000 milliseconds (1 second) while the 1 kHz tone plays.
Different frequency signals are given to the buzzer in a loop producing a sound.
Download the program or try this circuit on Tinkercad from here.
3. LED brightness control using a potentiometer
In this project, we are going to control the brightness of the LED using a potentiometer with Arduino.
We will read the analog readings from the potentiometer(wiper terminal position) and based on this value, the PWM duty cycle of the LED is varied.
Components
- 10k potentiometer
- LED
- 220-ohm resistor
Circuit diagram
- Connect one end of the potentiometer to 5V, another leg to the ground, and the middle leg to the analog pin A0 on the Arduino board.
- Connect the LED to the 9th digital pin of Arduino through a 220ohm resistor.
Program
Upload this code to your Arduino board.
// This line sets the potPin constant to analog pin A0
const int potPin = A0;
// This line sets the ledPin constant to digital pin 9
const int ledPin = 9;
void setup() {
// This line sets the mode of the ledPin to OUTPUT
pinMode(ledPin, OUTPUT);
}
void loop() {
// This line reads the value from the analog pin potPin and stores it in the potValue variable
int potValue = analogRead(potPin);
// This line maps the value from the potentiometer (0 to 1023) to the value for the LED (0 to 255)
int ledValue = map(potValue, 0, 1023, 0, 255);
// This line sets the brightness of the LED using PWM
analogWrite(ledPin, ledValue);
}
Program explanation
This program will adjust the brightness of the LED based on the position of the potentiometer. The analogRead function reads the voltage from the analog pin. The map function scales this value from 0-1023 to the range of 0-255. This is necessary because the analogwrite function only accepts values between 0-255.
const int potPin = A0;
potPin is assigned the value A0, indicating that the potentiometer is connected to analog pin A0 of the Arduino.
const int ledPin = 9;
ledPin is assigned the value 9, indicating that the LED is connected to digital pin 9 of the Arduino.
With these steps, you should be able to interface a potentiometer with an Arduino in Tinkercad with ease.
pinMode(ledPin, OUTPUT);
Configures pin 9 as an output, allowing the Arduino to control the LED connected to this pin.
Loop function:
int potValue = analogRead(potPin);
Reads the analog voltage from the potentiometer connected to pin A0.
The returned value (potValue) ranges from 0 to 1023, corresponding to the analog voltage range of 0V to 5V.
int ledValue = map(potValue, 0, 1023, 0, 255);
Maps the potValue from its range of 0-1023 to a new range of 0-255.
This is necessary because the PWM value for analogWrite must be between 0 and 255, where 0 is off and 255 is fully on.
analogWrite(ledPin, ledValue);
Writes the mapped value to the LED pin using Pulse Width Modulation (PWM).
This sets the brightness of the LED based on the position of the position of the potentiometer wiper terminal.
Download the program or try this circuit on Tinkercad from here.
Program 3 has program 2 code in it. Not helpful.
Hi Joe,
Sorry for the wrong code.
That program is now replaced with the right one.
Thank you for pointing it out.